Compare commits
283 Commits
9b28fbcfb6
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b949dff9b | |||
| 773d38d838 | |||
| d987ddea0e | |||
| a4ded78442 | |||
| 831b868d9d | |||
| 771889a99a | |||
| 4d396601f7 | |||
| d29de83116 | |||
| ad276c01f3 | |||
| fb95bf0048 | |||
| d8e6f3ed61 | |||
| 402826ee3d | |||
| 82096e7e6f | |||
| 6ffaaf37ac | |||
| d1747b510e | |||
| bf247726e1 | |||
| 8cb6245560 | |||
| b7eb95056d | |||
| 556abba687 | |||
| 1a8002015a | |||
| 7c63f6c9ba | |||
| 7c5348969b | |||
| 0a9b82544d | |||
| 6080946e74 | |||
| 560fb79bf0 | |||
| 0767a3fe94 | |||
| 0754ed8d69 | |||
| 9aa64b5f4c | |||
| 5e2fbe800c | |||
| 89238bba99 | |||
| 225e64b992 | |||
| 7809ba9741 | |||
| 48ae014def | |||
| 89f02d020b | |||
| 3b76ff43fc | |||
| a0b96b056a | |||
| 93374c3c0a | |||
| 55543af5e1 | |||
| d32eea3523 | |||
| 099303995b | |||
| 44a7dcf089 | |||
| a8f5547c3c | |||
| 41dce076d6 | |||
| 315d85ddcc | |||
| bc827e8b60 | |||
| 8922bb69de | |||
| 4877fec1da | |||
| 73c52ded88 | |||
| f1de8d7ab7 | |||
| 5957d0f45e | |||
| c5405a95c3 | |||
| 5d03e42302 | |||
| d4c20df34f | |||
| 73077295a4 | |||
| c5b1a9372a | |||
| ece2676e38 | |||
| 26259c252d | |||
| 120240ad0c | |||
| ece9938bfb | |||
| a16e21dbfd | |||
| 75905e7036 | |||
| bcaa3e2f25 | |||
| 5448a9ff85 | |||
| bdccb79029 | |||
| a89e936f4d | |||
| fa3e75a333 | |||
| 8bdb942a49 | |||
| 609ce6a439 | |||
| 46a4298a71 | |||
| 9f91683633 | |||
| 5aaac3246d | |||
| 677cb8f054 | |||
| f79dab163d | |||
| 4438c351e2 | |||
| 1a03a1cbba | |||
| 3f61e9ceaf | |||
| b41297f972 | |||
| a5de2dbbb1 | |||
| 1fa36ae62f | |||
| 1353b5571f | |||
| 4e83f27703 | |||
| d5e1732505 | |||
| ae757bee3d | |||
| 6e04b64466 | |||
| f70a7b5a58 | |||
| b6b110254a | |||
| d3e6b5aed5 | |||
| ac84097254 | |||
| 971bf165cc | |||
| f1faa0d435 | |||
| 9dbb1d38d8 | |||
| e908e35530 | |||
| b51f22cfba | |||
| 764464e785 | |||
| cfd344f48c | |||
| 4dc7ff7df7 | |||
| e9aad74df6 | |||
| e768f53ccc | |||
| b0e2e112fc | |||
| 28eba8a3ea | |||
| 7eb6a4db78 | |||
| 7dc03f3bc0 | |||
| 8d91bbeb31 | |||
| 182f8bf74c | |||
| a88567fea6 | |||
| e53cea7a82 | |||
| e88ea7917f | |||
| 99585a1c0e | |||
| d327a5146c | |||
| 4276ca890b | |||
| 3a121f6085 | |||
| 5a25b33258 | |||
| b0deb62c82 | |||
| a2ecc895de | |||
| 1e6ddddf1f | |||
| c54adf1eda | |||
| 5e0348de1d | |||
| 8f18166dbf | |||
| 8f1af536ed | |||
| 180dea60c1 | |||
| 9df391b42c | |||
| 4225b49e58 | |||
| 5a915ebdd1 | |||
| fd71f5a107 | |||
| 9405914d88 | |||
| 39432ac588 | |||
| 4c22cfaf19 | |||
| c8bc7103ba | |||
| 3eeb314dc2 | |||
| 0ddb34dd20 | |||
| 444cc70b56 | |||
| 85bf329d93 | |||
| 3544b6ee78 | |||
| 0e90f19377 | |||
| f9c4d7edb2 | |||
| b7372dec1f | |||
| 21e9823008 | |||
| 583408032d | |||
| ea0ea233a8 | |||
| 7356d0e810 | |||
| b1e3e23325 | |||
| a298d0ee1c | |||
| 249ae1164d | |||
| c6e3f1db64 | |||
| bd722933dc | |||
| f6277aa339 | |||
| 2e226e60f5 | |||
| 68649223d9 | |||
| 9d7c224ad2 | |||
| 47aec287aa | |||
| 5dfca873dd | |||
| 62592c29ae | |||
| 870eeec82a | |||
| deff2264a6 | |||
| 2b28d2079c | |||
| c7ac431deb | |||
| 8a159f1b79 | |||
| 70ea56280c | |||
| bcd6b39356 | |||
| 1fb97cfccc | |||
| 0924b1a980 | |||
| 807e88f929 | |||
| b8a4c9b727 | |||
| d2dc568794 | |||
| a537974edf | |||
| ef3731ba48 | |||
| ddced87dc6 | |||
| 7ab8e9703b | |||
| aaaae09bd2 | |||
| 8061a60fe5 | |||
| 87425b3276 | |||
| 2af169fa60 | |||
| 3558c67fd7 | |||
| f55807fa7d | |||
| b6c50a38aa | |||
| caed5091f0 | |||
| 769597d769 | |||
| 241870fe48 | |||
| e817801e14 | |||
| aef5454202 | |||
| 9a94e3b09e | |||
| fba0b63214 | |||
| e5296e79dc | |||
| 61e34d343a | |||
| 126e640731 | |||
| 4e15e9f630 | |||
| 4bee06addb | |||
| a99755a5db | |||
| fef3b76a31 | |||
| e37aade69f | |||
| fe50ea3d30 | |||
| 95fa37ebdf | |||
| e1f99158aa | |||
| 95008788f3 | |||
| f5ff03260b | |||
| aa77f2051a | |||
| 4704d33b4a | |||
| 18b9707e44 | |||
| 1bb9da16d4 | |||
| 3188064335 | |||
| 04b05617b8 | |||
| 9933c180b7 | |||
| 86d9879a6d | |||
| d9289008f6 | |||
| 015f689d9b | |||
| 15cdfe6f92 | |||
| e7bf07c2ad | |||
| ac65c68e18 | |||
| cf929557fe | |||
| cc58d06723 | |||
| b3eb9d297a | |||
| f6f06d841c | |||
| 50e518095e | |||
| fdd0d7c8e1 | |||
| 0639d1fe83 | |||
| a2d394029a | |||
| 5f8676f962 | |||
| 48885dba83 | |||
| af21e50d9f | |||
| a573179714 | |||
| 66640d1fd0 | |||
| 001db35cef | |||
| 81a0b5a038 | |||
| 7260e5c115 | |||
| 91247a7c69 | |||
| 4a2b142061 | |||
| b5a15dd9f2 | |||
| 86041c0d05 | |||
| e04776460d | |||
| 586551aec0 | |||
| 8ff93e3698 | |||
| 2b6f29e775 | |||
| 81efaedbc2 | |||
| cb15d30980 | |||
| 798dfa3fe0 | |||
| 8b52572fad | |||
| 577ae1aabe | |||
| e20964ae0d | |||
| 999f8a80f9 | |||
| 3974cec967 | |||
| 82b9744024 | |||
| a525c71baa | |||
| d79b1faa8f | |||
| e83fa4c2e9 | |||
| bc67146d86 | |||
| a18d44bd0a | |||
| 6c3292861a | |||
| 3a5b5721e4 | |||
| 07e0270599 | |||
| 32e47e4566 | |||
| d2eac52a47 | |||
| 8249b3fe3e | |||
| 3ab0998793 | |||
| 0986233d9b | |||
| bfffdee2a8 | |||
| 97743f6974 | |||
| 34344cbf83 | |||
| cd5413125d | |||
| 820ca6981c | |||
| f703519838 | |||
| 5041873c2b | |||
| 61c6697c87 | |||
| 5d556b882d | |||
| adad5cb7e9 | |||
| 60405ef0aa | |||
| 62428cd2d4 | |||
| 4874f2a0a3 | |||
| dc7909e247 | |||
| aa0c5403a1 | |||
| 98965274b8 | |||
| d1f342e3d0 | |||
| 2aa095c158 | |||
| ef0098d5cc | |||
| 8b86bd573e | |||
| 9db8b34181 | |||
| f74563bb36 | |||
| b335867b30 | |||
| a66a3f7cb0 | |||
| 40d740d6e0 | |||
| 5a789fb0c2 | |||
| cab4c6778f | |||
| 4da8806bfc | |||
| d5648315a0 |
@@ -0,0 +1,85 @@
|
||||
name: ci-cd-vm
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
# Everything lives on the same Ubuntu VM (Gitea, the registry, the build, and the
|
||||
# runtime share one Docker daemon), so a single job on the `ubuntu` runner does
|
||||
# test -> build -> push -> deploy. No cross-machine pull is needed; deploy reuses
|
||||
# the images just built in the local Docker.
|
||||
jobs:
|
||||
ci-cd:
|
||||
runs-on: ubuntu
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
env:
|
||||
REGISTRY: git.golife.love/chrischen
|
||||
DEPLOY_DIR: /home/chris/docker/rolac
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Test API
|
||||
run: dotnet test API/ROLAC.API.Tests/ROLAC.API.Tests.csproj -c Release
|
||||
|
||||
- name: Registry login
|
||||
run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.golife.love -u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
|
||||
- name: Build images
|
||||
run: |
|
||||
docker build -t "$REGISTRY/rolac-api:latest" -t "$REGISTRY/rolac-api:${{ github.sha }}" ./API
|
||||
docker build \
|
||||
--build-arg KENDO_UI_LICENSE="${{ secrets.KENDO_UI_LICENSE }}" \
|
||||
-t "$REGISTRY/rolac-app:latest" -t "$REGISTRY/rolac-app:${{ github.sha }}" ./APP
|
||||
|
||||
- name: Push images
|
||||
run: |
|
||||
docker push --all-tags "$REGISTRY/rolac-api"
|
||||
docker push --all-tags "$REGISTRY/rolac-app"
|
||||
|
||||
- name: Sync compose + nginx to deploy dir
|
||||
run: |
|
||||
mkdir -p "$DEPLOY_DIR/nginx/conf.d" "$DEPLOY_DIR/data/api-storage"
|
||||
cp deploy/vm/docker-compose.yml "$DEPLOY_DIR/docker-compose.yml"
|
||||
cp deploy/vm/nginx/conf.d/rolac.conf "$DEPLOY_DIR/nginx/conf.d/rolac.conf"
|
||||
|
||||
- name: Deploy
|
||||
run: |
|
||||
cd "$DEPLOY_DIR"
|
||||
export TAG=${{ github.sha }}
|
||||
docker compose up -d
|
||||
sleep 5
|
||||
curl -fsS http://localhost:8080/api/health
|
||||
|
||||
# Always runs (success or failure) so the team gets a build result in Rocket.Chat.
|
||||
- name: Notify Rocket.Chat
|
||||
if: always()
|
||||
env:
|
||||
JOB_STATUS: ${{ job.status }}
|
||||
REPO: ${{ github.repository }}
|
||||
REF: ${{ github.ref_name }}
|
||||
SHA: ${{ github.sha }}
|
||||
ACTOR: ${{ github.actor }}
|
||||
COMMIT_URL: ${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }}
|
||||
WEBHOOK: ${{ secrets.ROCKETCHAT_WEBHOOK }}
|
||||
run: |
|
||||
if [ "$JOB_STATUS" = "success" ]; then
|
||||
STATUS_TEXT="✅ Build succeeded"
|
||||
COLOR="#2ecc71"
|
||||
else
|
||||
STATUS_TEXT="❌ Build failed"
|
||||
COLOR="#e74c3c"
|
||||
fi
|
||||
SHORT_SHA="${SHA:0:7}"
|
||||
curl -fsS -X POST -H 'Content-Type: application/json' --data @- "$WEBHOOK" <<JSON
|
||||
{
|
||||
"attachments": [
|
||||
{
|
||||
"title": "$REPO — $STATUS_TEXT",
|
||||
"title_link": "$COMMIT_URL",
|
||||
"color": "$COLOR",
|
||||
"text": "Branch *$REF* · commit $SHORT_SHA · by $ACTOR"
|
||||
}
|
||||
]
|
||||
}
|
||||
JSON
|
||||
@@ -0,0 +1,92 @@
|
||||
name: ci-cd
|
||||
on:
|
||||
push:
|
||||
branches: [azure-deploy]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with: { dotnet-version: '8.0.x' }
|
||||
- run: dotnet test API/ROLAC.API.Tests/ROLAC.API.Tests.csproj -c Release
|
||||
|
||||
build-push:
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.golife.love
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
- uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./API
|
||||
push: true
|
||||
tags: |
|
||||
git.golife.love/chrischen/rolac-api:latest
|
||||
git.golife.love/chrischen/rolac-api:${{ github.sha }}
|
||||
- uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./APP
|
||||
push: true
|
||||
tags: |
|
||||
git.golife.love/chrischen/rolac-app:latest
|
||||
git.golife.love/chrischen/rolac-app:${{ github.sha }}
|
||||
|
||||
deploy:
|
||||
needs: build-push
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: appleboy/ssh-action@v1
|
||||
with:
|
||||
host: ${{ secrets.VM_HOST }}
|
||||
username: ${{ secrets.VM_USER }}
|
||||
key: ${{ secrets.VM_SSH_KEY }}
|
||||
script: |
|
||||
cd /opt/rolac/deploy
|
||||
export TAG=${{ github.sha }}
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
curl -fsS https://manage.rolac.org/api/health
|
||||
|
||||
# Always runs (success or failure) so the team gets a build result in Rocket.Chat.
|
||||
# A failed or skipped upstream job (skipped means an earlier job failed) reports as failed.
|
||||
notify:
|
||||
needs: [test, build-push, deploy]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Notify Rocket.Chat
|
||||
env:
|
||||
BUILD_FAILED: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') }}
|
||||
REPO: ${{ github.repository }}
|
||||
REF: ${{ github.ref_name }}
|
||||
SHA: ${{ github.sha }}
|
||||
ACTOR: ${{ github.actor }}
|
||||
COMMIT_URL: ${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }}
|
||||
WEBHOOK: ${{ secrets.ROCKETCHAT_WEBHOOK }}
|
||||
run: |
|
||||
if [ "$BUILD_FAILED" = "true" ]; then
|
||||
STATUS_TEXT="❌ Build failed"
|
||||
COLOR="#e74c3c"
|
||||
else
|
||||
STATUS_TEXT="✅ Build succeeded"
|
||||
COLOR="#2ecc71"
|
||||
fi
|
||||
SHORT_SHA="${SHA:0:7}"
|
||||
curl -fsS -X POST -H 'Content-Type: application/json' --data @- "$WEBHOOK" <<JSON
|
||||
{
|
||||
"attachments": [
|
||||
{
|
||||
"title": "$REPO — $STATUS_TEXT",
|
||||
"title_link": "$COMMIT_URL",
|
||||
"color": "$COLOR",
|
||||
"text": "Branch *$REF* · commit $SHORT_SHA · by $ACTOR"
|
||||
}
|
||||
]
|
||||
}
|
||||
JSON
|
||||
@@ -91,3 +91,6 @@ logs/
|
||||
*.log
|
||||
*.tmp
|
||||
*.temp
|
||||
/.claude
|
||||
/API/ROLAC.API/bin-verify
|
||||
API/ROLAC.API/App_Data/
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
**/bin
|
||||
**/obj
|
||||
**/appsettings.Development.json
|
||||
**/appsettings.*.local.json
|
||||
ROLAC.API.Tests/
|
||||
.git
|
||||
*.user
|
||||
@@ -0,0 +1,35 @@
|
||||
# ---- build ----
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
WORKDIR /src
|
||||
# nuget.config carries the DevExpress licensed feed so restore resolves 24.1.3
|
||||
# (the public feed only offers the trial 25.x, which renamed TableBorderLineStyle).
|
||||
COPY nuget.config ./
|
||||
COPY ROLAC.API/ROLAC.API.csproj ROLAC.API/
|
||||
RUN dotnet restore ROLAC.API/ROLAC.API.csproj --configfile nuget.config
|
||||
COPY ROLAC.API/ ROLAC.API/
|
||||
RUN dotnet publish ROLAC.API/ROLAC.API.csproj -c Release -o /app/publish /p:UseAppHost=false --no-restore
|
||||
|
||||
# ---- runtime ----
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
|
||||
WORKDIR /app
|
||||
ENV ASPNETCORE_ENVIRONMENT=Production \
|
||||
ASPNETCORE_HTTP_PORTS=8080
|
||||
# curl: used by the HEALTHCHECK (not present in the base image)
|
||||
# libfontconfig1 + fonts: required by DevExpress.Drawing's Skia backend for PDF text
|
||||
# rendering. fonts-noto-cjk supplies the Chinese glyphs used in the receipt PDF.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
curl \
|
||||
libfontconfig1 \
|
||||
fontconfig \
|
||||
fonts-dejavu \
|
||||
fonts-noto-cjk \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=build /app/publish .
|
||||
# storage dir created + owned for the non-root app user
|
||||
RUN mkdir -p /app/App_Data/storage && chown -R app:app /app/App_Data
|
||||
USER app
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s \
|
||||
CMD curl -fsS http://localhost:8080/health || exit 1
|
||||
ENTRYPOINT ["dotnet", "ROLAC.API.dll"]
|
||||
@@ -0,0 +1,64 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Moq;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Authorization;
|
||||
|
||||
public class PermissionAuthorizationHandlerTests
|
||||
{
|
||||
private static ClaimsPrincipal UserWithRoles(params string[] roles)
|
||||
{
|
||||
var claims = roles.Select(role => new Claim("role", role));
|
||||
return new ClaimsPrincipal(new ClaimsIdentity(claims, authenticationType: "test"));
|
||||
}
|
||||
|
||||
private static async Task<bool> EvaluateAsync(
|
||||
ClaimsPrincipal user, PermissionRequirement requirement, IPermissionService permissions)
|
||||
{
|
||||
var handler = new PermissionAuthorizationHandler(permissions);
|
||||
var context = new AuthorizationHandlerContext([requirement], user, resource: null);
|
||||
await handler.HandleAsync(context);
|
||||
return context.HasSucceeded;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SuperAdmin_AlwaysSucceeds_WithoutConsultingMatrix()
|
||||
{
|
||||
var permissions = new Mock<IPermissionService>(MockBehavior.Strict); // must NOT be called
|
||||
var requirement = new PermissionRequirement(Modules.Members, PermissionActions.Delete);
|
||||
|
||||
var succeeded = await EvaluateAsync(UserWithRoles("super_admin"), requirement, permissions.Object);
|
||||
|
||||
Assert.True(succeeded);
|
||||
permissions.Verify(p => p.HasPermissionAsync(It.IsAny<IEnumerable<string>>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RoleWithPermission_Succeeds()
|
||||
{
|
||||
var permissions = new Mock<IPermissionService>();
|
||||
permissions.Setup(p => p.HasPermissionAsync(It.IsAny<IEnumerable<string>>(), Modules.Members, PermissionActions.Write))
|
||||
.ReturnsAsync(true);
|
||||
var requirement = new PermissionRequirement(Modules.Members, PermissionActions.Write);
|
||||
|
||||
var succeeded = await EvaluateAsync(UserWithRoles("secretary"), requirement, permissions.Object);
|
||||
|
||||
Assert.True(succeeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RoleWithoutPermission_Fails()
|
||||
{
|
||||
var permissions = new Mock<IPermissionService>();
|
||||
permissions.Setup(p => p.HasPermissionAsync(It.IsAny<IEnumerable<string>>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ReturnsAsync(false);
|
||||
var requirement = new PermissionRequirement(Modules.Givings, PermissionActions.Write);
|
||||
|
||||
var succeeded = await EvaluateAsync(UserWithRoles("member"), requirement, permissions.Object);
|
||||
|
||||
Assert.False(succeeded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.Entities;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Data;
|
||||
|
||||
public class AuditInterceptorTests
|
||||
{
|
||||
private static AppDbContext BuildDb(AuditSaveChangesInterceptor interceptor)
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(interceptor)
|
||||
.Options;
|
||||
return new AppDbContext(options);
|
||||
}
|
||||
|
||||
private static AuditSaveChangesInterceptor BuildInterceptor(string userId = "user-1")
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(mock.Object));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Added_SetsCreatedAtAndCreatedBy()
|
||||
{
|
||||
var interceptor = BuildInterceptor("user-42");
|
||||
using var db = BuildDb(interceptor);
|
||||
|
||||
var member = new Member { FirstName_en = "A", LastName_en = "B" };
|
||||
db.Members.Add(member);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
Assert.Equal("user-42", member.CreatedBy);
|
||||
Assert.Equal("user-42", member.UpdatedBy);
|
||||
Assert.True(member.CreatedAt > DateTimeOffset.UtcNow.AddSeconds(-5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Modified_UpdatesUpdatedAtAndUpdatedBy()
|
||||
{
|
||||
var interceptor = BuildInterceptor("user-1");
|
||||
using var db = BuildDb(interceptor);
|
||||
|
||||
var member = new Member { FirstName_en = "A", LastName_en = "B" };
|
||||
db.Members.Add(member);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
member.NickName = "Nick";
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
Assert.Equal("user-1", member.UpdatedBy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.2">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.11" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="8.0.11" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ROLAC.API\ROLAC.API.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,29 @@
|
||||
using ROLAC.API.Services.Disbursement;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class AmountToWordsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(0, "Zero and 00/100 Dollars")]
|
||||
[InlineData(0.05, "Zero and 05/100 Dollars")]
|
||||
[InlineData(1, "One and 00/100 Dollars")]
|
||||
[InlineData(19, "Nineteen and 00/100 Dollars")]
|
||||
[InlineData(20, "Twenty and 00/100 Dollars")]
|
||||
[InlineData(21, "Twenty-One and 00/100 Dollars")]
|
||||
[InlineData(100, "One Hundred and 00/100 Dollars")]
|
||||
[InlineData(115, "One Hundred Fifteen and 00/100 Dollars")]
|
||||
[InlineData(1234.56, "One Thousand Two Hundred Thirty-Four and 56/100 Dollars")]
|
||||
[InlineData(1000000, "One Million and 00/100 Dollars")]
|
||||
public void Convert_FormatsExpectedWords(double amount, string expected)
|
||||
{
|
||||
Assert.Equal(expected, AmountToWords.Convert((decimal)amount));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convert_RoundsCentsHalfUp()
|
||||
{
|
||||
Assert.Equal("One and 00/100 Dollars", AmountToWords.Convert(0.999m));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.DTOs.Auth;
|
||||
using ROLAC.API.DTOs.Permissions;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class AuthServiceTests
|
||||
{
|
||||
// -----------------------------------------------------------------------
|
||||
// Factory helpers
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private static AppDbContext BuildDb() =>
|
||||
new(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options);
|
||||
|
||||
private static IConfiguration BuildConfig() =>
|
||||
new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
{ "Jwt:RefreshTokenExpiryDays", "30" },
|
||||
})
|
||||
.Build();
|
||||
|
||||
/// <summary>Creates a <see cref="UserManager{TUser}"/> mock with sensible defaults.</summary>
|
||||
private static Mock<UserManager<AppUser>> BuildUserManager(
|
||||
AppUser? findResult = null,
|
||||
bool passwordOk = true,
|
||||
IList<string>? roles = null,
|
||||
IdentityResult? changePasswordResult = null)
|
||||
{
|
||||
var store = new Mock<IUserStore<AppUser>>();
|
||||
// Remaining ctor params are all optional; Moq passes them via reflection.
|
||||
#pragma warning disable CS8625
|
||||
var mgr = new Mock<UserManager<AppUser>>(
|
||||
store.Object, null, null, null, null, null, null, null, null);
|
||||
#pragma warning restore CS8625
|
||||
|
||||
mgr.Setup(m => m.FindByEmailAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync(findResult);
|
||||
mgr.Setup(m => m.FindByIdAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync(findResult);
|
||||
mgr.Setup(m => m.CheckPasswordAsync(It.IsAny<AppUser>(), It.IsAny<string>()))
|
||||
.ReturnsAsync(passwordOk);
|
||||
mgr.Setup(m => m.GetRolesAsync(It.IsAny<AppUser>()))
|
||||
.ReturnsAsync(roles ?? new List<string> { "member" });
|
||||
mgr.Setup(m => m.UpdateAsync(It.IsAny<AppUser>()))
|
||||
.ReturnsAsync(IdentityResult.Success);
|
||||
mgr.Setup(m => m.ChangePasswordAsync(
|
||||
It.IsAny<AppUser>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ReturnsAsync(changePasswordResult ?? IdentityResult.Success);
|
||||
|
||||
return mgr;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ITokenService mock: GenerateAccessToken → "access-token",
|
||||
/// GenerateRefreshToken → "raw-refresh", HashToken(x) → "hash:{x}".
|
||||
/// </summary>
|
||||
private static Mock<ITokenService> BuildTokenService()
|
||||
{
|
||||
var svc = new Mock<ITokenService>();
|
||||
svc.Setup(t => t.GenerateAccessToken(It.IsAny<AppUser>(), It.IsAny<IList<string>>()))
|
||||
.Returns("access-token");
|
||||
svc.Setup(t => t.GenerateRefreshToken())
|
||||
.Returns("raw-refresh");
|
||||
svc.Setup(t => t.HashToken(It.IsAny<string>()))
|
||||
.Returns<string>(s => $"hash:{s}");
|
||||
return svc;
|
||||
}
|
||||
|
||||
/// <summary>IPermissionService mock: returns an empty effective-permission map.</summary>
|
||||
private static Mock<IPermissionService> BuildPermissionService()
|
||||
{
|
||||
var svc = new Mock<IPermissionService>();
|
||||
svc.Setup(p => p.GetEffectivePermissionsAsync(It.IsAny<IEnumerable<string>>()))
|
||||
.ReturnsAsync(new Dictionary<string, ModuleActions>());
|
||||
return svc;
|
||||
}
|
||||
|
||||
private static AuthService BuildSut(
|
||||
Mock<UserManager<AppUser>> umMock,
|
||||
Mock<ITokenService> tsMock,
|
||||
AppDbContext db)
|
||||
=> new(umMock.Object, tsMock.Object, db, BuildPermissionService().Object,
|
||||
ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance, BuildConfig());
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Login tests
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task Login_ValidCredentials_ReturnsAccessTokenAndRefreshToken()
|
||||
{
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = true };
|
||||
var um = BuildUserManager(findResult: user, roles: new[] { "member" });
|
||||
var ts = BuildTokenService();
|
||||
var db = BuildDb();
|
||||
var sut = BuildSut(um, ts, db);
|
||||
|
||||
var (response, raw) = await sut.LoginAsync(new LoginRequest { Email = "a@b.com", Password = "P@ssw0rd!" });
|
||||
|
||||
Assert.Equal("access-token", response.AccessToken);
|
||||
Assert.Equal(900, response.ExpiresIn);
|
||||
Assert.Equal("u1", response.User.Id);
|
||||
Assert.Equal("a@b.com", response.User.Email);
|
||||
Assert.Contains("member", response.User.Roles);
|
||||
Assert.Equal("raw-refresh", raw);
|
||||
|
||||
// Persisted in DB
|
||||
var stored = db.RefreshTokens.Single();
|
||||
Assert.Equal("hash:raw-refresh", stored.TokenHash);
|
||||
Assert.Equal("u1", stored.UserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_UnknownEmail_ThrowsUnauthorized()
|
||||
{
|
||||
var um = BuildUserManager(findResult: null);
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, BuildDb());
|
||||
|
||||
await Assert.ThrowsAsync<UnauthorizedAccessException>(
|
||||
() => sut.LoginAsync(new LoginRequest { Email = "nope@b.com", Password = "P@ssw0rd!" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_WrongPassword_ThrowsUnauthorized()
|
||||
{
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = true };
|
||||
var um = BuildUserManager(findResult: user, passwordOk: false);
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, BuildDb());
|
||||
|
||||
await Assert.ThrowsAsync<UnauthorizedAccessException>(
|
||||
() => sut.LoginAsync(new LoginRequest { Email = "a@b.com", Password = "wrong" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_InactiveAccount_ThrowsUnauthorized()
|
||||
{
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = false };
|
||||
var um = BuildUserManager(findResult: user, passwordOk: true);
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, BuildDb());
|
||||
|
||||
await Assert.ThrowsAsync<UnauthorizedAccessException>(
|
||||
() => sut.LoginAsync(new LoginRequest { Email = "a@b.com", Password = "P@ssw0rd!" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_Success_UpdatesLastLoginAt()
|
||||
{
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = true };
|
||||
var um = BuildUserManager(findResult: user);
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, BuildDb());
|
||||
|
||||
await sut.LoginAsync(new LoginRequest { Email = "a@b.com", Password = "P@ssw0rd!" });
|
||||
|
||||
um.Verify(m => m.UpdateAsync(It.Is<AppUser>(u => u.LastLoginAt != null)), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_LinkedMember_ReturnsMemberInfo()
|
||||
{
|
||||
var db = BuildDb();
|
||||
db.Members.Add(new Member
|
||||
{
|
||||
Id = 7,
|
||||
NickName = "Johnny",
|
||||
FirstName_en = "John",
|
||||
LastName_en = "Chen",
|
||||
LastName_zh = "陳",
|
||||
CreatedBy = "seed",
|
||||
UpdatedBy = "seed",
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = true, MemberId = 7 };
|
||||
var um = BuildUserManager(findResult: user);
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, db);
|
||||
|
||||
var (response, _) = await sut.LoginAsync(new LoginRequest { Email = "a@b.com", Password = "P@ssw0rd!" });
|
||||
|
||||
Assert.NotNull(response.User.MemberInfo);
|
||||
Assert.Equal(7, response.User.MemberInfo!.Id);
|
||||
Assert.Equal("Johnny", response.User.MemberInfo.NickName);
|
||||
Assert.Equal("Chen", response.User.MemberInfo.LastName_en);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_AdminOnlyAccount_ReturnsNullMemberInfo()
|
||||
{
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = true, MemberId = null };
|
||||
var um = BuildUserManager(findResult: user);
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, BuildDb());
|
||||
|
||||
var (response, _) = await sut.LoginAsync(new LoginRequest { Email = "a@b.com", Password = "P@ssw0rd!" });
|
||||
|
||||
Assert.Null(response.User.MemberInfo);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Refresh tests
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task Refresh_ValidToken_RotatesRefreshToken()
|
||||
{
|
||||
const string rawOld = "old-raw";
|
||||
const string rawNew = "raw-refresh"; // what BuildTokenService returns
|
||||
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = true };
|
||||
var um = BuildUserManager(findResult: user);
|
||||
var ts = BuildTokenService();
|
||||
var db = BuildDb();
|
||||
|
||||
// Seed an active token
|
||||
db.RefreshTokens.Add(new RefreshToken
|
||||
{
|
||||
UserId = "u1",
|
||||
TokenHash = "hash:old-raw",
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(30),
|
||||
CreatedAt = DateTime.UtcNow.AddHours(-1),
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var sut = BuildSut(um, ts, db);
|
||||
var (response, newRaw) = await sut.RefreshAsync(rawOld);
|
||||
|
||||
Assert.Equal("access-token", response.AccessToken);
|
||||
Assert.Equal(rawNew, newRaw);
|
||||
|
||||
// Old token revoked
|
||||
var old = db.RefreshTokens.First(rt => rt.TokenHash == "hash:old-raw");
|
||||
Assert.NotNull(old.RevokedAt);
|
||||
Assert.Equal("hash:raw-refresh", old.ReplacedByHash);
|
||||
|
||||
// New token stored
|
||||
var newTok = db.RefreshTokens.First(rt => rt.TokenHash == "hash:raw-refresh");
|
||||
Assert.Null(newTok.RevokedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Refresh_UnknownToken_ThrowsUnauthorized()
|
||||
{
|
||||
var um = BuildUserManager();
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, BuildDb());
|
||||
|
||||
await Assert.ThrowsAsync<UnauthorizedAccessException>(
|
||||
() => sut.RefreshAsync("no-such-token"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Refresh_ExpiredToken_ThrowsUnauthorized()
|
||||
{
|
||||
var db = BuildDb();
|
||||
db.RefreshTokens.Add(new RefreshToken
|
||||
{
|
||||
UserId = "u1",
|
||||
TokenHash = "hash:expired-raw",
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(-1), // already expired
|
||||
CreatedAt = DateTime.UtcNow.AddDays(-31),
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var um = BuildUserManager();
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, db);
|
||||
|
||||
await Assert.ThrowsAsync<UnauthorizedAccessException>(
|
||||
() => sut.RefreshAsync("expired-raw"));
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Logout tests
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task Logout_ValidToken_RevokesRefreshToken()
|
||||
{
|
||||
const string raw = "my-raw-token";
|
||||
|
||||
var db = BuildDb();
|
||||
db.RefreshTokens.Add(new RefreshToken
|
||||
{
|
||||
UserId = "u1",
|
||||
TokenHash = "hash:my-raw-token",
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(30),
|
||||
CreatedAt = DateTime.UtcNow.AddHours(-1),
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var um = BuildUserManager();
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, db);
|
||||
|
||||
await sut.LogoutAsync(raw);
|
||||
|
||||
var token = db.RefreshTokens.Single();
|
||||
Assert.NotNull(token.RevokedAt);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Change password tests
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_ValidRequest_Succeeds()
|
||||
{
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = true };
|
||||
var um = BuildUserManager(findResult: user);
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, BuildDb());
|
||||
|
||||
var result = await sut.ChangePasswordAsync("u1", "Old1234!", "New1234!", null);
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
um.Verify(m => m.ChangePasswordAsync(user, "Old1234!", "New1234!"), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_UnknownUser_Fails()
|
||||
{
|
||||
var um = BuildUserManager(findResult: null);
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, BuildDb());
|
||||
|
||||
var result = await sut.ChangePasswordAsync("missing", "Old1234!", "New1234!", null);
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
um.Verify(m => m.ChangePasswordAsync(
|
||||
It.IsAny<AppUser>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_WrongCurrentPassword_ReturnsFailure()
|
||||
{
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = true };
|
||||
var failed = IdentityResult.Failed(new IdentityError { Description = "Incorrect password." });
|
||||
var um = BuildUserManager(findResult: user, changePasswordResult: failed);
|
||||
var ts = BuildTokenService();
|
||||
var sut = BuildSut(um, ts, BuildDb());
|
||||
|
||||
var result = await sut.ChangePasswordAsync("u1", "WrongOld!", "New1234!", null);
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangePassword_Success_RevokesOtherSessionsButKeepsCurrent()
|
||||
{
|
||||
var user = new AppUser { Id = "u1", Email = "a@b.com", UserName = "a@b.com", IsActive = true };
|
||||
var um = BuildUserManager(findResult: user);
|
||||
var ts = BuildTokenService(); // HashToken(x) => "hash:{x}"
|
||||
var db = BuildDb();
|
||||
|
||||
// Current session token (raw "current-raw" => "hash:current-raw")
|
||||
db.RefreshTokens.Add(new RefreshToken
|
||||
{
|
||||
UserId = "u1",
|
||||
TokenHash = "hash:current-raw",
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(30),
|
||||
CreatedAt = DateTime.UtcNow.AddHours(-1),
|
||||
});
|
||||
// Another active session on a different device
|
||||
db.RefreshTokens.Add(new RefreshToken
|
||||
{
|
||||
UserId = "u1",
|
||||
TokenHash = "hash:other-device",
|
||||
ExpiresAt = DateTime.UtcNow.AddDays(30),
|
||||
CreatedAt = DateTime.UtcNow.AddHours(-2),
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var sut = BuildSut(um, ts, db);
|
||||
await sut.ChangePasswordAsync("u1", "Old1234!", "New1234!", "current-raw");
|
||||
|
||||
var current = db.RefreshTokens.Single(rt => rt.TokenHash == "hash:current-raw");
|
||||
var other = db.RefreshTokens.Single(rt => rt.TokenHash == "hash:other-device");
|
||||
Assert.Null(current.RevokedAt); // current session preserved
|
||||
Assert.NotNull(other.RevokedAt); // other session revoked
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Services.Ai;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class ChurchAiConfigProviderTests
|
||||
{
|
||||
private static AppDbContext NewDb() =>
|
||||
new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_returns_defaults_when_no_profile_row()
|
||||
{
|
||||
using var db = NewDb(); // empty DB, no ChurchProfile
|
||||
|
||||
var cfg = await new ChurchAiConfigProvider(db).GetAsync();
|
||||
|
||||
Assert.Equal("Claude", cfg.Provider);
|
||||
Assert.Equal("claude-haiku-4-5-20251001", cfg.ClaudeModel);
|
||||
Assert.Equal("gemini-2.5-flash-lite", cfg.GeminiModel);
|
||||
Assert.Null(cfg.ClaudeApiKey);
|
||||
Assert.Null(cfg.GeminiApiKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Disbursement;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class ChurchProfileServiceTests
|
||||
{
|
||||
// ChurchProfile is auditable, so the InMemory store rejects saves unless the
|
||||
// required CreatedBy/UpdatedBy fields are populated. Wire the same audit
|
||||
// interceptor the app uses so seeded entities save cleanly.
|
||||
private static AppDbContext NewDb()
|
||||
{
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "test-user") })),
|
||||
};
|
||||
var httpContextAccessor = new Mock<IHttpContextAccessor>();
|
||||
httpContextAccessor.Setup(accessor => accessor.HttpContext).Returns(httpContext);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.ConfigureWarnings(warnings => warnings.Ignore(InMemoryEventId.TransactionIgnoredWarning))
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new CurrentUserAccessor(httpContextAccessor.Object)))
|
||||
.Options);
|
||||
}
|
||||
|
||||
private static UpdateChurchProfileRequest Req(
|
||||
string provider = "Claude", string? claudeKey = null, string? geminiKey = null,
|
||||
string? claudeModel = "m", string? geminiModel = "m") =>
|
||||
new()
|
||||
{
|
||||
Name = "C", NextCheckNumber = 1001, AiProvider = provider,
|
||||
ClaudeModel = claudeModel, GeminiModel = geminiModel,
|
||||
ClaudeApiKey = claudeKey, GeminiApiKey = geminiKey,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_masks_stored_api_keys()
|
||||
{
|
||||
using var db = NewDb();
|
||||
db.ChurchProfiles.Add(new ChurchProfile
|
||||
{
|
||||
Name = "C", ClaudeApiKey = "sk-ant-abcd1234", GeminiApiKey = "AIzaXYZ9876",
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var dto = await new ChurchProfileService(db).GetAsync();
|
||||
|
||||
Assert.Equal("••••••1234", dto.ClaudeApiKeyMasked);
|
||||
Assert.Equal("••••••9876", dto.GeminiApiKeyMasked);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_blank_key_keeps_existing()
|
||||
{
|
||||
using var db = NewDb();
|
||||
db.ChurchProfiles.Add(new ChurchProfile { Name = "C", ClaudeApiKey = "sk-keep-0001" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
await new ChurchProfileService(db).UpdateAsync(Req(claudeKey: null));
|
||||
|
||||
var p = await db.ChurchProfiles.FirstAsync();
|
||||
Assert.Equal("sk-keep-0001", p.ClaudeApiKey);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_nonblank_key_replaces()
|
||||
{
|
||||
using var db = NewDb();
|
||||
db.ChurchProfiles.Add(new ChurchProfile { Name = "C", ClaudeApiKey = "sk-keep-0001" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
await new ChurchProfileService(db).UpdateAsync(Req(claudeKey: "sk-new-9999"));
|
||||
|
||||
var p = await db.ChurchProfiles.FirstAsync();
|
||||
Assert.Equal("sk-new-9999", p.ClaudeApiKey);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_sets_provider_and_models()
|
||||
{
|
||||
using var db = NewDb();
|
||||
db.ChurchProfiles.Add(new ChurchProfile { Name = "C" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
await new ChurchProfileService(db).UpdateAsync(
|
||||
Req(provider: "Gemini", claudeModel: "claude-x", geminiModel: "gemini-y"));
|
||||
|
||||
var p = await db.ChurchProfiles.FirstAsync();
|
||||
Assert.Equal("Gemini", p.AiProvider);
|
||||
Assert.Equal("claude-x", p.ClaudeModel);
|
||||
Assert.Equal("gemini-y", p.GeminiModel);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.Entities;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class DbSeederForm990Tests
|
||||
{
|
||||
private static AppDbContext BuildDb()
|
||||
{
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "seed") })) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(mock.Object))).Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedExpenseCategories_AddsNewGroups_RenamesDuplicates_AndIsIdempotent()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var fnb = new ExpenseCategoryGroup { Name_en = "Food & Beverage", Name_zh = "餐飲", SortOrder = 3 };
|
||||
db.ExpenseCategoryGroups.Add(fnb);
|
||||
await db.SaveChangesAsync();
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { GroupId = fnb.Id, Name_en = "Consumables", Name_zh = "消耗品" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
await DbSeeder.SeedExpenseCategoriesAsync(db);
|
||||
await DbSeeder.SeedExpenseCategoriesAsync(db); // idempotent second run
|
||||
|
||||
var groups = await db.ExpenseCategoryGroups.ToListAsync();
|
||||
Assert.Contains(groups, g => g.Name_en == "Professional Services");
|
||||
Assert.Contains(groups, g => g.Name_en == "Information Technology");
|
||||
Assert.Contains(groups, g => g.Name_en == "Finance & Banking");
|
||||
|
||||
var fnbSubs = await db.ExpenseSubCategories.Where(s => s.GroupId == fnb.Id).ToListAsync();
|
||||
Assert.DoesNotContain(fnbSubs, s => s.Name_en == "Consumables");
|
||||
Assert.Contains(fnbSubs, s => s.Name_en == "Disposable Tableware");
|
||||
|
||||
Assert.Single(groups, g => g.Name_en == "Professional Services");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedMinistries_SetsAdministrationToManagementGeneral_OthersProgram()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
await DbSeeder.SeedMinistriesAsync(db);
|
||||
|
||||
var admin = await db.Ministries.FirstAsync(m => m.Name_en == "Administration");
|
||||
var worship = await db.Ministries.FirstAsync(m => m.Name_en == "Worship");
|
||||
Assert.Equal("ManagementGeneral", admin.DefaultFunctionalClass);
|
||||
Assert.Equal("Program", worship.DefaultFunctionalClass);
|
||||
|
||||
// Activity/shepherding ministries are an attribution axis only; they default to Program
|
||||
// so adding them never distorts the 990 functional columns.
|
||||
var cellGroups = await db.Ministries.FirstAsync(m => m.Name_en == "Cell Groups");
|
||||
var specialEvents = await db.Ministries.FirstAsync(m => m.Name_en == "Special Events");
|
||||
Assert.Equal("Program", cellGroups.DefaultFunctionalClass);
|
||||
Assert.Equal("Program", specialEvents.DefaultFunctionalClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedForm990Lines_CreatesCatalog_AndMapsKnownSubcategories()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
await DbSeeder.SeedExpenseCategoriesAsync(db);
|
||||
await DbSeeder.SeedForm990ExpenseLinesAsync(db);
|
||||
await DbSeeder.SeedForm990ExpenseLinesAsync(db); // idempotent
|
||||
|
||||
Assert.Equal(1, await db.Form990ExpenseLines.CountAsync(l => l.LineCode == "7"));
|
||||
Assert.True(await db.Form990ExpenseLines.AnyAsync(l => l.LineCode == "24"));
|
||||
|
||||
var salary = await db.ExpenseSubCategories.Include(s => s.Form990Line)
|
||||
.FirstAsync(s => s.Name_en == "Salary & Wages");
|
||||
Assert.Equal("7", salary.Form990Line!.LineCode);
|
||||
|
||||
var audit = await db.ExpenseSubCategories.Include(s => s.Form990Line)
|
||||
.FirstAsync(s => s.Name_en == "Accounting & Audit");
|
||||
Assert.Equal("11c", audit.Form990Line!.LineCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedForm990Lines_MapsAuditCorrectedSubcategories_OffTheLine24CatchAll()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
await DbSeeder.SeedExpenseCategoriesAsync(db);
|
||||
await DbSeeder.SeedForm990ExpenseLinesAsync(db);
|
||||
|
||||
async Task<string> CodeOf(string subEn) =>
|
||||
(await db.ExpenseSubCategories.Include(s => s.Form990Line)
|
||||
.FirstAsync(s => s.Name_en == subEn)).Form990Line!.LineCode;
|
||||
|
||||
// Newly mapped subcategories that previously fell through to line 24.
|
||||
Assert.Equal("13", await CodeOf("Bank & Processing Fees"));
|
||||
Assert.Equal("13", await CodeOf("Rental"));
|
||||
Assert.Equal("13", await CodeOf("Maintenance & Repair"));
|
||||
Assert.Equal("13", await CodeOf("Cleaning Supplies"));
|
||||
Assert.Equal("13", await CodeOf("Craft Supplies"));
|
||||
// Building repairs & maintenance are part of Occupancy (line 16), not equipment (line 13).
|
||||
Assert.Equal("16", await CodeOf("Repairs & Maintenance"));
|
||||
// Appreciation/outreach gifts are deliberately mapped to Other (line 24), not left unmapped.
|
||||
Assert.Equal("24", await CodeOf("Gifts"));
|
||||
// Visitation is a travel/program cost, not a grant to an individual.
|
||||
Assert.Equal("17", await CodeOf("Visit Expenses"));
|
||||
// Missions support paid to individual missionaries → line 2, not line 1 (organizations).
|
||||
Assert.Equal("2", await CodeOf("Missionary Support"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedForm990Lines_RemapsExistingBadMapping_ButNotAdminOverride()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
await DbSeeder.SeedExpenseCategoriesAsync(db);
|
||||
await DbSeeder.SeedForm990ExpenseLinesAsync(db);
|
||||
|
||||
// Simulate a database seeded by the OLD code: Visit Expenses on line 2, Missionary
|
||||
// Support on line 1. Also simulate an admin who deliberately moved one elsewhere.
|
||||
var lineByCode = await db.Form990ExpenseLines.ToDictionaryAsync(l => l.LineCode, l => l.Id);
|
||||
var visit = await db.ExpenseSubCategories.FirstAsync(s => s.Name_en == "Visit Expenses");
|
||||
var missionary = await db.ExpenseSubCategories.FirstAsync(s => s.Name_en == "Missionary Support");
|
||||
var transfer = await db.ExpenseSubCategories.FirstAsync(s => s.Name_en == "Offering Transfer");
|
||||
visit.Form990LineId = lineByCode["2"]; // old (wrong) value → should be corrected
|
||||
missionary.Form990LineId = lineByCode["1"]; // old (wrong) value → should be corrected
|
||||
transfer.Form990LineId = lineByCode["24"]; // admin override → must be left alone
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
await DbSeeder.SeedForm990ExpenseLinesAsync(db);
|
||||
|
||||
await db.Entry(visit).ReloadAsync();
|
||||
await db.Entry(missionary).ReloadAsync();
|
||||
await db.Entry(transfer).ReloadAsync();
|
||||
Assert.Equal(lineByCode["17"], visit.Form990LineId); // corrected 2 → 17
|
||||
Assert.Equal(lineByCode["2"], missionary.Form990LineId); // corrected 1 → 2
|
||||
Assert.Equal(lineByCode["24"], transfer.Form990LineId); // admin edit preserved
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Disbursement;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using ROLAC.API.Services.Disbursement;
|
||||
using ROLAC.API.Services.Storage;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class DisbursementServiceTests
|
||||
{
|
||||
private sealed class FakeStorage : IFileStorage
|
||||
{
|
||||
public Dictionary<string, byte[]> Files = new();
|
||||
public Task<string> SaveAsync(Stream c, string p, CancellationToken ct = default)
|
||||
{ using var ms = new MemoryStream(); c.CopyTo(ms); Files[p] = ms.ToArray(); return Task.FromResult(p); }
|
||||
public Task<Stream?> OpenReadAsync(string p, CancellationToken ct = default)
|
||||
=> Task.FromResult<Stream?>(Files.TryGetValue(p, out var b) ? new MemoryStream(b) : null);
|
||||
public Task DeleteAsync(string p, CancellationToken ct = default) { Files.Remove(p); return Task.CompletedTask; }
|
||||
}
|
||||
|
||||
private sealed class FakePrint : ICheckPrintService
|
||||
{
|
||||
public CheckPrintModel? LastReceiptModel;
|
||||
|
||||
public Task<Stream> RenderPdfAsync(CheckPrintModel model)
|
||||
=> Task.FromResult<Stream>(new MemoryStream(Encoding.UTF8.GetBytes("pdf")));
|
||||
|
||||
public Task<Stream> RenderReceiptPdfAsync(CheckPrintModel model)
|
||||
{
|
||||
LastReceiptModel = model;
|
||||
return Task.FromResult<Stream>(new MemoryStream(Encoding.UTF8.GetBytes("receipt-pdf")));
|
||||
}
|
||||
}
|
||||
|
||||
private static AppDbContext BuildDb(string userId)
|
||||
{
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) })) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(mock.Object))).Options);
|
||||
}
|
||||
|
||||
private static DisbursementService SvcAs(AppDbContext db, FakeStorage fs, string userId)
|
||||
{
|
||||
var http = new Mock<IHttpContextAccessor>();
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) })) };
|
||||
http.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new DisbursementService(db, http.Object, fs, new FakePrint(), ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
}
|
||||
|
||||
private static (DisbursementService svc, AppDbContext db, FakeStorage fs) Build(string userId = "fin")
|
||||
{
|
||||
var db = BuildDb(userId);
|
||||
db.ChurchProfiles.Add(new ChurchProfile { Id = 1, Name = "ROLAC", NextCheckNumber = 1001 });
|
||||
db.Members.Add(new Member { Id = 1, FirstName_en = "John", LastName_en = "Doe", Address = "1 Main St", City = "Arcadia", State = "CA", ZipCode = "91006" });
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 1, Name_en = "Equipment" });
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 2, Name_en = "Food & Beverage" });
|
||||
db.SaveChanges();
|
||||
var fs = new FakeStorage();
|
||||
return (SvcAs(db, fs, userId), db, fs);
|
||||
}
|
||||
|
||||
private static Expense Approved(string type, decimal amount, int? memberId = null, string? vendor = null) => new()
|
||||
{
|
||||
Type = type, Status = "Approved", Amount = amount, Description = $"{type} {amount}",
|
||||
MinistryId = 1, ExpenseDate = new DateOnly(2026, 6, 1),
|
||||
MemberId = memberId, VendorName = vendor,
|
||||
Lines = { new ExpenseLine { CategoryGroupId = 1, SubCategoryId = 1, Amount = amount } },
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task GroupedWorklist_BundlesSamePayee()
|
||||
{
|
||||
var (svc, db, _) = Build();
|
||||
db.Expenses.AddRange(
|
||||
Approved("StaffReimbursement", 10m, memberId: 1),
|
||||
Approved("StaffReimbursement", 15m, memberId: 1),
|
||||
Approved("VendorPayment", 30m, vendor: "Acme"));
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var groups = await svc.GetApprovedUnpaidGroupedAsync();
|
||||
|
||||
Assert.Equal(2, groups.Count);
|
||||
var member = groups.Single(g => g.PayeeType == "Member");
|
||||
Assert.Equal(25m, member.TotalAmount);
|
||||
Assert.Equal(2, member.Lines.Count);
|
||||
Assert.Equal("John Doe", member.PayeeName);
|
||||
Assert.Equal("1 Main St", member.Address);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GroupedWorklist_MultiCategoryExpense_ShowsMultipleLabel()
|
||||
{
|
||||
var (svc, db, _) = Build();
|
||||
db.Expenses.Add(new Expense
|
||||
{
|
||||
Type = "VendorPayment", Status = "Approved", Amount = 50m, Description = "mixed invoice",
|
||||
MinistryId = 1, ExpenseDate = new DateOnly(2026, 6, 1), VendorName = "Costco",
|
||||
Lines =
|
||||
{
|
||||
new ExpenseLine { CategoryGroupId = 1, SubCategoryId = 1, Amount = 30m },
|
||||
new ExpenseLine { CategoryGroupId = 2, SubCategoryId = 2, Amount = 20m },
|
||||
},
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var groups = await svc.GetApprovedUnpaidGroupedAsync();
|
||||
|
||||
var line = groups.Single(g => g.PayeeType == "Vendor").Lines.Single();
|
||||
Assert.Equal("Multiple / 多類別", line.CategoryName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Issue_CreatesOneCheckPerPayee_MarksPaid_SequentialNumbers()
|
||||
{
|
||||
var (svc, db, _) = Build();
|
||||
var e1 = Approved("StaffReimbursement", 10m, memberId: 1);
|
||||
var e2 = Approved("StaffReimbursement", 15m, memberId: 1);
|
||||
var e3 = Approved("VendorPayment", 30m, vendor: "Acme");
|
||||
db.Expenses.AddRange(e1, e2, e3);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var req = new IssueChecksRequest
|
||||
{
|
||||
CheckDate = new DateOnly(2026, 6, 20),
|
||||
Payees =
|
||||
[
|
||||
new() { PayeeType = "Member", MemberId = 1, PayeeName = "John Doe", ExpenseIds = [e1.Id, e2.Id] },
|
||||
new() { PayeeType = "Vendor", VendorKey = "acme", PayeeName = "Acme", ExpenseIds = [e3.Id] },
|
||||
],
|
||||
};
|
||||
|
||||
var result = await svc.IssueChecksAsync(req);
|
||||
|
||||
Assert.Equal(2, result.Created.Count);
|
||||
Assert.Equal(new[] { "1001", "1002" }, result.Created.Select(c => c.CheckNumber).ToArray());
|
||||
Assert.All(await db.Expenses.ToListAsync(), e => Assert.Equal("Paid", e.Status));
|
||||
var memberCheck = await db.Checks.FirstAsync(c => c.PayeeType == "Member");
|
||||
Assert.Equal(25m, memberCheck.Amount);
|
||||
Assert.Equal(1003, (await db.ChurchProfiles.FirstAsync()).NextCheckNumber);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Issue_RejectsNonApprovedExpense()
|
||||
{
|
||||
var (svc, db, _) = Build();
|
||||
var e = Approved("VendorPayment", 30m, vendor: "Acme");
|
||||
e.Status = "Draft";
|
||||
db.Expenses.Add(e);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var req = new IssueChecksRequest
|
||||
{
|
||||
CheckDate = new DateOnly(2026, 6, 20),
|
||||
Payees = [new() { PayeeType = "Vendor", PayeeName = "Acme", ExpenseIds = [e.Id] }],
|
||||
};
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => svc.IssueChecksAsync(req));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Void_RevertsExpensesToApproved()
|
||||
{
|
||||
var (svc, db, _) = Build();
|
||||
var e = Approved("VendorPayment", 30m, vendor: "Acme");
|
||||
db.Expenses.Add(e);
|
||||
await db.SaveChangesAsync();
|
||||
var result = await svc.IssueChecksAsync(new IssueChecksRequest
|
||||
{
|
||||
CheckDate = new DateOnly(2026, 6, 20),
|
||||
Payees = [new() { PayeeType = "Vendor", PayeeName = "Acme", ExpenseIds = [e.Id] }],
|
||||
});
|
||||
var checkId = result.Created[0].CheckId;
|
||||
|
||||
await svc.VoidAsync(checkId, "wrong amount");
|
||||
|
||||
var check = await db.Checks.FirstAsync(c => c.Id == checkId);
|
||||
Assert.Equal("Voided", check.Status);
|
||||
var reverted = await db.Expenses.FirstAsync(x => x.Id == e.Id);
|
||||
Assert.Equal("Approved", reverted.Status);
|
||||
Assert.Null(reverted.CheckNumber);
|
||||
Assert.Null(reverted.PaidAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Acknowledge_StoresSignatureAndTimestamp()
|
||||
{
|
||||
var (svc, db, fs) = Build();
|
||||
var e = Approved("VendorPayment", 30m, vendor: "Acme");
|
||||
db.Expenses.Add(e);
|
||||
await db.SaveChangesAsync();
|
||||
var result = await svc.IssueChecksAsync(new IssueChecksRequest
|
||||
{
|
||||
CheckDate = new DateOnly(2026, 6, 20),
|
||||
Payees = [new() { PayeeType = "Vendor", PayeeName = "Acme", ExpenseIds = [e.Id] }],
|
||||
});
|
||||
var checkId = result.Created[0].CheckId;
|
||||
|
||||
using var img = new MemoryStream(Encoding.UTF8.GetBytes("png-bytes"));
|
||||
await svc.AcknowledgeReceiptAsync(checkId, img, "sig.png", "Acme Rep");
|
||||
|
||||
var check = await db.Checks.FirstAsync(c => c.Id == checkId);
|
||||
Assert.NotNull(check.ReceiptSignedAt);
|
||||
Assert.Equal("Acme Rep", check.ReceiptSignedName);
|
||||
Assert.NotNull(check.ReceiptSignatureBlobPath);
|
||||
Assert.Single(fs.Files);
|
||||
}
|
||||
|
||||
private static (DisbursementService svc, AppDbContext db, FakeStorage fs, FakePrint print) BuildWithPrint(string userId = "fin")
|
||||
{
|
||||
var db = BuildDb(userId);
|
||||
db.ChurchProfiles.Add(new ChurchProfile { Id = 1, Name = "ROLAC", NextCheckNumber = 1001 });
|
||||
db.SaveChanges();
|
||||
var fs = new FakeStorage();
|
||||
var print = new FakePrint();
|
||||
var http = new Mock<IHttpContextAccessor>();
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) })) };
|
||||
http.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return (new DisbursementService(db, http.Object, fs, print, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance), db, fs, print);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReceiptPdf_NullWhenNotSigned()
|
||||
{
|
||||
var (svc, db, _, _) = BuildWithPrint();
|
||||
var e = Approved("VendorPayment", 30m, vendor: "Acme");
|
||||
db.Expenses.Add(e);
|
||||
await db.SaveChangesAsync();
|
||||
var result = await svc.IssueChecksAsync(new IssueChecksRequest
|
||||
{
|
||||
CheckDate = new DateOnly(2026, 6, 20),
|
||||
Payees = [new() { PayeeType = "Vendor", PayeeName = "Acme", ExpenseIds = [e.Id] }],
|
||||
});
|
||||
|
||||
var receipt = await svc.RenderReceiptPdfAsync(result.Created[0].CheckId);
|
||||
|
||||
Assert.Null(receipt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReceiptPdf_AfterSigning_RendersWithSignatureBytes()
|
||||
{
|
||||
var (svc, db, _, print) = BuildWithPrint();
|
||||
var e = Approved("VendorPayment", 30m, vendor: "Acme");
|
||||
db.Expenses.Add(e);
|
||||
await db.SaveChangesAsync();
|
||||
var result = await svc.IssueChecksAsync(new IssueChecksRequest
|
||||
{
|
||||
CheckDate = new DateOnly(2026, 6, 20),
|
||||
Payees = [new() { PayeeType = "Vendor", PayeeName = "Acme", ExpenseIds = [e.Id] }],
|
||||
});
|
||||
var checkId = result.Created[0].CheckId;
|
||||
using var img = new MemoryStream(Encoding.UTF8.GetBytes("png-bytes"));
|
||||
await svc.AcknowledgeReceiptAsync(checkId, img, "sig.png", "Acme Rep");
|
||||
|
||||
var receipt = await svc.RenderReceiptPdfAsync(checkId);
|
||||
|
||||
Assert.NotNull(receipt);
|
||||
Assert.Equal("receipt-1001.pdf", receipt!.Value.fileName);
|
||||
Assert.NotNull(print.LastReceiptModel);
|
||||
Assert.NotNull(print.LastReceiptModel!.SignatureImage);
|
||||
Assert.Equal("Acme Rep", print.LastReceiptModel.Check.ReceiptSignedName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Acknowledge_VoidedCheck_Throws()
|
||||
{
|
||||
var (svc, db, _) = Build();
|
||||
var e = Approved("VendorPayment", 30m, vendor: "Acme");
|
||||
db.Expenses.Add(e);
|
||||
await db.SaveChangesAsync();
|
||||
var result = await svc.IssueChecksAsync(new IssueChecksRequest
|
||||
{
|
||||
CheckDate = new DateOnly(2026, 6, 20),
|
||||
Payees = [new() { PayeeType = "Vendor", PayeeName = "Acme", ExpenseIds = [e.Id] }],
|
||||
});
|
||||
var checkId = result.Created[0].CheckId;
|
||||
await svc.VoidAsync(checkId, null);
|
||||
|
||||
using var img = new MemoryStream(Encoding.UTF8.GetBytes("png"));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(
|
||||
() => svc.AcknowledgeReceiptAsync(checkId, img, "sig.png", "X"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services.Ai;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class ExpenseAiServiceFactoryTests
|
||||
{
|
||||
// ChurchProfile is auditable, so the InMemory store rejects saves unless the
|
||||
// required CreatedBy/UpdatedBy fields are populated. Wire the same audit
|
||||
// interceptor the app uses so seeded entities save cleanly.
|
||||
private static AppDbContext NewDb()
|
||||
{
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "test-user") })),
|
||||
};
|
||||
var httpContextAccessor = new Mock<IHttpContextAccessor>();
|
||||
httpContextAccessor.Setup(accessor => accessor.HttpContext).Returns(httpContext);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.ConfigureWarnings(warnings => warnings.Ignore(InMemoryEventId.TransactionIgnoredWarning))
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new CurrentUserAccessor(httpContextAccessor.Object)))
|
||||
.Options);
|
||||
}
|
||||
|
||||
private static ExpenseAiServiceFactory Build(AppDbContext db)
|
||||
{
|
||||
var cfg = new ChurchAiConfigProvider(db);
|
||||
var claude = new ClaudeExpenseAiService(
|
||||
new HttpClient(), cfg, db, NullLogger<ClaudeExpenseAiService>.Instance);
|
||||
var gemini = new GeminiExpenseAiService(
|
||||
new HttpClient(), cfg, db, NullLogger<GeminiExpenseAiService>.Instance);
|
||||
return new ExpenseAiServiceFactory(cfg, claude, gemini);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolves_Claude_by_default()
|
||||
{
|
||||
using var db = NewDb();
|
||||
db.ChurchProfiles.Add(new ChurchProfile { Name = "C", AiProvider = "Claude" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var svc = await Build(db).ResolveAsync();
|
||||
|
||||
Assert.IsType<ClaudeExpenseAiService>(svc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolves_Gemini_when_selected()
|
||||
{
|
||||
using var db = NewDb();
|
||||
db.ChurchProfiles.Add(new ChurchProfile { Name = "C", AiProvider = "Gemini" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var svc = await Build(db).ResolveAsync();
|
||||
|
||||
Assert.IsType<GeminiExpenseAiService>(svc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services.Ai;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class ExpenseCategoryAiServiceFactoryTests
|
||||
{
|
||||
// ChurchProfile is auditable, so the InMemory store rejects saves unless the
|
||||
// required CreatedBy/UpdatedBy fields are populated. Wire the same audit
|
||||
// interceptor the app uses so seeded entities save cleanly.
|
||||
private static AppDbContext NewDb()
|
||||
{
|
||||
var httpContext = new DefaultHttpContext
|
||||
{
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "test-user") })),
|
||||
};
|
||||
var httpContextAccessor = new Mock<IHttpContextAccessor>();
|
||||
httpContextAccessor.Setup(accessor => accessor.HttpContext).Returns(httpContext);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.ConfigureWarnings(warnings => warnings.Ignore(InMemoryEventId.TransactionIgnoredWarning))
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new CurrentUserAccessor(httpContextAccessor.Object)))
|
||||
.Options);
|
||||
}
|
||||
|
||||
private static ExpenseCategoryAiServiceFactory Build(AppDbContext db)
|
||||
{
|
||||
var cfg = new ChurchAiConfigProvider(db);
|
||||
var claude = new ClaudeExpenseCategoryAiService(
|
||||
new HttpClient(), cfg, db, NullLogger<ClaudeExpenseCategoryAiService>.Instance);
|
||||
var gemini = new GeminiExpenseCategoryAiService(
|
||||
new HttpClient(), cfg, db, NullLogger<GeminiExpenseCategoryAiService>.Instance);
|
||||
return new ExpenseCategoryAiServiceFactory(cfg, claude, gemini);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolves_Claude_by_default()
|
||||
{
|
||||
using var db = NewDb();
|
||||
db.ChurchProfiles.Add(new ChurchProfile { Name = "C", AiProvider = "Claude" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var svc = await Build(db).ResolveAsync();
|
||||
|
||||
Assert.IsType<ClaudeExpenseCategoryAiService>(svc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolves_Gemini_when_selected()
|
||||
{
|
||||
using var db = NewDb();
|
||||
db.ChurchProfiles.Add(new ChurchProfile { Name = "C", AiProvider = "Gemini" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var svc = await Build(db).ResolveAsync();
|
||||
|
||||
Assert.IsType<GeminiExpenseCategoryAiService>(svc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Expense;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class ExpenseCategoryServiceTests
|
||||
{
|
||||
private static AppDbContext BuildDb()
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "test-user") };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(mock.Object))).Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAll_NestsSubcategories_AndExcludesInactiveByDefault()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new ExpenseCategoryService(db);
|
||||
var gid = await svc.CreateGroupAsync(new CreateExpenseGroupRequest { Name_en = "Equipment" });
|
||||
var sid = await svc.CreateSubCategoryAsync(new CreateExpenseSubCategoryRequest { GroupId = gid, Name_en = "Purchase" });
|
||||
await svc.DeactivateSubCategoryAsync(sid);
|
||||
|
||||
var active = await svc.GetAllAsync(includeInactive: false);
|
||||
var all = await svc.GetAllAsync(includeInactive: true);
|
||||
|
||||
Assert.Single(active);
|
||||
Assert.Empty(active[0].SubCategories);
|
||||
Assert.Single(all[0].SubCategories);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeactivateGroup_SetsInactive()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new ExpenseCategoryService(db);
|
||||
var gid = await svc.CreateGroupAsync(new CreateExpenseGroupRequest { Name_en = "Other" });
|
||||
await svc.DeactivateGroupAsync(gid);
|
||||
Assert.Empty(await svc.GetAllAsync(includeInactive: false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateGroup_Throws_WhenMissing()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new ExpenseCategoryService(db);
|
||||
await Assert.ThrowsAsync<KeyNotFoundException>(() =>
|
||||
svc.UpdateGroupAsync(999, new UpdateExpenseGroupRequest { Name_en = "X" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAndGet_RoundTrips_Form990LineId()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
db.Form990ExpenseLines.Add(new ROLAC.API.Entities.Form990ExpenseLine { Id = 1, LineCode = "24", Name_en = "Other" });
|
||||
db.Form990ExpenseLines.Add(new ROLAC.API.Entities.Form990ExpenseLine { Id = 7, LineCode = "7", Name_en = "Salaries" });
|
||||
await db.SaveChangesAsync();
|
||||
var svc = new ExpenseCategoryService(db);
|
||||
var gid = await svc.CreateGroupAsync(new CreateExpenseGroupRequest { Name_en = "Personnel", Form990LineId = 1 });
|
||||
var sid = await svc.CreateSubCategoryAsync(new CreateExpenseSubCategoryRequest { GroupId = gid, Name_en = "Salary & Wages", Form990LineId = 7 });
|
||||
|
||||
var all = await svc.GetAllAsync(includeInactive: true);
|
||||
var sub = all.Single(g => g.Id == gid).SubCategories.Single(s => s.Id == sid);
|
||||
Assert.Equal(7, sub.Form990LineId);
|
||||
Assert.Equal("7", sub.Form990LineCode);
|
||||
Assert.Equal(1, all.Single(g => g.Id == gid).Form990LineId);
|
||||
Assert.Equal("24", all.Single(g => g.Id == gid).Form990LineCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Expense;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Entities.Logging;
|
||||
using ROLAC.API.Services;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using ROLAC.API.Services.Storage;
|
||||
using ROLAC.API.Tests.TestSupport;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class ExpenseServiceTests
|
||||
{
|
||||
private sealed class FakeStorage : IFileStorage
|
||||
{
|
||||
public Dictionary<string, byte[]> Files = new();
|
||||
public Task<string> SaveAsync(Stream c, string p, CancellationToken ct = default)
|
||||
{ using var ms = new MemoryStream(); c.CopyTo(ms); Files[p] = ms.ToArray(); return Task.FromResult(p); }
|
||||
public Task<Stream?> OpenReadAsync(string p, CancellationToken ct = default)
|
||||
=> Task.FromResult<Stream?>(Files.TryGetValue(p, out var b) ? new MemoryStream(b) : null);
|
||||
public Task DeleteAsync(string p, CancellationToken ct = default) { Files.Remove(p); return Task.CompletedTask; }
|
||||
}
|
||||
|
||||
private static AppDbContext BuildDb(string userId)
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(mock.Object))).Options);
|
||||
}
|
||||
|
||||
private static (ExpenseService svc, AppDbContext db, FakeStorage fs) Build(string userId = "u1")
|
||||
{
|
||||
var db = BuildDb(userId);
|
||||
db.Ministries.Add(new Ministry { Id = 1, Name_en = "Worship" });
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 1, Name_en = "Equipment" });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 1, GroupId = 1, Name_en = "Purchase" });
|
||||
db.SaveChanges();
|
||||
var fs = new FakeStorage();
|
||||
return (SvcAs(db, fs, userId), db, fs);
|
||||
}
|
||||
|
||||
private static ExpenseService SvcAs(AppDbContext db, FakeStorage fs, string userId)
|
||||
{
|
||||
var http = new Mock<IHttpContextAccessor>();
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) })) };
|
||||
http.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new ExpenseService(db, http.Object, fs, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
}
|
||||
|
||||
private static ExpenseService SvcAs(AppDbContext db, FakeStorage fs, string userId, IAuditLogger audit)
|
||||
{
|
||||
var http = new Mock<IHttpContextAccessor>();
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) })) };
|
||||
http.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new ExpenseService(db, http.Object, fs, audit);
|
||||
}
|
||||
|
||||
// Builds a service whose principal carries ONLY the "sub" claim (no NameIdentifier),
|
||||
// mirroring the real JWT (NameClaimType="sub", MapInboundClaims=false).
|
||||
private static ExpenseService SvcWithSubClaim(AppDbContext db, FakeStorage fs, string userId)
|
||||
{
|
||||
var http = new Mock<IHttpContextAccessor>();
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim("sub", userId) })) };
|
||||
http.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new ExpenseService(db, http.Object, fs, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
}
|
||||
|
||||
private static CreateExpenseRequest Reimb() => new()
|
||||
{
|
||||
Type = "StaffReimbursement", MinistryId = 1,
|
||||
Lines = { new ExpenseLineInput { CategoryGroupId = 1, SubCategoryId = 1, Amount = 45.50m } },
|
||||
Description = "Batteries", ExpenseDate = new DateOnly(2026, 5, 28),
|
||||
};
|
||||
|
||||
private static UpdateExpenseRequest CloneToUpdate(CreateExpenseRequest r) => new()
|
||||
{
|
||||
Type = r.Type, MinistryId = r.MinistryId,
|
||||
Lines = r.Lines.Select(l => new ExpenseLineInput
|
||||
{
|
||||
CategoryGroupId = l.CategoryGroupId, SubCategoryId = l.SubCategoryId,
|
||||
Amount = l.Amount, FunctionalClass = l.FunctionalClass, Description = l.Description,
|
||||
}).ToList(),
|
||||
Description = r.Description,
|
||||
VendorName = r.VendorName, MemberId = r.MemberId, CheckNumber = r.CheckNumber,
|
||||
ExpenseDate = r.ExpenseDate, Notes = r.Notes,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Create_Reimbursement_ResolvesUserId_FromSubClaim()
|
||||
{
|
||||
// Regression: the real JWT exposes the user id as "sub", not ClaimTypes.NameIdentifier.
|
||||
// SubmittedBy must be the sub value (not "system"), or the self-ownership guard breaks.
|
||||
var db = BuildDb("ignored");
|
||||
db.Ministries.Add(new Ministry { Id = 1, Name_en = "Worship" });
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 1, Name_en = "Equipment" });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 1, GroupId = 1, Name_en = "Purchase" });
|
||||
await db.SaveChangesAsync();
|
||||
var svc = SvcWithSubClaim(db, new FakeStorage(), "user-guid-123");
|
||||
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
|
||||
var e = await db.Expenses.FindAsync(id);
|
||||
Assert.Equal("user-guid-123", e!.SubmittedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_Vendor_AsFinance_IsPendingApproval()
|
||||
{
|
||||
var (svc, db, _) = Build();
|
||||
var r = Reimb(); r.Type = "VendorPayment"; r.VendorName = "ABC"; r.CheckNumber = "2051";
|
||||
var id = await svc.CreateAsync(r, isFinance: true);
|
||||
Assert.Equal("PendingApproval", (await db.Expenses.FindAsync(id))!.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_Reimbursement_AsFinance_OnBehalf_IsPendingApproval_AndLinksPickedMember()
|
||||
{
|
||||
// Finance entering on behalf of a member (member explicitly picked) goes straight to the
|
||||
// approval queue and links the picked member.
|
||||
var (svc, db, _) = Build();
|
||||
db.Members.Add(new Member { Id = 9, FirstName_en = "Pat", LastName_en = "Vendor" });
|
||||
await db.SaveChangesAsync();
|
||||
var r = Reimb(); r.MemberId = 9;
|
||||
|
||||
var id = await svc.CreateAsync(r, isFinance: true);
|
||||
|
||||
var e = await db.Expenses.FindAsync(id);
|
||||
Assert.Equal("PendingApproval", e!.Status);
|
||||
Assert.Equal(9, e.MemberId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_Reimbursement_AsFinance_SelfService_LinksCallerMember_AndIsDraft()
|
||||
{
|
||||
// Regression: a finance/super_admin user filing their OWN reimbursement via "My Reimbursements"
|
||||
// sends no MemberId. The entry must link to the caller's own member (so the Payee shows their
|
||||
// legal name) and stay a Draft until they explicitly Submit — not jump to PendingApproval with
|
||||
// a null member.
|
||||
var (svc, db, _) = Build("u1");
|
||||
db.Members.Add(new Member { Id = 7, FirstName_en = "Grace", LastName_en = "Lee" });
|
||||
db.Users.Add(new AppUser { Id = "u1", MemberId = 7 });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: true); // no MemberId on the request
|
||||
|
||||
var e = await db.Expenses.FindAsync(id);
|
||||
Assert.Equal(7, e!.MemberId);
|
||||
Assert.Equal("Draft", e.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_Reimbursement_AsMember_IsDraft_WithSubmitter()
|
||||
{
|
||||
var (svc, db, _) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
var e = await db.Expenses.FindAsync(id);
|
||||
Assert.Equal("Draft", e!.Status);
|
||||
Assert.Equal("alice", e.SubmittedBy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StateMachine_HappyPath_Submit_Approve_Pay()
|
||||
{
|
||||
var (svc, db, _) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(id);
|
||||
Assert.Equal("PendingApproval", (await db.Expenses.FindAsync(id))!.Status);
|
||||
await svc.ApproveAsync(id);
|
||||
Assert.Equal("Approved", (await db.Expenses.FindAsync(id))!.Status);
|
||||
await svc.PayAsync(id, "3001", new DateOnly(2026, 6, 1));
|
||||
var paid = await db.Expenses.FindAsync(id);
|
||||
Assert.Equal("Paid", paid!.Status);
|
||||
Assert.Equal("3001", paid.CheckNumber);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Approve_FromDraft_Throws()
|
||||
{
|
||||
var (svc, _, _) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => svc.ApproveAsync(id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reject_RecordsNotes_AndStatus()
|
||||
{
|
||||
var (svc, db, _) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(id);
|
||||
await svc.RejectAsync(id, "Missing receipt");
|
||||
var e = await db.Expenses.FindAsync(id);
|
||||
Assert.Equal("Rejected", e!.Status);
|
||||
Assert.Equal("Missing receipt", e.ReviewNotes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_OthersDraft_AsNonFinance_Throws()
|
||||
{
|
||||
var (aliceSvc, db, fs) = Build("alice");
|
||||
var id = await aliceSvc.CreateAsync(Reimb(), isFinance: false);
|
||||
var bobSvc = SvcAs(db, fs, "bob");
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
bobSvc.UpdateAsync(id, CloneToUpdate(Reimb()), isFinance: false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_OwnPendingApproval_AsNonFinance_Succeeds()
|
||||
{
|
||||
// After Submit a reimbursement sits in PendingApproval; the owner may still correct it.
|
||||
var (svc, db, _) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(id);
|
||||
Assert.Equal("PendingApproval", (await db.Expenses.FindAsync(id))!.Status);
|
||||
|
||||
var edit = CloneToUpdate(Reimb());
|
||||
edit.Lines[0].Amount = 99.99m;
|
||||
await svc.UpdateAsync(id, edit, isFinance: false);
|
||||
|
||||
var e = await db.Expenses.FindAsync(id);
|
||||
Assert.Equal(99.99m, e!.Amount);
|
||||
Assert.Equal("PendingApproval", e.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_OwnApproved_AsNonFinance_Throws()
|
||||
{
|
||||
// Once approved, the owner can no longer edit.
|
||||
var (svc, db, fs) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(id);
|
||||
await SvcAs(db, fs, "finance").ApproveAsync(id);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
svc.UpdateAsync(id, CloneToUpdate(Reimb()), isFinance: false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveReceipt_OwnPendingApproval_AsNonFinance_Succeeds()
|
||||
{
|
||||
var (svc, db, _) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(id);
|
||||
using var input = new MemoryStream(Encoding.UTF8.GetBytes("img"));
|
||||
await svc.SaveReceiptAsync(id, input, "r.jpg", isFinance: false);
|
||||
Assert.NotNull(await svc.OpenReceiptAsync(id, isFinance: true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SoftDelete_HidesFromQueries()
|
||||
{
|
||||
var (svc, db, _) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.DeleteAsync(id, isFinance: true);
|
||||
Assert.Null(await db.Expenses.FirstOrDefaultAsync(e => e.Id == id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_PersistsFunctionalClass_AndGetReturnsIt()
|
||||
{
|
||||
var db = BuildDb("u1");
|
||||
db.Ministries.Add(new ROLAC.API.Entities.Ministry { Id = 1, Name_en = "Admin" });
|
||||
db.ExpenseCategoryGroups.Add(new ROLAC.API.Entities.ExpenseCategoryGroup { Id = 1, Name_en = "Other" });
|
||||
db.ExpenseSubCategories.Add(new ROLAC.API.Entities.ExpenseSubCategory { Id = 1, GroupId = 1, Name_en = "Misc" });
|
||||
await db.SaveChangesAsync();
|
||||
var svc = SvcAs(db, new FakeStorage(), "u1");
|
||||
|
||||
var id = await svc.CreateAsync(new CreateExpenseRequest
|
||||
{
|
||||
Type = "VendorPayment", MinistryId = 1,
|
||||
Lines = { new ExpenseLineInput { CategoryGroupId = 1, SubCategoryId = 1, Amount = 50m, FunctionalClass = "ManagementGeneral" } },
|
||||
Description = "x", ExpenseDate = new DateOnly(2026, 5, 1),
|
||||
}, isFinance: true);
|
||||
|
||||
var dto = await svc.GetByIdAsync(id);
|
||||
Assert.Equal("ManagementGeneral", dto!.Lines.Single().FunctionalClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_MultiLine_SetsHeaderTotal_AndRoundTripsLines()
|
||||
{
|
||||
var (svc, db, _) = Build("u1");
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 2, Name_en = "Food & Beverage" });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 2, GroupId = 2, Name_en = "Snacks" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var r = new CreateExpenseRequest
|
||||
{
|
||||
Type = "VendorPayment", MinistryId = 1, VendorName = "Costco",
|
||||
Description = "Mixed invoice", ExpenseDate = new DateOnly(2026, 5, 1),
|
||||
Lines =
|
||||
{
|
||||
new ExpenseLineInput { CategoryGroupId = 1, SubCategoryId = 1, Amount = 30m },
|
||||
new ExpenseLineInput { CategoryGroupId = 2, SubCategoryId = 2, Amount = 12.50m },
|
||||
},
|
||||
};
|
||||
var id = await svc.CreateAsync(r, isFinance: true);
|
||||
|
||||
Assert.Equal(42.50m, (await db.Expenses.FindAsync(id))!.Amount);
|
||||
var dto = await svc.GetByIdAsync(id);
|
||||
Assert.Equal(2, dto!.Lines.Count);
|
||||
Assert.Equal(42.50m, dto.Amount);
|
||||
Assert.Equal(2, dto.LineCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_WithNoLines_Throws()
|
||||
{
|
||||
var (svc, _, _) = Build("u1");
|
||||
var r = Reimb(); r.Lines.Clear();
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => svc.CreateAsync(r, isFinance: false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_ReplacesLines_AndRecomputesTotal()
|
||||
{
|
||||
var (svc, db, _) = Build("alice");
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 2, Name_en = "Food & Beverage" });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 2, GroupId = 2, Name_en = "Snacks" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
|
||||
var edit = CloneToUpdate(Reimb());
|
||||
edit.Lines = new()
|
||||
{
|
||||
new ExpenseLineInput { CategoryGroupId = 1, SubCategoryId = 1, Amount = 10m },
|
||||
new ExpenseLineInput { CategoryGroupId = 2, SubCategoryId = 2, Amount = 5m },
|
||||
};
|
||||
await svc.UpdateAsync(id, edit, isFinance: false);
|
||||
|
||||
Assert.Equal(15m, (await db.Expenses.FindAsync(id))!.Amount);
|
||||
Assert.Equal(2, await db.ExpenseLines.CountAsync(l => l.ExpenseId == id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Receipt_SaveThenOpen_RoundTrips()
|
||||
{
|
||||
var (svc, _, _) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
using var input = new MemoryStream(Encoding.UTF8.GetBytes("img"));
|
||||
await svc.SaveReceiptAsync(id, input, "r.jpg", isFinance: false);
|
||||
var got = await svc.OpenReceiptAsync(id, isFinance: true);
|
||||
Assert.NotNull(got);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reject_WritesAuditEntry_WithReason()
|
||||
{
|
||||
var (svc, db, fs) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(id);
|
||||
|
||||
var audit = new CapturingAuditLogger();
|
||||
await SvcAs(db, fs, "finance", audit).RejectAsync(id, "Receipt unclear, please retake");
|
||||
|
||||
var entry = Assert.Single(audit.Entries);
|
||||
Assert.Equal(AuditActions.ExpenseRejected, entry.Action);
|
||||
Assert.Equal(AuditCategories.Business, entry.Category);
|
||||
Assert.Equal(nameof(ROLAC.API.Entities.Expense), entry.EntityName);
|
||||
Assert.Equal(id.ToString(), entry.EntityId);
|
||||
Assert.Contains("Receipt unclear", entry.Summary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resubmit_FromRejected_ReturnsToPending_AndClearsReview()
|
||||
{
|
||||
var (svc, db, fs) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(id);
|
||||
await SvcAs(db, fs, "finance").RejectAsync(id, "Receipt missing");
|
||||
|
||||
// Owner fixes the issue and re-submits.
|
||||
await svc.SubmitAsync(id);
|
||||
|
||||
var e = await db.Expenses.FindAsync(id);
|
||||
Assert.Equal("PendingApproval", e!.Status);
|
||||
Assert.Null(e.ReviewedBy);
|
||||
Assert.Null(e.ReviewedAt);
|
||||
Assert.Null(e.ReviewNotes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_OwnRejected_AsNonFinance_Succeeds()
|
||||
{
|
||||
// A rejected reimbursement can be corrected by its owner before re-submitting.
|
||||
var (svc, db, fs) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(id);
|
||||
await SvcAs(db, fs, "finance").RejectAsync(id, "Amount does not match receipt");
|
||||
|
||||
var edit = CloneToUpdate(Reimb());
|
||||
edit.Lines[0].Amount = 77.77m;
|
||||
await svc.UpdateAsync(id, edit, isFinance: false);
|
||||
|
||||
var e = await db.Expenses.FindAsync(id);
|
||||
Assert.Equal(77.77m, e!.Amount);
|
||||
Assert.Equal("Rejected", e.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveReceipt_OwnRejected_AsNonFinance_Succeeds()
|
||||
{
|
||||
var (svc, db, fs) = Build("alice");
|
||||
var id = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(id);
|
||||
await SvcAs(db, fs, "finance").RejectAsync(id, "Receipt unclear, please retake");
|
||||
|
||||
using var input = new MemoryStream(Encoding.UTF8.GetBytes("img"));
|
||||
await svc.SaveReceiptAsync(id, input, "retake.jpg", isFinance: false);
|
||||
Assert.NotNull(await svc.OpenReceiptAsync(id, isFinance: true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetById_ResolvesReviewerName_MemberFullName_EmailFallback()
|
||||
{
|
||||
var (svc, db, fs) = Build("alice");
|
||||
// Reviewer linked to a member → shows the member's full name.
|
||||
db.Members.Add(new Member { Id = 5, FirstName_en = "Sam", LastName_en = "Approver" });
|
||||
db.Users.Add(new AppUser { Id = "reviewer-with-member", MemberId = 5 });
|
||||
// Reviewer with no member → falls back to email.
|
||||
db.Users.Add(new AppUser { Id = "reviewer-no-member", Email = "nomember@church.org" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var withMember = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(withMember);
|
||||
await SvcAs(db, fs, "reviewer-with-member").ApproveAsync(withMember);
|
||||
Assert.Equal("Sam Approver", (await svc.GetByIdAsync(withMember))!.ReviewedByName);
|
||||
|
||||
var noMember = await svc.CreateAsync(Reimb(), isFinance: false);
|
||||
await svc.SubmitAsync(noMember);
|
||||
await SvcAs(db, fs, "reviewer-no-member").RejectAsync(noMember, "Duplicate submission");
|
||||
Assert.Equal("nomember@church.org", (await svc.GetByIdAsync(noMember))!.ReviewedByName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Expense;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class ExpenseSnapshotServiceTests
|
||||
{
|
||||
private static AppDbContext BuildDb(string userId)
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new CurrentUserAccessor(mock.Object))).Options);
|
||||
}
|
||||
|
||||
private static (ExpenseSnapshotService svc, AppDbContext db) Build(string userId = "u1")
|
||||
{
|
||||
var db = BuildDb(userId);
|
||||
db.Ministries.Add(new Ministry { Id = 1, Name_en = "Worship", Name_zh = "敬拜" });
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 1, Name_en = "Facilities" });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 1, GroupId = 1, Name_en = "Rent" });
|
||||
db.SaveChanges();
|
||||
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var http = new Mock<IHttpContextAccessor>();
|
||||
http.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return (new ExpenseSnapshotService(db, http.Object), db);
|
||||
}
|
||||
|
||||
private static CreateExpenseSnapshotRequest Rent() => new()
|
||||
{
|
||||
Name = "Monthly Rent", MinistryId = 1, Description = "Office rent", VendorName = "Landlord X",
|
||||
CheckNumber = "1001",
|
||||
Lines = { new ExpenseLineInput { CategoryGroupId = 1, SubCategoryId = 1, Amount = 1200m } },
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Create_PersistsHeaderAndLines_StampsCreator()
|
||||
{
|
||||
var (svc, db) = Build("creator-1");
|
||||
var id = await svc.CreateAsync(Rent());
|
||||
|
||||
var saved = await db.ExpenseSnapshots.FindAsync(id);
|
||||
Assert.Equal("Monthly Rent", saved!.Name);
|
||||
Assert.Equal("creator-1", saved.CreatedBy);
|
||||
Assert.Equal(1, await db.ExpenseSnapshotLines.CountAsync(l => l.SnapshotId == id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_WithNoLines_Throws()
|
||||
{
|
||||
var (svc, _) = Build();
|
||||
var r = Rent(); r.Lines.Clear();
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => svc.CreateAsync(r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_WithInvalidFunctionalClass_Throws()
|
||||
{
|
||||
var (svc, _) = Build();
|
||||
var r = Rent();
|
||||
r.Lines[0].FunctionalClass = "NotAClass";
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => svc.CreateAsync(r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetById_ReturnsLines_TotalsAndCreatorName()
|
||||
{
|
||||
var (svc, db) = Build("creator-1");
|
||||
db.Members.Add(new Member { Id = 5, FirstName_en = "Joy", LastName_en = "Wong" });
|
||||
db.Users.Add(new AppUser { Id = "creator-1", MemberId = 5 });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var id = await svc.CreateAsync(Rent());
|
||||
var dto = await svc.GetByIdAsync(id);
|
||||
|
||||
Assert.NotNull(dto);
|
||||
Assert.Equal(1200m, dto!.TotalAmount);
|
||||
Assert.Equal(1, dto.LineCount);
|
||||
Assert.Equal("Rent", dto.Lines.Single().SubCategoryName);
|
||||
Assert.Equal("Joy Wong", dto.CreatedByName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAll_ReturnsNewestFirst()
|
||||
{
|
||||
var (svc, _) = Build();
|
||||
var first = await svc.CreateAsync(Rent());
|
||||
var second = await svc.CreateAsync(Rent());
|
||||
|
||||
var all = await svc.GetAllAsync();
|
||||
|
||||
Assert.Equal(2, all.Count);
|
||||
Assert.Equal(second, all[0].Id);
|
||||
Assert.Equal(first, all[1].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_RenamesAndReplacesLines()
|
||||
{
|
||||
var (svc, db) = Build();
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 2, Name_en = "Utilities" });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 2, GroupId = 2, Name_en = "Internet" });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var id = await svc.CreateAsync(Rent());
|
||||
await svc.UpdateAsync(id, new UpdateExpenseSnapshotRequest
|
||||
{
|
||||
Name = "Monthly Internet", MinistryId = 1, Description = "ISP",
|
||||
Lines = { new ExpenseLineInput { CategoryGroupId = 2, SubCategoryId = 2, Amount = 80m } },
|
||||
});
|
||||
|
||||
var dto = await svc.GetByIdAsync(id);
|
||||
Assert.Equal("Monthly Internet", dto!.Name);
|
||||
Assert.Equal(80m, dto.TotalAmount);
|
||||
Assert.Equal("Internet", dto.Lines.Single().SubCategoryName);
|
||||
Assert.Equal(1, await db.ExpenseSnapshotLines.CountAsync(l => l.SnapshotId == id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_MissingId_Throws()
|
||||
{
|
||||
var (svc, _) = Build();
|
||||
await Assert.ThrowsAsync<KeyNotFoundException>(() => svc.UpdateAsync(999, new UpdateExpenseSnapshotRequest
|
||||
{
|
||||
Name = "x", MinistryId = 1, Description = "x",
|
||||
Lines = { new ExpenseLineInput { CategoryGroupId = 1, SubCategoryId = 1, Amount = 1m } },
|
||||
}));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_SoftDeletes_HidesFromQueries()
|
||||
{
|
||||
var (svc, db) = Build();
|
||||
var id = await svc.CreateAsync(Rent());
|
||||
|
||||
await svc.DeleteAsync(id);
|
||||
|
||||
Assert.Empty(await svc.GetAllAsync());
|
||||
Assert.Null(await db.ExpenseSnapshots.FirstOrDefaultAsync(s => s.Id == id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_StampsDeletedBy()
|
||||
{
|
||||
var (svc, db) = Build("deleter-1");
|
||||
var id = await svc.CreateAsync(Rent());
|
||||
await svc.DeleteAsync(id);
|
||||
var row = await db.ExpenseSnapshots.IgnoreQueryFilters().FirstAsync(s => s.Id == id);
|
||||
Assert.Equal("deleter-1", row.DeletedBy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using ROLAC.API.DTOs.Finance;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class Form1099FormServiceTests
|
||||
{
|
||||
/// <summary>Stub report service: only GetAnnualSummaryAsync is exercised by the CSV export.</summary>
|
||||
private sealed class StubReportService : IForm1099ReportService
|
||||
{
|
||||
private readonly Form1099SummaryDto _summary;
|
||||
public StubReportService(Form1099SummaryDto summary) => _summary = summary;
|
||||
|
||||
public Task<Form1099SummaryDto> GetAnnualSummaryAsync(int taxYear) => Task.FromResult(_summary);
|
||||
public Task<List<Form1099BoxDto>> GetBoxesAsync() => throw new NotImplementedException();
|
||||
public Task<Form1099RecipientDetailDto?> GetRecipientDetailAsync(int payeeId, int taxYear)
|
||||
=> throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static Form1099FormService BuildService(Form1099SummaryDto summary) =>
|
||||
// IPayee1099Service and AppDbContext are only used by RenderCopyBAsync, not by the CSV path.
|
||||
new Form1099FormService(new StubReportService(summary), payees: null!, db: null!);
|
||||
|
||||
[Fact]
|
||||
public async Task ExportFilingCsvAsync_WritesHeaderRowPerRecipientAndInvariantNumbers()
|
||||
{
|
||||
var summary = new Form1099SummaryDto
|
||||
{
|
||||
TaxYear = 2026,
|
||||
Rows =
|
||||
{
|
||||
new Form1099RecipientRowDto
|
||||
{
|
||||
PayeeId = 1, LegalName = "Acme, LLC", TinLast4 = "1234", W9Status = "OnFile",
|
||||
NecTotal = 1234.50m, RentsTotal = 0m, GrandTotal = 1234.50m, MeetsThreshold = true
|
||||
},
|
||||
new Form1099RecipientRowDto
|
||||
{
|
||||
PayeeId = 2, LegalName = "Bob Smith", TinLast4 = "9876", W9Status = "Missing",
|
||||
NecTotal = 100m, RentsTotal = 50m, GrandTotal = 150m, MeetsThreshold = false
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
var service = BuildService(summary);
|
||||
var (stream, contentType, fileName) = await service.ExportFilingCsvAsync(2026);
|
||||
|
||||
Assert.Equal("text/csv", contentType);
|
||||
Assert.Equal("1099-filing-2026.csv", fileName);
|
||||
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
var text = await reader.ReadToEndAsync();
|
||||
var lines = text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
// Header + one data line per row.
|
||||
Assert.Equal(3, lines.Length);
|
||||
Assert.Equal("LegalName,TinLast4,W9Status,Box1_NEC,Box1_Rents,Total,MeetsThreshold", lines[0]);
|
||||
|
||||
// A value containing a comma is quoted.
|
||||
Assert.StartsWith("\"Acme, LLC\",1234,OnFile,", lines[1]);
|
||||
|
||||
// Invariant numeric formatting (period decimal separator) and Y/N threshold flag.
|
||||
Assert.Contains("1234.50", lines[1]);
|
||||
Assert.EndsWith(",Y", lines[1]);
|
||||
Assert.EndsWith(",N", lines[2]);
|
||||
|
||||
// Sanity: the period really is the invariant separator regardless of current culture.
|
||||
Assert.Equal("1234.50", 1234.50m.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using System.Security.Claims;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class Form1099ReportServiceTests
|
||||
{
|
||||
private static AppDbContext NewDb()
|
||||
{
|
||||
var httpContext = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "t") })) };
|
||||
var accessorMock = new Mock<IHttpContextAccessor>();
|
||||
accessorMock.Setup(x => x.HttpContext).Returns(httpContext);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(accessorMock.Object))).Options);
|
||||
}
|
||||
|
||||
private static AppDbContext Seeded(out int necSubId, out int rentSubId, out int salarySubId)
|
||||
{
|
||||
var db = NewDb();
|
||||
db.Ministries.Add(new Ministry { Id = 1, Name_en = "Admin", DefaultFunctionalClass = "Program" });
|
||||
var nec = new Form1099Box { Id = 1, BoxCode = Form1099.BoxNec1, Name_en = "NEC", FormType = "1099-NEC", SortOrder = 1 };
|
||||
var rent = new Form1099Box { Id = 2, BoxCode = Form1099.BoxMisc1, Name_en = "Rent", FormType = "1099-MISC", SortOrder = 2 };
|
||||
db.Form1099Boxes.AddRange(nec, rent);
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 1, Name_en = "Personnel" });
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 2, Name_en = "Facility" });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 1, GroupId = 1, Name_en = "Contract Labor", Form1099BoxId = 1 });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 2, GroupId = 2, Name_en = "Rent", Form1099BoxId = 2 });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 3, GroupId = 1, Name_en = "Salary & Wages", Form1099BoxId = null });
|
||||
db.SaveChanges();
|
||||
necSubId = 1; rentSubId = 2; salarySubId = 3;
|
||||
return db;
|
||||
}
|
||||
|
||||
private static void AddPaidExpense(AppDbContext db, int payeeId, int subId, int groupId, decimal amount, DateOnly paidOn)
|
||||
{
|
||||
var e = new Expense
|
||||
{
|
||||
MinistryId = 1, Type = "VendorPayment", Status = "Paid", PayeeId = payeeId,
|
||||
Amount = amount, Description = "x", ExpenseDate = paidOn,
|
||||
PaidAt = new DateTimeOffset(paidOn.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero),
|
||||
Lines = [ new ExpenseLine { CategoryGroupId = groupId, SubCategoryId = subId, Amount = amount } ],
|
||||
};
|
||||
db.Expenses.Add(e);
|
||||
db.SaveChanges();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Sums_tracked_recipient_by_box_and_flags_threshold_and_w9()
|
||||
{
|
||||
var db = Seeded(out var necSub, out var rentSub, out _);
|
||||
db.Payee1099s.Add(new Payee1099 { Id = 10, LegalName = "Pat Player", Is1099Tracked = true, W9Status = "Missing" });
|
||||
db.SaveChanges();
|
||||
AddPaidExpense(db, 10, necSub, 1, 700m, new DateOnly(2026, 3, 1));
|
||||
AddPaidExpense(db, 10, rentSub, 2, 500m, new DateOnly(2026, 4, 1));
|
||||
|
||||
var svc = new Form1099ReportService(db);
|
||||
var sum = await svc.GetAnnualSummaryAsync(2026);
|
||||
|
||||
var row = Assert.Single(sum.Rows);
|
||||
Assert.Equal(700m, row.NecTotal);
|
||||
Assert.Equal(500m, row.RentsTotal);
|
||||
Assert.Equal(1200m, row.GrandTotal);
|
||||
Assert.True(row.MeetsThreshold);
|
||||
Assert.True(row.W9Missing);
|
||||
Assert.Equal(1, sum.RecipientsAtThreshold);
|
||||
Assert.Equal(1, sum.RecipientsMissingW9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Excludes_untracked_recipients_and_unmapped_and_wrong_year()
|
||||
{
|
||||
var db = Seeded(out var necSub, out _, out var salarySub);
|
||||
db.Payee1099s.Add(new Payee1099 { Id = 10, LegalName = "Tracked Tim", Is1099Tracked = true, W9Status = "OnFile" });
|
||||
db.Payee1099s.Add(new Payee1099 { Id = 11, LegalName = "Corp Inc", Is1099Tracked = false, W9Status = "OnFile" });
|
||||
db.SaveChanges();
|
||||
AddPaidExpense(db, 11, necSub, 1, 5000m, new DateOnly(2026, 5, 1)); // untracked
|
||||
AddPaidExpense(db, 10, salarySub, 1, 5000m, new DateOnly(2026, 6, 1)); // unmapped box
|
||||
AddPaidExpense(db, 10, necSub, 1, 5000m, new DateOnly(2025, 6, 1)); // wrong year
|
||||
|
||||
var sum = await new Form1099ReportService(db).GetAnnualSummaryAsync(2026);
|
||||
Assert.Empty(sum.Rows);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Threshold_flag_is_false_below_600()
|
||||
{
|
||||
var db = Seeded(out var necSub, out _, out _);
|
||||
db.Payee1099s.Add(new Payee1099 { Id = 10, LegalName = "Small Sam", Is1099Tracked = true, W9Status = "OnFile" });
|
||||
db.SaveChanges();
|
||||
AddPaidExpense(db, 10, necSub, 1, 599.99m, new DateOnly(2026, 7, 1));
|
||||
|
||||
var sum = await new Form1099ReportService(db).GetAnnualSummaryAsync(2026);
|
||||
var row = Assert.Single(sum.Rows);
|
||||
Assert.False(row.MeetsThreshold);
|
||||
Assert.False(row.W9Missing);
|
||||
Assert.Equal(0, sum.RecipientsAtThreshold);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class Form990ReportServiceTests
|
||||
{
|
||||
private static AppDbContext BuildDb()
|
||||
{
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "t") })) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(mock.Object))).Options);
|
||||
}
|
||||
|
||||
private static async Task SeedAsync(AppDbContext db)
|
||||
{
|
||||
db.Form990ExpenseLines.Add(new Form990ExpenseLine { Id = 7, LineCode = "7", Name_en = "Salaries", SortOrder = 5 });
|
||||
db.Form990ExpenseLines.Add(new Form990ExpenseLine { Id = 24, LineCode = "24", Name_en = "Other", SortOrder = 21 });
|
||||
db.Ministries.Add(new Ministry { Id = 1, Name_en = "Admin", DefaultFunctionalClass = "ManagementGeneral" });
|
||||
db.Ministries.Add(new Ministry { Id = 2, Name_en = "Worship", DefaultFunctionalClass = "Program" });
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 1, Name_en = "Personnel", Form990LineId = 24 });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 1, GroupId = 1, Name_en = "Salary", Form990LineId = 7 });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 2, GroupId = 1, Name_en = "Misc", Form990LineId = null });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private static Expense Exp(int min, int sub, decimal amt, string status, string? fc = null) => new()
|
||||
{
|
||||
MinistryId = min, Type = "VendorPayment",
|
||||
Status = status, Amount = amt, Description = "x", ExpenseDate = new DateOnly(2026, 5, 10),
|
||||
Lines = { new ExpenseLine { CategoryGroupId = 1, SubCategoryId = sub, Amount = amt, FunctionalClass = fc } },
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Statement_AggregatesByLineAndFunction_WithFallbackAndUnmappedCount()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
await SeedAsync(db);
|
||||
db.Expenses.Add(Exp(2, 1, 100m, "Paid"));
|
||||
db.Expenses.Add(Exp(1, 1, 40m, "Approved"));
|
||||
db.Expenses.Add(Exp(2, 2, 25m, "Paid"));
|
||||
db.Expenses.Add(Exp(2, 1, 999m, "Draft"));
|
||||
db.Expenses.Add(Exp(1, 1, 10m, "Paid", fc: "Program"));
|
||||
await db.SaveChangesAsync();
|
||||
var svc = new Form990ReportService(db);
|
||||
|
||||
var stmt = await svc.GetFunctionalExpenseStatementAsync(null, null);
|
||||
|
||||
var line7 = stmt.Rows.Single(r => r.LineCode == "7");
|
||||
Assert.Equal(110m, line7.Program);
|
||||
Assert.Equal(40m, line7.ManagementGeneral);
|
||||
Assert.Equal(150m, line7.Total);
|
||||
var line24 = stmt.Rows.Single(r => r.LineCode == "24");
|
||||
Assert.Equal(25m, line24.Program);
|
||||
Assert.Equal(1, stmt.UnmappedExpenseCount);
|
||||
Assert.Equal(175m, stmt.GrandTotal);
|
||||
Assert.Equal(135m, stmt.ProgramTotal);
|
||||
Assert.Equal(40m, stmt.ManagementGeneralTotal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Statement_RespectsDateRange()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
await SeedAsync(db);
|
||||
db.Expenses.Add(Exp(2, 1, 100m, "Paid"));
|
||||
var older = Exp(2, 1, 500m, "Paid"); older.ExpenseDate = new DateOnly(2026, 1, 1);
|
||||
db.Expenses.Add(older);
|
||||
await db.SaveChangesAsync();
|
||||
var svc = new Form990ReportService(db);
|
||||
|
||||
var stmt = await svc.GetFunctionalExpenseStatementAsync(new DateOnly(2026, 5, 1), new DateOnly(2026, 5, 31));
|
||||
Assert.Equal(100m, stmt.GrandTotal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Statement_SplitsOneExpenseAcrossLines()
|
||||
{
|
||||
// One invoice with two lines of different categories must land on two different 990 lines.
|
||||
using var db = BuildDb();
|
||||
await SeedAsync(db);
|
||||
db.Expenses.Add(new Expense
|
||||
{
|
||||
MinistryId = 2, Type = "VendorPayment", Status = "Paid", Amount = 70m,
|
||||
Description = "mixed", ExpenseDate = new DateOnly(2026, 5, 10),
|
||||
Lines =
|
||||
{
|
||||
new ExpenseLine { CategoryGroupId = 1, SubCategoryId = 1, Amount = 50m }, // sub→line 7
|
||||
new ExpenseLine { CategoryGroupId = 1, SubCategoryId = 2, Amount = 20m }, // sub unmapped→group fallback line 24
|
||||
},
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
var svc = new Form990ReportService(db);
|
||||
|
||||
var stmt = await svc.GetFunctionalExpenseStatementAsync(null, null);
|
||||
|
||||
Assert.Equal(50m, stmt.Rows.Single(r => r.LineCode == "7").Program); // ministry 2 default = Program
|
||||
Assert.Equal(20m, stmt.Rows.Single(r => r.LineCode == "24").Program);
|
||||
Assert.Equal(70m, stmt.GrandTotal);
|
||||
Assert.Equal(1, stmt.UnmappedExpenseCount); // one unmapped line
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Giving;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class GivingCategoryServiceTests
|
||||
{
|
||||
private static IHttpContextAccessor BuildAccessor(string userId = "test-user")
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return mock.Object;
|
||||
}
|
||||
|
||||
private static AppDbContext BuildDb(string userId = "test-user")
|
||||
{
|
||||
var interceptor = new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(BuildAccessor(userId)));
|
||||
return new AppDbContext(
|
||||
new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(interceptor)
|
||||
.Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_ReturnsId_AndDefaultsActive()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new GivingCategoryService(db);
|
||||
|
||||
var id = await svc.CreateAsync(new CreateGivingCategoryRequest { Name_en = "Tithe", Name_zh = "什一" });
|
||||
|
||||
var saved = await db.GivingCategories.FindAsync(id);
|
||||
Assert.NotNull(saved);
|
||||
Assert.True(saved!.IsActive);
|
||||
Assert.Equal("Tithe", saved.Name_en);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_ExcludesInactive_ByDefault()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new GivingCategoryService(db);
|
||||
var id1 = await svc.CreateAsync(new CreateGivingCategoryRequest { Name_en = "Active" });
|
||||
var id2 = await svc.CreateAsync(new CreateGivingCategoryRequest { Name_en = "Gone" });
|
||||
await svc.DeactivateAsync(id2);
|
||||
|
||||
var active = await svc.GetAllAsync(includeInactive: false);
|
||||
var all = await svc.GetAllAsync(includeInactive: true);
|
||||
|
||||
Assert.Single(active);
|
||||
Assert.Equal(2, all.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeactivateAsync_SetsIsActiveFalse()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new GivingCategoryService(db);
|
||||
var id = await svc.CreateAsync(new CreateGivingCategoryRequest { Name_en = "Temp" });
|
||||
|
||||
await svc.DeactivateAsync(id);
|
||||
|
||||
var saved = await db.GivingCategories.FindAsync(id);
|
||||
Assert.False(saved!.IsActive);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_Throws_WhenMissing()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new GivingCategoryService(db);
|
||||
await Assert.ThrowsAsync<KeyNotFoundException>(() =>
|
||||
svc.UpdateAsync(999, new UpdateGivingCategoryRequest { Name_en = "X" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeactivateAsync_Throws_WhenMissing()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new GivingCategoryService(db);
|
||||
await Assert.ThrowsAsync<KeyNotFoundException>(() => svc.DeactivateAsync(999));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Giving;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class GivingServiceTests
|
||||
{
|
||||
private static IHttpContextAccessor BuildAccessor(string userId = "test-user")
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return mock.Object;
|
||||
}
|
||||
|
||||
private static AppDbContext BuildDb(string userId = "test-user")
|
||||
{
|
||||
var interceptor = new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(BuildAccessor(userId)));
|
||||
return new AppDbContext(
|
||||
new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(interceptor)
|
||||
.Options);
|
||||
}
|
||||
|
||||
private static async Task<int> SeedCategoryAsync(AppDbContext db)
|
||||
{
|
||||
var c = new GivingCategory { Name_en = "Tithe", IsActive = true };
|
||||
db.GivingCategories.Add(c);
|
||||
await db.SaveChangesAsync();
|
||||
return c.Id;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_PersistsGiving()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new GivingService(db);
|
||||
|
||||
var id = await svc.CreateAsync(new CreateGivingRequest
|
||||
{
|
||||
GivingCategoryId = catId, Amount = 100m, PaymentMethod = "Cash",
|
||||
GivingDate = new DateOnly(2026, 5, 31), IsAnonymous = true,
|
||||
});
|
||||
|
||||
var saved = await db.Givings.FindAsync(id);
|
||||
Assert.NotNull(saved);
|
||||
Assert.Equal(100m, saved!.Amount);
|
||||
Assert.Null(saved.OfferingSessionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPagedAsync_FiltersByCategory()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new GivingService(db);
|
||||
await svc.CreateAsync(new CreateGivingRequest { GivingCategoryId = catId, Amount = 10m, PaymentMethod = "Cash", GivingDate = new DateOnly(2026,5,31) });
|
||||
|
||||
var page = await svc.GetPagedAsync(1, 20, null, catId, null, null);
|
||||
|
||||
Assert.Equal(1, page.TotalCount);
|
||||
Assert.Equal("Tithe", page.Items[0].CategoryName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_Throws_WhenGivingBelongsToSubmittedSession()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var session = new OfferingSession { SessionDate = new DateOnly(2026,5,31), Status = "Submitted" };
|
||||
db.OfferingSessions.Add(session);
|
||||
await db.SaveChangesAsync();
|
||||
var giving = new Giving { GivingCategoryId = catId, Amount = 50m, PaymentMethod = "Cash",
|
||||
GivingDate = new DateOnly(2026,5,31), OfferingSessionId = session.Id };
|
||||
db.Givings.Add(giving);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var svc = new GivingService(db);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
svc.UpdateAsync(giving.Id, new UpdateGivingRequest
|
||||
{ GivingCategoryId = catId, Amount = 999m, PaymentMethod = "Cash", GivingDate = new DateOnly(2026,5,31) }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAsync_Throws_WhenMissing()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new GivingService(db);
|
||||
await Assert.ThrowsAsync<KeyNotFoundException>(() => svc.DeleteAsync(999));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_Anonymous_NullsProvidedMemberId()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new GivingService(db);
|
||||
|
||||
var id = await svc.CreateAsync(new CreateGivingRequest
|
||||
{
|
||||
GivingCategoryId = catId, Amount = 25m, PaymentMethod = "Cash",
|
||||
GivingDate = new DateOnly(2026, 5, 31),
|
||||
IsAnonymous = true, MemberId = 12345, // provided, but must be stripped
|
||||
});
|
||||
|
||||
var saved = await db.Givings.FindAsync(id);
|
||||
Assert.True(saved!.IsAnonymous);
|
||||
Assert.Null(saved.MemberId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAsync_Throws_WhenGivingBelongsToSubmittedSession()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var session = new OfferingSession { SessionDate = new DateOnly(2026, 5, 31), Status = "Submitted" };
|
||||
db.OfferingSessions.Add(session);
|
||||
await db.SaveChangesAsync();
|
||||
var giving = new Giving { GivingCategoryId = catId, Amount = 50m, PaymentMethod = "Cash",
|
||||
GivingDate = new DateOnly(2026, 5, 31), OfferingSessionId = session.Id };
|
||||
db.Givings.Add(giving);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var svc = new GivingService(db);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => svc.DeleteAsync(giving.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPagedAsync_MatchesByMemberName()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var member = new Member { FirstName_en = "Grace", LastName_en = "Lee" };
|
||||
db.Members.Add(member);
|
||||
await db.SaveChangesAsync();
|
||||
var svc = new GivingService(db);
|
||||
await svc.CreateAsync(new CreateGivingRequest
|
||||
{
|
||||
GivingCategoryId = catId, Amount = 75m, PaymentMethod = "Cash",
|
||||
GivingDate = new DateOnly(2026, 5, 31), MemberId = member.Id,
|
||||
});
|
||||
|
||||
var page = await svc.GetPagedAsync(1, 20, "grace", null, null, null);
|
||||
|
||||
Assert.Equal(1, page.TotalCount);
|
||||
Assert.Equal(member.Id, page.Items[0].MemberId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using ROLAC.API.Services.Storage;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class LocalDiskFileStorageTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "rolac-test-" + Guid.NewGuid());
|
||||
|
||||
private LocalDiskFileStorage Build()
|
||||
{
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?> { ["Storage:LocalRoot"] = _root })
|
||||
.Build();
|
||||
return new LocalDiskFileStorage(config);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveThenOpen_RoundTrips()
|
||||
{
|
||||
var fs = Build();
|
||||
using var input = new MemoryStream(Encoding.UTF8.GetBytes("hello"));
|
||||
var path = await fs.SaveAsync(input, "finance/receipts/2026/5/1-r.txt");
|
||||
|
||||
await using var read = await fs.OpenReadAsync(path);
|
||||
Assert.NotNull(read);
|
||||
using var sr = new StreamReader(read!);
|
||||
Assert.Equal("hello", await sr.ReadToEndAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OpenRead_ReturnsNull_WhenMissing()
|
||||
{
|
||||
var fs = Build();
|
||||
Assert.Null(await fs.OpenReadAsync("finance/receipts/none.txt"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Save_RejectsPathTraversal()
|
||||
{
|
||||
var fs = Build();
|
||||
using var input = new MemoryStream(Encoding.UTF8.GetBytes("x"));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => fs.SaveAsync(input, "../escape.txt"));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class MealAttendanceServiceTests
|
||||
{
|
||||
// MealAttendance is auditable, so the InMemory provider requires CreatedBy/UpdatedBy
|
||||
// to be set before insert. Wire in the AuditSaveChangesInterceptor (as the other
|
||||
// service tests do) so those columns are stamped automatically on SaveChanges.
|
||||
private static AppDbContext BuildDb()
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "test-user") };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(
|
||||
new ROLAC.API.Services.Logging.CurrentUserAccessor(mock.Object))).Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetCountsAsync_CreatesRowWhenMissing_AndReturnsTotals()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MealAttendanceService(db);
|
||||
var date = new DateOnly(2026, 5, 31);
|
||||
|
||||
var result = await svc.SetCountsAsync(date, adult: 40, youth: 12, kid: 8);
|
||||
|
||||
Assert.Equal("2026-05-31", result.Date);
|
||||
Assert.Equal(40, result.Adult);
|
||||
Assert.Equal(12, result.Youth);
|
||||
Assert.Equal(8, result.Kid);
|
||||
Assert.Single(db.MealAttendances.Where(a => a.AttendanceDate == date));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetCountsAsync_OverwritesExistingRow_AndClampsNegativesToZero()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MealAttendanceService(db);
|
||||
var date = new DateOnly(2026, 5, 31);
|
||||
await svc.SetCountsAsync(date, 40, 12, 8);
|
||||
|
||||
var result = await svc.SetCountsAsync(date, adult: 50, youth: -3, kid: 0);
|
||||
|
||||
Assert.Equal(50, result.Adult);
|
||||
Assert.Equal(0, result.Youth); // negative clamped to zero
|
||||
Assert.Equal(0, result.Kid);
|
||||
Assert.Single(db.MealAttendances.Where(a => a.AttendanceDate == date)); // still one row
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Members;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class MemberServiceTests
|
||||
{
|
||||
private static IHttpContextAccessor BuildAccessor(string userId = "test-user")
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return mock.Object;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds an InMemory AppDbContext that includes the AuditSaveChangesInterceptor
|
||||
/// so that CreatedBy/UpdatedBy are stamped on save (required by InMemory null checks).
|
||||
/// </summary>
|
||||
private static AppDbContext BuildDb(string userId = "test-user")
|
||||
{
|
||||
var accessor = BuildAccessor(userId);
|
||||
var interceptor = new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(accessor));
|
||||
return new AppDbContext(
|
||||
new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(interceptor)
|
||||
.Options);
|
||||
}
|
||||
|
||||
// ── Create ───────────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_ReturnsNewId()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
var request = new CreateMemberRequest { FirstName_en = "Chris", LastName_en = "Chen" };
|
||||
|
||||
var id = await svc.CreateAsync(request);
|
||||
|
||||
Assert.True(id > 0);
|
||||
var saved = await db.Members.FindAsync(id);
|
||||
Assert.NotNull(saved);
|
||||
Assert.Equal("Chris", saved.FirstName_en);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_SavesNickName()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
var request = new CreateMemberRequest
|
||||
{ FirstName_en = "Yuan", LastName_en = "Chen", NickName = "Chris" };
|
||||
|
||||
var id = await svc.CreateAsync(request);
|
||||
var saved = await db.Members.FindAsync(id);
|
||||
|
||||
Assert.Equal("Chris", saved!.NickName);
|
||||
}
|
||||
|
||||
// ── GetById ──────────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_ReturnsDto_WhenExists()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
var id = await svc.CreateAsync(
|
||||
new CreateMemberRequest { FirstName_en = "A", LastName_en = "B" });
|
||||
|
||||
var dto = await svc.GetByIdAsync(id);
|
||||
|
||||
Assert.NotNull(dto);
|
||||
Assert.Equal(id, dto.Id);
|
||||
Assert.Equal("A", dto.FirstName_en);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_ReturnsNull_WhenNotFound()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
|
||||
var dto = await svc.GetByIdAsync(9999);
|
||||
|
||||
Assert.Null(dto);
|
||||
}
|
||||
|
||||
// ── GetPaged ─────────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task GetPagedAsync_FiltersOnSearch()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
await svc.CreateAsync(new CreateMemberRequest { FirstName_en = "Chris", LastName_en = "Chen" });
|
||||
await svc.CreateAsync(new CreateMemberRequest { FirstName_en = "Alice", LastName_en = "Wang" });
|
||||
|
||||
var result = await svc.GetPagedAsync(1, 20, "Chris", null, null);
|
||||
|
||||
Assert.Equal(1, result.TotalCount);
|
||||
Assert.Equal("Chris", result.Items[0].FirstName_en);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPagedAsync_FiltersOnStatus()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
await svc.CreateAsync(new CreateMemberRequest
|
||||
{ FirstName_en = "A", LastName_en = "A", Status = "Member" });
|
||||
await svc.CreateAsync(new CreateMemberRequest
|
||||
{ FirstName_en = "B", LastName_en = "B", Status = "Visitor" });
|
||||
|
||||
var result = await svc.GetPagedAsync(1, 20, null, "Visitor", null);
|
||||
|
||||
Assert.Equal(1, result.TotalCount);
|
||||
Assert.Equal("Visitor", result.Items[0].Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPagedAsync_SearchesNickName()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
await svc.CreateAsync(new CreateMemberRequest
|
||||
{ FirstName_en = "Yuan", LastName_en = "Chen", NickName = "Chris" });
|
||||
|
||||
var result = await svc.GetPagedAsync(1, 20, "Chris", null, null);
|
||||
|
||||
Assert.Equal(1, result.TotalCount);
|
||||
}
|
||||
|
||||
// ── Update ───────────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_PersistsChanges()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
var id = await svc.CreateAsync(
|
||||
new CreateMemberRequest { FirstName_en = "Old", LastName_en = "Name" });
|
||||
|
||||
await svc.UpdateAsync(id, new UpdateMemberRequest
|
||||
{ FirstName_en = "New", LastName_en = "Name", Country = "USA",
|
||||
Status = "Member", LanguagePreference = "en" });
|
||||
|
||||
var saved = await db.Members.FindAsync(id);
|
||||
Assert.Equal("New", saved!.FirstName_en);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_ThrowsKeyNotFound_WhenMissing()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
|
||||
await Assert.ThrowsAsync<KeyNotFoundException>(() =>
|
||||
svc.UpdateAsync(9999, new UpdateMemberRequest
|
||||
{ FirstName_en = "X", LastName_en = "Y", Country = "USA",
|
||||
Status = "Member", LanguagePreference = "en" }));
|
||||
}
|
||||
|
||||
// ── Delete (soft) ────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAsync_SoftDeletesMember()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor("deleter-id"));
|
||||
var id = await svc.CreateAsync(
|
||||
new CreateMemberRequest { FirstName_en = "A", LastName_en = "B" });
|
||||
|
||||
await svc.DeleteAsync(id);
|
||||
|
||||
// Query-filtered view returns null
|
||||
var filtered = await db.Members.FindAsync(id);
|
||||
Assert.Null(filtered);
|
||||
|
||||
// Raw view shows IsDeleted = true
|
||||
var raw = await db.Members.IgnoreQueryFilters()
|
||||
.FirstAsync(m => m.Id == id);
|
||||
Assert.True(raw.IsDeleted);
|
||||
Assert.Equal("deleter-id", raw.DeletedBy);
|
||||
Assert.NotNull(raw.DeletedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAsync_ThrowsKeyNotFound_WhenMissing()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MemberService(db, BuildAccessor());
|
||||
|
||||
await Assert.ThrowsAsync<KeyNotFoundException>(() => svc.DeleteAsync(9999));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Ministry;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class MinistryServiceTests
|
||||
{
|
||||
private static AppDbContext BuildDb()
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "test-user") };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(mock.Object))).Options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllAsync_OrdersBySortOrder_AndExcludesInactive()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
db.Ministries.AddRange(
|
||||
new Ministry { Name_en = "B", SortOrder = 2, IsActive = true },
|
||||
new Ministry { Name_en = "A", SortOrder = 1, IsActive = true },
|
||||
new Ministry { Name_en = "Z", SortOrder = 3, IsActive = false });
|
||||
await db.SaveChangesAsync();
|
||||
var svc = new MinistryService(db);
|
||||
|
||||
var active = await svc.GetAllAsync(includeInactive: false);
|
||||
var all = await svc.GetAllAsync(includeInactive: true);
|
||||
|
||||
Assert.Equal(2, active.Count);
|
||||
Assert.Equal("A", active[0].Name_en);
|
||||
Assert.Equal(3, all.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_DefaultsFunctionalClassToProgram_AndUpdateChangesIt()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = new MinistryService(db);
|
||||
var id = await svc.CreateAsync(new CreateMinistryRequest { Name_en = "Worship" });
|
||||
|
||||
var afterCreate = (await svc.GetAllAsync(true)).Single(m => m.Id == id);
|
||||
Assert.Equal("Program", afterCreate.DefaultFunctionalClass);
|
||||
|
||||
await svc.UpdateAsync(id, new UpdateMinistryRequest { Name_en = "Worship", DefaultFunctionalClass = "ManagementGeneral" });
|
||||
var afterUpdate = (await svc.GetAllAsync(true)).Single(m => m.Id == id);
|
||||
Assert.Equal("ManagementGeneral", afterUpdate.DefaultFunctionalClass);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Expense;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class MonthlyStatementServiceTests
|
||||
{
|
||||
private static AppDbContext BuildDb()
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "test-user") };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(mock.Object))).Options);
|
||||
}
|
||||
|
||||
private static MonthlyStatementService Build(AppDbContext db)
|
||||
{
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "test-user") })) };
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new MonthlyStatementService(db, mock.Object, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_ComputesGivingAndPaidExpenses_ForMonthOnly()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
db.GivingCategories.Add(new GivingCategory { Id = 1, Name_en = "Tithe" });
|
||||
db.Ministries.Add(new Ministry { Id = 1, Name_en = "Admin" });
|
||||
db.ExpenseCategoryGroups.Add(new ExpenseCategoryGroup { Id = 1, Name_en = "Other" });
|
||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 1, GroupId = 1, Name_en = "Misc" });
|
||||
db.Givings.Add(new Giving { GivingCategoryId = 1, Amount = 1000m, PaymentMethod = "Cash", GivingDate = new DateOnly(2026, 5, 10) });
|
||||
db.Givings.Add(new Giving { GivingCategoryId = 1, Amount = 500m, PaymentMethod = "Cash", GivingDate = new DateOnly(2026, 6, 1) });
|
||||
db.Expenses.Add(new Expense { MinistryId = 1, Type = "VendorPayment", Status = "Paid", Amount = 300m, Description = "x", ExpenseDate = new DateOnly(2026, 5, 20), Lines = { new ExpenseLine { CategoryGroupId = 1, SubCategoryId = 1, Amount = 300m } } });
|
||||
db.Expenses.Add(new Expense { MinistryId = 1, Type = "StaffReimbursement", Status = "Approved", Amount = 999m, Description = "not paid", ExpenseDate = new DateOnly(2026, 5, 21), Lines = { new ExpenseLine { CategoryGroupId = 1, SubCategoryId = 1, Amount = 999m } } });
|
||||
await db.SaveChangesAsync();
|
||||
var svc = Build(db);
|
||||
|
||||
var id = await svc.CreateAsync(new CreateMonthlyStatementRequest
|
||||
{ Year = 2026, Month = 5, OpeningBalance = 2000m, TotalOtherIncome = 100m, BankStatementBalance = 2800m });
|
||||
|
||||
var dto = await svc.GetByIdAsync(id);
|
||||
Assert.Equal(1000m, dto!.TotalGiving);
|
||||
Assert.Equal(300m, dto.TotalExpenses);
|
||||
Assert.Equal(2800m, dto.CalculatedClosingBalance);
|
||||
Assert.Equal(0m, dto.Difference);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_Duplicate_Throws()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = Build(db);
|
||||
await svc.CreateAsync(new CreateMonthlyStatementRequest { Year = 2026, Month = 5 });
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
svc.CreateAsync(new CreateMonthlyStatementRequest { Year = 2026, Month = 5 }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_AfterFinalize_Throws()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var svc = Build(db);
|
||||
var id = await svc.CreateAsync(new CreateMonthlyStatementRequest { Year = 2026, Month = 5 });
|
||||
await svc.FinalizeAsync(id);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
svc.UpdateAsync(id, new UpdateMonthlyStatementRequest { OpeningBalance = 1m }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using ROLAC.API.Services.Notifications;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services.Notifications;
|
||||
|
||||
public class EmailServiceTests
|
||||
{
|
||||
// Records every email it is asked to send; can be told to throw for a given address.
|
||||
private sealed class FakeSmtpDispatcher : ISmtpDispatcher
|
||||
{
|
||||
public List<OutboundEmail> Sent { get; } = new();
|
||||
public string? FailForAddress { get; set; }
|
||||
|
||||
public Task SendAsync(OutboundEmail email, CancellationToken ct = default)
|
||||
{
|
||||
if (email.ToAddress == FailForAddress)
|
||||
throw new InvalidOperationException("smtp rejected");
|
||||
Sent.Add(email);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private static CurrentUserAccessor BuildAccessor(string userId = "test-user")
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new CurrentUserAccessor(mock.Object);
|
||||
}
|
||||
|
||||
private static AppDbContext BuildDb()
|
||||
{
|
||||
var interceptor = new AuditSaveChangesInterceptor(BuildAccessor());
|
||||
return new AppDbContext(
|
||||
new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(interceptor)
|
||||
.Options);
|
||||
}
|
||||
|
||||
private static async Task<int> SeedMemberAsync(AppDbContext db, string? email)
|
||||
{
|
||||
var member = new Member { FirstName_en = "Test", LastName_en = "User", Email = email };
|
||||
db.Members.Add(member);
|
||||
await db.SaveChangesAsync();
|
||||
return member.Id;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_ResolvesMemberEmails_MergesRawAddresses_AndDedupes()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var memberId = await SeedMemberAsync(db, "member@example.com");
|
||||
var dispatcher = new FakeSmtpDispatcher();
|
||||
var service = new EmailService(db, dispatcher, BuildAccessor());
|
||||
|
||||
var message = new EmailMessage(
|
||||
MemberIds: new[] { memberId },
|
||||
Addresses: new[] { "extra@example.com", "member@example.com" }, // dup of member email
|
||||
Subject: "Hi", HtmlBody: "<p>Body</p>");
|
||||
|
||||
var result = await service.SendAsync(message);
|
||||
|
||||
Assert.Equal(2, result.SentCount); // member@ + extra@, dup dropped
|
||||
Assert.Equal(0, result.FailedCount);
|
||||
Assert.Equal(2, dispatcher.Sent.Count);
|
||||
Assert.Equal(2, await db.NotificationLogs.CountAsync(l => l.Status == NotificationStatuses.Sent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_SkipsMembersWithNoEmail()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var memberId = await SeedMemberAsync(db, null);
|
||||
var dispatcher = new FakeSmtpDispatcher();
|
||||
var service = new EmailService(db, dispatcher, BuildAccessor());
|
||||
|
||||
var result = await service.SendAsync(new EmailMessage(
|
||||
new[] { memberId }, Array.Empty<string>(), "Hi", "<p>Body</p>"));
|
||||
|
||||
Assert.Equal(0, result.SentCount);
|
||||
Assert.Empty(dispatcher.Sent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendAsync_LogsFailure_WithoutAbortingBatch()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var dispatcher = new FakeSmtpDispatcher { FailForAddress = "bad@example.com" };
|
||||
var service = new EmailService(db, dispatcher, BuildAccessor());
|
||||
|
||||
var result = await service.SendAsync(new EmailMessage(
|
||||
Array.Empty<int>(),
|
||||
new[] { "bad@example.com", "good@example.com" },
|
||||
"Hi", "<p>Body</p>"));
|
||||
|
||||
Assert.Equal(1, result.SentCount);
|
||||
Assert.Equal(1, result.FailedCount);
|
||||
Assert.Single(result.Failures);
|
||||
Assert.Equal("bad@example.com", result.Failures[0].Target);
|
||||
Assert.Equal(1, await db.NotificationLogs.CountAsync(l => l.Status == NotificationStatuses.Failed));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using ROLAC.API.Services.Notifications;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services.Notifications;
|
||||
|
||||
public class LineMessageChannelTests
|
||||
{
|
||||
// Stub settings provider returning fixed SMTP/Line values for the channel under test.
|
||||
private sealed class StubSettings : INotificationSettingsService
|
||||
{
|
||||
public SmtpOptions GetSmtp() => new();
|
||||
public LineOptions GetLine() => new() { ChannelAccessToken = "tok", ChannelSecret = "sec" };
|
||||
public void Reload() { }
|
||||
}
|
||||
|
||||
// Captures the outgoing request and returns a canned response.
|
||||
private sealed class CapturingHandler : HttpMessageHandler
|
||||
{
|
||||
public HttpRequestMessage? LastRequest { get; private set; }
|
||||
public string? LastBody { get; private set; }
|
||||
public HttpStatusCode StatusCode { get; set; } = HttpStatusCode.OK;
|
||||
public string ResponseBody { get; set; } = "{}";
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
LastRequest = request;
|
||||
LastBody = request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken);
|
||||
return new HttpResponseMessage(StatusCode) { Content = new StringContent(ResponseBody) };
|
||||
}
|
||||
}
|
||||
|
||||
private static LineMessageChannel BuildChannel(CapturingHandler handler)
|
||||
{
|
||||
var http = new HttpClient(handler);
|
||||
return new LineMessageChannel(http, new StubSettings());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PushToUserAsync_PostsTextMessage_WithBearerToken()
|
||||
{
|
||||
var handler = new CapturingHandler();
|
||||
var channel = BuildChannel(handler);
|
||||
|
||||
var result = await channel.PushToUserAsync("U123", "hello");
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal("https://api.line.me/v2/bot/message/push", handler.LastRequest!.RequestUri!.ToString());
|
||||
Assert.Equal("Bearer", handler.LastRequest.Headers.Authorization!.Scheme);
|
||||
Assert.Equal("tok", handler.LastRequest.Headers.Authorization.Parameter);
|
||||
|
||||
using var doc = JsonDocument.Parse(handler.LastBody!);
|
||||
Assert.Equal("U123", doc.RootElement.GetProperty("to").GetString());
|
||||
Assert.Equal("hello", doc.RootElement.GetProperty("messages")[0].GetProperty("text").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReplyAsync_PostsToReplyEndpoint_WithReplyToken()
|
||||
{
|
||||
var handler = new CapturingHandler();
|
||||
var channel = BuildChannel(handler);
|
||||
|
||||
await channel.ReplyAsync("RTOKEN", "hi back");
|
||||
|
||||
Assert.Equal("https://api.line.me/v2/bot/message/reply", handler.LastRequest!.RequestUri!.ToString());
|
||||
using var doc = JsonDocument.Parse(handler.LastBody!);
|
||||
Assert.Equal("RTOKEN", doc.RootElement.GetProperty("replyToken").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PushToUserAsync_ReturnsFailure_OnNonSuccessStatus()
|
||||
{
|
||||
var handler = new CapturingHandler { StatusCode = HttpStatusCode.TooManyRequests, ResponseBody = "quota" };
|
||||
var channel = BuildChannel(handler);
|
||||
|
||||
var result = await channel.PushToUserAsync("U123", "hello");
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Contains("429", result.Error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Entities.Notifications;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using ROLAC.API.Services.Notifications;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services.Notifications;
|
||||
|
||||
public class LineNotificationServiceTests
|
||||
{
|
||||
// Records pushes; can be told to fail every call.
|
||||
private sealed class FakeMessageChannel : IMessageChannel
|
||||
{
|
||||
public List<(string Target, string Text)> UserPushes { get; } = new();
|
||||
public List<(string Target, string Text)> GroupPushes { get; } = new();
|
||||
public bool Fail { get; set; }
|
||||
|
||||
public Task<MessageSendResult> PushToUserAsync(string externalId, string text, CancellationToken ct = default)
|
||||
{
|
||||
UserPushes.Add((externalId, text));
|
||||
return Task.FromResult(new MessageSendResult(!Fail, Fail ? "boom" : null));
|
||||
}
|
||||
public Task<MessageSendResult> PushToGroupAsync(string externalId, string text, CancellationToken ct = default)
|
||||
{
|
||||
GroupPushes.Add((externalId, text));
|
||||
return Task.FromResult(new MessageSendResult(!Fail, Fail ? "boom" : null));
|
||||
}
|
||||
public Task<MessageSendResult> ReplyAsync(string replyToken, string text, CancellationToken ct = default)
|
||||
=> Task.FromResult(new MessageSendResult(true, null));
|
||||
}
|
||||
|
||||
private static CurrentUserAccessor BuildAccessor(string userId = "test-user")
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return new CurrentUserAccessor(mock.Object);
|
||||
}
|
||||
|
||||
private static AppDbContext BuildDb()
|
||||
{
|
||||
var interceptor = new AuditSaveChangesInterceptor(BuildAccessor());
|
||||
return new AppDbContext(
|
||||
new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(interceptor)
|
||||
.Options);
|
||||
}
|
||||
|
||||
private static async Task<int> SeedMemberAsync(AppDbContext db)
|
||||
{
|
||||
var member = new Member { FirstName_en = "Test", LastName_en = "User" };
|
||||
db.Members.Add(member);
|
||||
await db.SaveChangesAsync();
|
||||
return member.Id;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GenerateLineBindingCodeAsync_PersistsUnconsumedCode()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var memberId = await SeedMemberAsync(db);
|
||||
var service = new LineNotificationService(db, new FakeMessageChannel());
|
||||
|
||||
var code = await service.GenerateLineBindingCodeAsync(memberId);
|
||||
|
||||
var stored = await db.LineBindingCodes.SingleAsync();
|
||||
Assert.Equal(code, stored.Code);
|
||||
Assert.Null(stored.ConsumedAt);
|
||||
Assert.True(stored.ExpiresAt > DateTime.UtcNow);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TryBindMemberAsync_BindsMember_AndConsumesCode()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var memberId = await SeedMemberAsync(db);
|
||||
var service = new LineNotificationService(db, new FakeMessageChannel());
|
||||
var code = await service.GenerateLineBindingCodeAsync(memberId);
|
||||
|
||||
var result = await service.TryBindMemberAsync("U999", code);
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal(memberId, result.MemberId);
|
||||
var binding = await db.MemberChannelBindings.SingleAsync();
|
||||
Assert.Equal("U999", binding.ExternalId);
|
||||
Assert.NotNull((await db.LineBindingCodes.SingleAsync()).ConsumedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TryBindMemberAsync_Fails_ForExpiredOrUsedOrUnknownCode()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var memberId = await SeedMemberAsync(db);
|
||||
db.LineBindingCodes.Add(new LineBindingCode
|
||||
{
|
||||
Code = "EXPIRE", MemberId = memberId, ExpiresAt = DateTime.UtcNow.AddMinutes(-1),
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
var service = new LineNotificationService(db, new FakeMessageChannel());
|
||||
|
||||
Assert.False((await service.TryBindMemberAsync("U1", "EXPIRE")).Success); // expired
|
||||
Assert.False((await service.TryBindMemberAsync("U1", "NOPE")).Success); // unknown
|
||||
Assert.Empty(await db.MemberChannelBindings.ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TryBindMemberAsync_Rebinds_UpdatesExistingBinding()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var memberId = await SeedMemberAsync(db);
|
||||
var service = new LineNotificationService(db, new FakeMessageChannel());
|
||||
await service.TryBindMemberAsync("U-OLD", await service.GenerateLineBindingCodeAsync(memberId));
|
||||
|
||||
await service.TryBindMemberAsync("U-NEW", await service.GenerateLineBindingCodeAsync(memberId));
|
||||
|
||||
var binding = await db.MemberChannelBindings.SingleAsync();
|
||||
Assert.Equal("U-NEW", binding.ExternalId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RegisterGroupAsync_IsIdempotent_AndDeactivateFlips()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var service = new LineNotificationService(db, new FakeMessageChannel());
|
||||
|
||||
await service.RegisterGroupAsync("G1");
|
||||
await service.RegisterGroupAsync("G1"); // second call must not duplicate
|
||||
Assert.Equal(1, await db.MessagingGroups.CountAsync());
|
||||
Assert.True((await db.MessagingGroups.SingleAsync()).IsActive);
|
||||
|
||||
await service.DeactivateGroupAsync("G1");
|
||||
Assert.False((await db.MessagingGroups.SingleAsync()).IsActive);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLineAsync_PushesToBoundMembersAndActiveGroups_AndLogs()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var memberId = await SeedMemberAsync(db);
|
||||
db.MemberChannelBindings.Add(new MemberChannelBinding
|
||||
{
|
||||
MemberId = memberId, Channel = "line", ExternalId = "U-MEM", BoundAt = DateTime.UtcNow,
|
||||
});
|
||||
var activeGroup = new MessagingGroup { Channel = "line", ExternalId = "G-ON", IsActive = true, RegisteredAt = DateTime.UtcNow };
|
||||
var deadGroup = new MessagingGroup { Channel = "line", ExternalId = "G-OFF", IsActive = false, RegisteredAt = DateTime.UtcNow };
|
||||
db.MessagingGroups.AddRange(activeGroup, deadGroup);
|
||||
await db.SaveChangesAsync();
|
||||
var channel = new FakeMessageChannel();
|
||||
var service = new LineNotificationService(db, channel);
|
||||
|
||||
var result = await service.SendLineAsync("notice", new[] { memberId },
|
||||
new[] { activeGroup.Id, deadGroup.Id }, "admin-1");
|
||||
|
||||
Assert.Equal(2, result.SentCount); // member + active group only
|
||||
Assert.Single(channel.UserPushes);
|
||||
Assert.Single(channel.GroupPushes); // inactive group skipped
|
||||
Assert.Equal(2, await db.NotificationLogs.CountAsync(l => l.Status == NotificationStatuses.Sent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLineAsync_RecordsFailures_WhenChannelFails()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var memberId = await SeedMemberAsync(db);
|
||||
db.MemberChannelBindings.Add(new MemberChannelBinding
|
||||
{
|
||||
MemberId = memberId, Channel = "line", ExternalId = "U-MEM", BoundAt = DateTime.UtcNow,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
var service = new LineNotificationService(db, new FakeMessageChannel { Fail = true });
|
||||
|
||||
var result = await service.SendLineAsync("notice", new[] { memberId }, Array.Empty<int>(), "admin-1");
|
||||
|
||||
Assert.Equal(0, result.SentCount);
|
||||
Assert.Equal(1, result.FailedCount);
|
||||
Assert.Equal(1, await db.NotificationLogs.CountAsync(l => l.Status == NotificationStatuses.Failed));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendLineAsync_SkipsSoftDeletedMembers()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var memberId = await SeedMemberAsync(db);
|
||||
db.MemberChannelBindings.Add(new MemberChannelBinding
|
||||
{
|
||||
MemberId = memberId, Channel = "line", ExternalId = "U-DEL", BoundAt = DateTime.UtcNow,
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
// Soft-delete the member.
|
||||
var member = await db.Members.FirstAsync(m => m.Id == memberId);
|
||||
member.IsDeleted = true;
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var channel = new FakeMessageChannel();
|
||||
var service = new LineNotificationService(db, channel);
|
||||
|
||||
var result = await service.SendLineAsync("notice", new[] { memberId }, Array.Empty<int>(), "admin-1");
|
||||
|
||||
Assert.Equal(0, result.SentCount);
|
||||
Assert.Empty(channel.UserPushes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ROLAC.API.Services.Notifications;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services.Notifications;
|
||||
|
||||
public class LineSignatureTests
|
||||
{
|
||||
private const string Secret = "test-channel-secret";
|
||||
|
||||
private static string Sign(string body)
|
||||
{
|
||||
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(Secret));
|
||||
return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(body)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValid_ReturnsTrue_ForMatchingSignature()
|
||||
{
|
||||
var body = """{"events":[]}""";
|
||||
var signature = Sign(body);
|
||||
|
||||
var result = LineSignature.IsValid(Secret, Encoding.UTF8.GetBytes(body), signature);
|
||||
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValid_ReturnsFalse_ForTamperedBody()
|
||||
{
|
||||
var signature = Sign("""{"events":[]}""");
|
||||
|
||||
var result = LineSignature.IsValid(Secret, Encoding.UTF8.GetBytes("""{"events":[1]}"""), signature);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsValid_ReturnsFalse_ForNullOrEmptyHeader()
|
||||
{
|
||||
var body = Encoding.UTF8.GetBytes("""{"events":[]}""");
|
||||
|
||||
Assert.False(LineSignature.IsValid(Secret, body, null));
|
||||
Assert.False(LineSignature.IsValid(Secret, body, ""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Giving;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using ROLAC.API.Services.Storage;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class OfferingSessionServiceTests
|
||||
{
|
||||
// Proof storage is not exercised by these tests; a no-op keeps the service constructible.
|
||||
private sealed class NoOpFileStorage : IFileStorage
|
||||
{
|
||||
public Task<string> SaveAsync(Stream content, string relativePath, CancellationToken ct = default)
|
||||
=> Task.FromResult(relativePath);
|
||||
public Task<Stream?> OpenReadAsync(string relativePath, CancellationToken ct = default)
|
||||
=> Task.FromResult<Stream?>(null);
|
||||
public Task DeleteAsync(string relativePath, CancellationToken ct = default)
|
||||
=> Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static IHttpContextAccessor BuildAccessor(string userId = "test-user")
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId) };
|
||||
var ctx = new DefaultHttpContext { User = new(new ClaimsIdentity(claims)) };
|
||||
var mock = new Mock<IHttpContextAccessor>();
|
||||
mock.Setup(x => x.HttpContext).Returns(ctx);
|
||||
return mock.Object;
|
||||
}
|
||||
|
||||
private static AppDbContext BuildDb(string userId = "test-user")
|
||||
{
|
||||
var interceptor = new AuditSaveChangesInterceptor(new ROLAC.API.Services.Logging.CurrentUserAccessor(BuildAccessor(userId)));
|
||||
return new AppDbContext(
|
||||
new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(interceptor)
|
||||
.Options);
|
||||
}
|
||||
|
||||
private static async Task<int> SeedCategoryAsync(AppDbContext db)
|
||||
{
|
||||
var c = new GivingCategory { Name_en = "Tithe", IsActive = true };
|
||||
db.GivingCategories.Add(c);
|
||||
await db.SaveChangesAsync();
|
||||
return c.Id;
|
||||
}
|
||||
|
||||
private static CreateOfferingSessionRequest BuildRequest(int catId, DateOnly date) => new()
|
||||
{
|
||||
SessionDate = date, CashTotal = 150m, CheckTotal = 0m,
|
||||
Givings =
|
||||
[
|
||||
new() { GivingCategoryId = catId, Amount = 100m, PaymentMethod = "Cash" },
|
||||
new() { GivingCategoryId = catId, Amount = 50m, PaymentMethod = "Cash", IsAnonymous = true },
|
||||
],
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_RecomputesSystemTotalAndDifference_ServerSide()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new OfferingSessionService(db, BuildAccessor(), new NoOpFileStorage());
|
||||
|
||||
var id = await svc.CreateAsync(BuildRequest(catId, new DateOnly(2026, 5, 31)));
|
||||
|
||||
var saved = await db.OfferingSessions.FindAsync(id);
|
||||
Assert.Equal("Submitted", saved!.Status);
|
||||
Assert.Equal(150m, saved.SystemTotal);
|
||||
Assert.Equal(0m, saved.Difference);
|
||||
Assert.NotNull(saved.SubmittedAt);
|
||||
Assert.Equal(2, await db.Givings.CountAsync(g => g.OfferingSessionId == id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_LinesGetSessionDateAndAnonymousNullsMember()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new OfferingSessionService(db, BuildAccessor(), new NoOpFileStorage());
|
||||
|
||||
var id = await svc.CreateAsync(BuildRequest(catId, new DateOnly(2026, 5, 31)));
|
||||
|
||||
var lines = await db.Givings.Where(g => g.OfferingSessionId == id).ToListAsync();
|
||||
Assert.All(lines, l => Assert.Equal(new DateOnly(2026,5,31), l.GivingDate));
|
||||
Assert.Contains(lines, l => l.IsAnonymous && l.MemberId == null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_Throws_OnDuplicateSessionDate()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new OfferingSessionService(db, BuildAccessor(), new NoOpFileStorage());
|
||||
await svc.CreateAsync(BuildRequest(catId, new DateOnly(2026, 5, 31)));
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
svc.CreateAsync(BuildRequest(catId, new DateOnly(2026, 5, 31))));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReplaceAsync_Throws_WhenSessionIsSubmitted()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new OfferingSessionService(db, BuildAccessor(), new NoOpFileStorage());
|
||||
var id = await svc.CreateAsync(BuildRequest(catId, new DateOnly(2026, 5, 31)));
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
svc.ReplaceAsync(id, BuildRequest(catId, new DateOnly(2026, 5, 31))));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReopenThenReplace_SwapsLinesAndResubmits()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new OfferingSessionService(db, BuildAccessor(), new NoOpFileStorage());
|
||||
var id = await svc.CreateAsync(BuildRequest(catId, new DateOnly(2026, 5, 31)));
|
||||
|
||||
await svc.ReopenAsync(id);
|
||||
var reopened = await db.OfferingSessions.FindAsync(id);
|
||||
Assert.Equal("Draft", reopened!.Status);
|
||||
|
||||
var newReq = new CreateOfferingSessionRequest
|
||||
{
|
||||
SessionDate = new DateOnly(2026,5,31), CashTotal = 200m, CheckTotal = 0m,
|
||||
Givings = [ new() { GivingCategoryId = catId, Amount = 200m, PaymentMethod = "Cash" } ],
|
||||
};
|
||||
await svc.ReplaceAsync(id, newReq);
|
||||
|
||||
var after = await db.OfferingSessions.FindAsync(id);
|
||||
Assert.Equal("Submitted", after!.Status);
|
||||
Assert.Equal(200m, after.SystemTotal);
|
||||
Assert.Equal(1, await db.Givings.CountAsync(g => g.OfferingSessionId == id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByIdAsync_ReturnsCheckZelleAndPayPalRefs()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new OfferingSessionService(db, BuildAccessor(), new NoOpFileStorage());
|
||||
var req = new CreateOfferingSessionRequest
|
||||
{
|
||||
SessionDate = new DateOnly(2026, 6, 7), CashTotal = 0m, CheckTotal = 100m,
|
||||
Givings = [ new() { GivingCategoryId = catId, Amount = 100m, PaymentMethod = "Zelle",
|
||||
ZelleReferenceCode = "Z-123", PayPalTransactionId = "PP-456", CheckNumber = "C-789" } ],
|
||||
};
|
||||
var id = await svc.CreateAsync(req);
|
||||
|
||||
var dto = await svc.GetByIdAsync(id);
|
||||
|
||||
Assert.NotNull(dto);
|
||||
var line = Assert.Single(dto!.Givings);
|
||||
Assert.Equal("Z-123", line.ZelleReferenceCode);
|
||||
Assert.Equal("PP-456", line.PayPalTransactionId);
|
||||
Assert.Equal("C-789", line.CheckNumber);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPagedAsync_IncludesSundayAttendanceTotal_WhenRowExists()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var catId = await SeedCategoryAsync(db);
|
||||
var svc = new OfferingSessionService(db, BuildAccessor(), new NoOpFileStorage());
|
||||
|
||||
var withDate = new DateOnly(2026, 5, 31);
|
||||
var withoutDate = new DateOnly(2026, 5, 24);
|
||||
await svc.CreateAsync(BuildRequest(catId, withDate));
|
||||
await svc.CreateAsync(BuildRequest(catId, withoutDate));
|
||||
db.MealAttendances.Add(new MealAttendance
|
||||
{ AttendanceDate = withDate, AdultCount = 40, YouthCount = 12, KidCount = 8 });
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var page = await svc.GetPagedAsync(1, 20, null, null);
|
||||
|
||||
var withItem = page.Items.Single(i => i.SessionDate == "2026-05-31");
|
||||
var withoutItem = page.Items.Single(i => i.SessionDate == "2026-05-24");
|
||||
Assert.Equal(60, withItem.SundayAttendanceCount); // 40 + 12 + 8
|
||||
Assert.Null(withoutItem.SundayAttendanceCount); // no attendance row -> null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using System.Security.Claims;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.Data.Interceptors;
|
||||
using ROLAC.API.DTOs.Payee;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using ROLAC.API.Services.Security;
|
||||
using ROLAC.API.Services.Storage;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class Payee1099ServiceTests
|
||||
{
|
||||
// Minimal in-memory IFileStorage (mirrors the ExpenseServiceTests fake).
|
||||
private sealed class FakeStorage : IFileStorage
|
||||
{
|
||||
public Dictionary<string, byte[]> Files = new();
|
||||
public Task<string> SaveAsync(Stream c, string p, CancellationToken ct = default)
|
||||
{ using var ms = new MemoryStream(); c.CopyTo(ms); Files[p] = ms.ToArray(); return Task.FromResult(p); }
|
||||
public Task<Stream?> OpenReadAsync(string p, CancellationToken ct = default)
|
||||
=> Task.FromResult<Stream?>(Files.TryGetValue(p, out var b) ? new MemoryStream(b) : null);
|
||||
public Task DeleteAsync(string p, CancellationToken ct = default) { Files.Remove(p); return Task.CompletedTask; }
|
||||
}
|
||||
|
||||
private static (Payee1099Service svc, AppDbContext db) Build()
|
||||
{
|
||||
var httpContext = new DefaultHttpContext { User = new(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "test-user") })) };
|
||||
var accessorMock = new Mock<IHttpContextAccessor>();
|
||||
accessorMock.Setup(x => x.HttpContext).Returns(httpContext);
|
||||
var db = new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.AddInterceptors(new AuditSaveChangesInterceptor(new CurrentUserAccessor(accessorMock.Object))).Options);
|
||||
var tin = new TinProtector(DataProtectionProvider.Create("ROLAC.Tests"));
|
||||
return (new Payee1099Service(db, tin, new FakeStorage()), db);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_encrypts_tin_and_stores_last4_only_in_clear()
|
||||
{
|
||||
var (svc, db) = Build();
|
||||
var id = await svc.CreateAsync(new SavePayee1099Request
|
||||
{ LegalName = "Pat Player", TinType = "SSN", Tin = "123-45-6789", W9Status = "OnFile" });
|
||||
|
||||
var saved = await db.Payee1099s.FindAsync(id);
|
||||
Assert.NotNull(saved);
|
||||
Assert.Equal("6789", saved!.TinLast4);
|
||||
Assert.NotNull(saved.TinEncrypted);
|
||||
Assert.DoesNotContain("123-45-6789", saved.TinEncrypted!);
|
||||
Assert.Equal("123-45-6789", await svc.RevealTinAsync(id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_with_null_tin_keeps_existing_ciphertext()
|
||||
{
|
||||
var (svc, db) = Build();
|
||||
var id = await svc.CreateAsync(new SavePayee1099Request { LegalName = "X", Tin = "11-2223333" });
|
||||
var before = (await db.Payee1099s.FindAsync(id))!.TinEncrypted;
|
||||
|
||||
await svc.UpdateAsync(id, new SavePayee1099Request { LegalName = "X renamed", Tin = null });
|
||||
|
||||
var after = await db.Payee1099s.FindAsync(id);
|
||||
Assert.Equal("X renamed", after!.LegalName);
|
||||
Assert.Equal(before, after.TinEncrypted);
|
||||
Assert.Equal("3333", after.TinLast4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_dto_masks_tin_to_last4()
|
||||
{
|
||||
var (svc, _) = Build();
|
||||
await svc.CreateAsync(new SavePayee1099Request { LegalName = "Y", Tin = "999-88-7777" });
|
||||
var list = await svc.GetAllAsync(includeInactive: true);
|
||||
var item = Assert.Single(list);
|
||||
Assert.Equal("7777", item.TinLast4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_is_soft_and_hides_from_list()
|
||||
{
|
||||
var (svc, _) = Build();
|
||||
var id = await svc.CreateAsync(new SavePayee1099Request { LegalName = "Z" });
|
||||
await svc.DeleteAsync(id);
|
||||
Assert.Empty(await svc.GetAllAsync(includeInactive: true));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveW9_records_document_and_round_trips_bytes()
|
||||
{
|
||||
var (svc, _) = Build();
|
||||
var id = await svc.CreateAsync(new SavePayee1099Request { LegalName = "W9 Payee" });
|
||||
|
||||
var bytes = new byte[] { 1, 2, 3, 4, 5 };
|
||||
await svc.SaveW9Async(id, new MemoryStream(bytes), "w9.pdf");
|
||||
|
||||
var dto = await svc.GetByIdAsync(id);
|
||||
Assert.NotNull(dto);
|
||||
Assert.True(dto!.HasW9Document);
|
||||
|
||||
var opened = await svc.OpenW9Async(id);
|
||||
Assert.NotNull(opened);
|
||||
Assert.Equal("application/pdf", opened!.Value.contentType);
|
||||
using var ms = new MemoryStream();
|
||||
await opened.Value.stream.CopyToAsync(ms);
|
||||
Assert.Equal(bytes, ms.ToArray());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.DTOs.Permissions;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class PermissionServiceTests
|
||||
{
|
||||
// -----------------------------------------------------------------------
|
||||
// Harness: a real PermissionService backed by an in-memory EF database.
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public required ServiceProvider Provider { get; init; }
|
||||
public required PermissionService Service { get; init; }
|
||||
|
||||
public async Task SeedRoleAsync(string roleName, params RolePermission[] permissions)
|
||||
{
|
||||
using var scope = Provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
|
||||
var role = new AppRole { Id = $"role-{roleName}", Name = roleName, NormalizedName = roleName.ToUpperInvariant() };
|
||||
db.Roles.Add(role);
|
||||
foreach (var permission in permissions)
|
||||
{
|
||||
permission.RoleId = role.Id;
|
||||
db.RolePermissions.Add(permission);
|
||||
}
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static Harness BuildHarness()
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString();
|
||||
var services = new ServiceCollection();
|
||||
services.AddDbContext<AppDbContext>(opt => opt.UseInMemoryDatabase(dbName));
|
||||
var provider = services.BuildServiceProvider();
|
||||
|
||||
var scopeFactory = provider.GetRequiredService<IServiceScopeFactory>();
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
return new Harness
|
||||
{
|
||||
Provider = provider,
|
||||
Service = new PermissionService(scopeFactory, cache,
|
||||
new ROLAC.API.Services.Logging.SystemLogQueue(),
|
||||
new Microsoft.AspNetCore.Http.HttpContextAccessor()),
|
||||
};
|
||||
}
|
||||
|
||||
private static RolePermission Perm(string module, bool r = false, bool w = false, bool d = false, bool a = false)
|
||||
=> new() { Module = module, CanRead = r, CanWrite = w, CanDelete = d, CanApprove = a };
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// HasPermissionAsync
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermission_RoleGrantsAction_ReturnsTrue()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
await h.SeedRoleAsync("finance", Perm(Modules.Givings, r: true, w: true));
|
||||
|
||||
Assert.True(await h.Service.HasPermissionAsync(["finance"], Modules.Givings, PermissionActions.Read));
|
||||
Assert.True(await h.Service.HasPermissionAsync(["finance"], Modules.Givings, PermissionActions.Write));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermission_RoleLacksAction_ReturnsFalse()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
await h.SeedRoleAsync("finance", Perm(Modules.Givings, r: true)); // read only
|
||||
|
||||
Assert.False(await h.Service.HasPermissionAsync(["finance"], Modules.Givings, PermissionActions.Delete));
|
||||
Assert.False(await h.Service.HasPermissionAsync(["finance"], Modules.Members, PermissionActions.Read));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasPermission_UnionAcrossRoles_ReturnsTrueIfAnyRoleGrants()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
await h.SeedRoleAsync("pastor", Perm(Modules.Members, r: true));
|
||||
await h.SeedRoleAsync("finance", Perm(Modules.Givings, r: true, w: true));
|
||||
|
||||
// User holds both roles — should get the union.
|
||||
Assert.True(await h.Service.HasPermissionAsync(["pastor", "finance"], Modules.Members, PermissionActions.Read));
|
||||
Assert.True(await h.Service.HasPermissionAsync(["pastor", "finance"], Modules.Givings, PermissionActions.Write));
|
||||
Assert.False(await h.Service.HasPermissionAsync(["pastor", "finance"], Modules.Members, PermissionActions.Delete));
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// GetEffectivePermissionsAsync
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task GetEffectivePermissions_SuperAdmin_ReturnsAllModulesFull()
|
||||
{
|
||||
var h = BuildHarness(); // no rows seeded at all
|
||||
|
||||
var effective = await h.Service.GetEffectivePermissionsAsync(["super_admin"]);
|
||||
|
||||
Assert.Equal(Modules.All.Count, effective.Count);
|
||||
foreach (var module in Modules.All)
|
||||
{
|
||||
Assert.True(effective[module].Read);
|
||||
Assert.True(effective[module].Write);
|
||||
Assert.True(effective[module].Delete);
|
||||
Assert.True(effective[module].Approve);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEffectivePermissions_MergesFlagsAcrossRoles()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
await h.SeedRoleAsync("a", Perm(Modules.Expenses, r: true));
|
||||
await h.SeedRoleAsync("b", Perm(Modules.Expenses, w: true, a: true));
|
||||
|
||||
var effective = await h.Service.GetEffectivePermissionsAsync(["a", "b"]);
|
||||
|
||||
Assert.True(effective[Modules.Expenses].Read);
|
||||
Assert.True(effective[Modules.Expenses].Write);
|
||||
Assert.True(effective[Modules.Expenses].Approve);
|
||||
Assert.False(effective[Modules.Expenses].Delete);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEffectivePermissions_OmitsModulesWithNoGrant()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
await h.SeedRoleAsync("member"); // role exists but no grants
|
||||
|
||||
var effective = await h.Service.GetEffectivePermissionsAsync(["member"]);
|
||||
|
||||
Assert.Empty(effective);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Caching / invalidation via UpsertRoleAsync
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertRole_InvalidatesCache_SoNextCheckReflectsNewState()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
await h.SeedRoleAsync("finance", Perm(Modules.Givings, r: true)); // read only
|
||||
|
||||
// Prime the cache with the original snapshot.
|
||||
Assert.False(await h.Service.HasPermissionAsync(["finance"], Modules.Givings, PermissionActions.Write));
|
||||
|
||||
// Grant write; UpsertRoleAsync must invalidate the cache.
|
||||
await h.Service.UpsertRoleAsync("finance", [new ModulePermissionDto
|
||||
{
|
||||
Module = Modules.Givings, CanRead = true, CanWrite = true,
|
||||
}]);
|
||||
|
||||
Assert.True(await h.Service.HasPermissionAsync(["finance"], Modules.Givings, PermissionActions.Write));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertRole_SuperAdmin_Throws()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
await h.SeedRoleAsync("super_admin");
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(
|
||||
() => h.Service.UpsertRoleAsync("super_admin", [new ModulePermissionDto { Module = Modules.Members, CanRead = true }]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertRole_UnknownRole_Throws()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
|
||||
await Assert.ThrowsAsync<KeyNotFoundException>(
|
||||
() => h.Service.UpsertRoleAsync("ghost", [new ModulePermissionDto { Module = Modules.Members, CanRead = true }]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using ROLAC.API.Services.Security;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class TinProtectorTests
|
||||
{
|
||||
private static TinProtector Build() =>
|
||||
new TinProtector(DataProtectionProvider.Create("ROLAC.Tests"));
|
||||
|
||||
[Fact]
|
||||
public void Protect_then_Unprotect_round_trips()
|
||||
{
|
||||
var p = Build();
|
||||
var cipher = p.Protect("123-45-6789");
|
||||
Assert.NotEqual("123-45-6789", cipher);
|
||||
Assert.Equal("123-45-6789", p.Unprotect(cipher));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("123-45-6789", "6789")]
|
||||
[InlineData("12-3456789", "6789")]
|
||||
[InlineData("7", "7")]
|
||||
public void Last4_keeps_only_trailing_digits(string raw, string expected)
|
||||
=> Assert.Equal(expected, TinProtector.Last4(raw));
|
||||
|
||||
[Fact]
|
||||
public void Last4_of_null_is_null() => Assert.Null(TinProtector.Last4(null));
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class TokenServiceTests
|
||||
{
|
||||
private readonly TokenService _sut;
|
||||
|
||||
public TokenServiceTests()
|
||||
{
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
{ "Jwt:SecretKey", "test-secret-key-that-is-at-least-32-characters-long!!" },
|
||||
{ "Jwt:Issuer", "rolac-api-test" },
|
||||
{ "Jwt:Audience", "rolac-client-test" },
|
||||
{ "Jwt:AccessTokenExpiryMinutes", "15" },
|
||||
{ "Jwt:RefreshTokenExpiryDays", "30" },
|
||||
})
|
||||
.Build();
|
||||
|
||||
_sut = new TokenService(config);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Base64Url-decodes the payload segment of a JWT and returns it as a
|
||||
/// <see cref="JsonDocument"/>. Caller is responsible for disposing.
|
||||
/// </summary>
|
||||
private static JsonDocument ReadJwtPayload(string token)
|
||||
{
|
||||
var b64 = token.Split('.')[1];
|
||||
var mod4 = b64.Length % 4;
|
||||
if (mod4 > 0) b64 += new string('=', 4 - mod4);
|
||||
var bytes = Convert.FromBase64String(b64.Replace('-', '+').Replace('_', '/'));
|
||||
return JsonDocument.Parse(bytes);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GenerateAccessToken
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void GenerateAccessToken_ReturnsValidJwt_WithUserIdAndRoles()
|
||||
{
|
||||
var user = new AppUser { Id = "user-123", Email = "test@rolac.org", UserName = "test@rolac.org" };
|
||||
var roles = new List<string> { "member", "finance" };
|
||||
|
||||
var token = _sut.GenerateAccessToken(user, roles);
|
||||
|
||||
Assert.NotEmpty(token);
|
||||
|
||||
// Decode payload without touching any Microsoft.IdentityModel API so that
|
||||
// library version mismatches (7.1.2 vs 7.5.2) cannot affect this test.
|
||||
using var doc = ReadJwtPayload(token);
|
||||
var root = doc.RootElement;
|
||||
|
||||
Assert.Equal("user-123", root.GetProperty("sub").GetString());
|
||||
Assert.Equal("test@rolac.org", root.GetProperty("email").GetString());
|
||||
|
||||
// JwtSecurityTokenHandler's DefaultOutboundClaimTypeMap maps
|
||||
// ClaimTypes.Role → "role", so roles land under the "role" key.
|
||||
// When multiple claims share a type they are serialised as a JSON array.
|
||||
var roleEl = root.GetProperty("role");
|
||||
var roleClaims = roleEl.ValueKind == JsonValueKind.Array
|
||||
? roleEl.EnumerateArray().Select(e => e.GetString()!).ToList()
|
||||
: new List<string> { roleEl.GetString()! };
|
||||
|
||||
Assert.Contains("member", roleClaims);
|
||||
Assert.Contains("finance", roleClaims);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateAccessToken_ExpiresIn15Minutes()
|
||||
{
|
||||
var user = new AppUser { Id = "user-123", Email = "test@rolac.org", UserName = "test@rolac.org" };
|
||||
|
||||
var token = _sut.GenerateAccessToken(user, new List<string>());
|
||||
|
||||
using var doc = ReadJwtPayload(token);
|
||||
var expUnix = doc.RootElement.GetProperty("exp").GetInt64();
|
||||
var expectedUnix = DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds();
|
||||
|
||||
// Allow ±2 s for test execution time.
|
||||
Assert.InRange(expUnix, expectedUnix - 2, expectedUnix + 2);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GenerateRefreshToken
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void GenerateRefreshToken_Returns86CharUrlSafeBase64()
|
||||
{
|
||||
var token = _sut.GenerateRefreshToken();
|
||||
|
||||
Assert.NotEmpty(token);
|
||||
// 64 bytes → 88 standard Base64 chars → 86 URL-safe chars (no '==' padding,
|
||||
// '+' → '-', '/' → '_'). All chars must be unreserved in RFC 6265 cookie-values.
|
||||
Assert.Equal(86, token.Length);
|
||||
Assert.True(
|
||||
token.All(c => char.IsLetterOrDigit(c) || c == '-' || c == '_'),
|
||||
"Token must use URL-safe Base64 alphabet (A-Z a-z 0-9 - _)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GenerateRefreshToken_ProducesUniqueTokensEachCall()
|
||||
{
|
||||
var token1 = _sut.GenerateRefreshToken();
|
||||
var token2 = _sut.GenerateRefreshToken();
|
||||
|
||||
Assert.NotEqual(token1, token2);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HashToken
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void HashToken_SameInputProducesSameHash()
|
||||
{
|
||||
const string raw = "some-raw-token-value";
|
||||
|
||||
var hash1 = _sut.HashToken(raw);
|
||||
var hash2 = _sut.HashToken(raw);
|
||||
|
||||
Assert.Equal(hash1, hash2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HashToken_DifferentInputsProduceDifferentHashes()
|
||||
{
|
||||
var hash1 = _sut.HashToken("token-a");
|
||||
var hash2 = _sut.HashToken("token-b");
|
||||
|
||||
Assert.NotEqual(hash1, hash2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HashToken_Returns64CharLowercaseHexString()
|
||||
{
|
||||
var hash = _sut.HashToken("any-token");
|
||||
|
||||
Assert.Equal(64, hash.Length);
|
||||
Assert.True(hash.All(c => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.DTOs.Users;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace ROLAC.API.Tests.Services;
|
||||
|
||||
public class UserManagementServiceTests
|
||||
{
|
||||
private static AppDbContext BuildDb() =>
|
||||
new(new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options);
|
||||
|
||||
private static Mock<UserManager<AppUser>> BuildUserManager(
|
||||
AppUser? findResult = null,
|
||||
bool createOk = true,
|
||||
IList<string>? roles = null)
|
||||
{
|
||||
var store = new Mock<IUserStore<AppUser>>();
|
||||
#pragma warning disable CS8625
|
||||
var mgr = new Mock<UserManager<AppUser>>(
|
||||
store.Object, null, null, null, null, null, null, null, null);
|
||||
#pragma warning restore CS8625
|
||||
mgr.Setup(m => m.FindByIdAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync(findResult);
|
||||
mgr.Setup(m => m.FindByEmailAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync((AppUser?)null);
|
||||
mgr.Setup(m => m.CreateAsync(It.IsAny<AppUser>(), It.IsAny<string>()))
|
||||
.ReturnsAsync(createOk ? IdentityResult.Success
|
||||
: IdentityResult.Failed(new IdentityError { Description = "fail" }));
|
||||
mgr.Setup(m => m.AddToRolesAsync(It.IsAny<AppUser>(), It.IsAny<IEnumerable<string>>()))
|
||||
.ReturnsAsync(IdentityResult.Success);
|
||||
mgr.Setup(m => m.GetRolesAsync(It.IsAny<AppUser>()))
|
||||
.ReturnsAsync(roles ?? new List<string> { "member" });
|
||||
mgr.Setup(m => m.UpdateAsync(It.IsAny<AppUser>()))
|
||||
.ReturnsAsync(IdentityResult.Success);
|
||||
mgr.Setup(m => m.RemoveFromRolesAsync(It.IsAny<AppUser>(), It.IsAny<IEnumerable<string>>()))
|
||||
.ReturnsAsync(IdentityResult.Success);
|
||||
mgr.Setup(m => m.GeneratePasswordResetTokenAsync(It.IsAny<AppUser>()))
|
||||
.ReturnsAsync("reset-token");
|
||||
mgr.Setup(m => m.ResetPasswordAsync(It.IsAny<AppUser>(), It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ReturnsAsync(IdentityResult.Success);
|
||||
return mgr;
|
||||
}
|
||||
|
||||
// ── CreateAsync ──────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_ReturnsTempPassword()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
// Seed a Member so MemberId validation passes
|
||||
// Note: InMemory DB requires audit fields — we set them directly
|
||||
var member = new Member
|
||||
{
|
||||
FirstName_en = "A", LastName_en = "B",
|
||||
CreatedBy = "system", UpdatedBy = "system",
|
||||
CreatedAt = DateTimeOffset.UtcNow, UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
db.Members.Add(member);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var mgr = BuildUserManager();
|
||||
// Capture the AppUser passed to CreateAsync
|
||||
AppUser? created = null;
|
||||
mgr.Setup(m => m.CreateAsync(It.IsAny<AppUser>(), It.IsAny<string>()))
|
||||
.Callback<AppUser, string>((u, _) => { created = u; u.Id = Guid.NewGuid().ToString(); })
|
||||
.ReturnsAsync(IdentityResult.Success);
|
||||
|
||||
// Mock Users queryable to return empty (no existing user for this member)
|
||||
mgr.Setup(m => m.Users)
|
||||
.Returns(new List<AppUser>().AsQueryable());
|
||||
|
||||
var svc = new UserManagementService(mgr.Object, db, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
var result = await svc.CreateAsync(new CreateUserRequest
|
||||
{
|
||||
MemberId = member.Id,
|
||||
Email = "test@rolac.org",
|
||||
Roles = ["member"],
|
||||
});
|
||||
|
||||
Assert.False(string.IsNullOrEmpty(result.TempPassword));
|
||||
Assert.Equal(12, result.TempPassword.Length);
|
||||
Assert.NotNull(created);
|
||||
Assert.Equal(member.Id, created!.MemberId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_Throws_WhenMemberNotFound()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var mgr = BuildUserManager();
|
||||
mgr.Setup(m => m.Users)
|
||||
.Returns(new List<AppUser>().AsQueryable());
|
||||
var svc = new UserManagementService(mgr.Object, db, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
svc.CreateAsync(new CreateUserRequest
|
||||
{ MemberId = 9999, Email = "x@y.com", Roles = ["member"] }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_Throws_WhenMemberAlreadyHasUser()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var member = new Member
|
||||
{
|
||||
FirstName_en = "A", LastName_en = "B",
|
||||
CreatedBy = "system", UpdatedBy = "system",
|
||||
CreatedAt = DateTimeOffset.UtcNow, UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
db.Members.Add(member);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var existingUser = new AppUser
|
||||
{
|
||||
Id = Guid.NewGuid().ToString(),
|
||||
UserName = "existing@test.com",
|
||||
Email = "existing@test.com",
|
||||
MemberId = member.Id,
|
||||
};
|
||||
db.Users.Add(existingUser);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var mgr = BuildUserManager();
|
||||
// The service checks _userManager.Users — we need to return the existing user
|
||||
mgr.Setup(m => m.Users)
|
||||
.Returns(new List<AppUser> { existingUser }.AsQueryable());
|
||||
var svc = new UserManagementService(mgr.Object, db, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
svc.CreateAsync(new CreateUserRequest
|
||||
{ MemberId = member.Id, Email = "new@test.com", Roles = ["member"] }));
|
||||
}
|
||||
|
||||
// ── DeactivateAsync ──────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task DeactivateAsync_SetsIsActiveFalse()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var user = new AppUser
|
||||
{ Id = "u1", UserName = "a@b.com", Email = "a@b.com", IsActive = true };
|
||||
var mgr = BuildUserManager(findResult: user);
|
||||
var svc = new UserManagementService(mgr.Object, db, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
|
||||
await svc.DeactivateAsync("u1");
|
||||
|
||||
Assert.False(user.IsActive);
|
||||
Assert.Equal(DateTimeOffset.MaxValue, user.LockoutEnd);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeactivateAsync_ThrowsKeyNotFound_WhenUserMissing()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var mgr = BuildUserManager(findResult: null);
|
||||
var svc = new UserManagementService(mgr.Object, db, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
|
||||
await Assert.ThrowsAsync<KeyNotFoundException>(() => svc.DeactivateAsync("missing"));
|
||||
}
|
||||
|
||||
// ── ResetPasswordAsync ───────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task ResetPasswordAsync_ReturnsNewTempPassword()
|
||||
{
|
||||
using var db = BuildDb();
|
||||
var user = new AppUser { Id = "u1", UserName = "a@b.com", Email = "a@b.com" };
|
||||
var mgr = BuildUserManager(findResult: user);
|
||||
var svc = new UserManagementService(mgr.Object, db, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
||||
|
||||
var pwd = await svc.ResetPasswordAsync("u1");
|
||||
|
||||
Assert.Equal(12, pwd.Length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using ROLAC.API.Entities.Logging;
|
||||
using ROLAC.API.Services.Logging;
|
||||
|
||||
namespace ROLAC.API.Tests.TestSupport;
|
||||
|
||||
/// <summary>Records every audit Write so tests can assert on the emitted actions/summaries.</summary>
|
||||
public sealed class CapturingAuditLogger : IAuditLogger
|
||||
{
|
||||
public readonly record struct Entry(string Action, string Category, string? EntityName, string? EntityId, string? Summary);
|
||||
|
||||
public readonly List<Entry> Entries = new();
|
||||
|
||||
public void Write(
|
||||
string action, string category, LogLevelEnum level = LogLevelEnum.Information,
|
||||
string? entityName = null, string? entityId = null, string? summary = null,
|
||||
object? before = null, object? after = null,
|
||||
string? userId = null, string? userEmail = null, string? ipAddress = null)
|
||||
{
|
||||
Entries.Add(new Entry(action, category, entityName, entityId, summary));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using ROLAC.API.Entities.Logging;
|
||||
using ROLAC.API.Services.Logging;
|
||||
|
||||
namespace ROLAC.API.Tests.TestSupport;
|
||||
|
||||
/// <summary>No-op <see cref="IAuditLogger"/> for unit tests that don't assert on audit output.</summary>
|
||||
public sealed class NullAuditLogger : IAuditLogger
|
||||
{
|
||||
public static readonly NullAuditLogger Instance = new();
|
||||
|
||||
public void Write(
|
||||
string action, string category, LogLevelEnum level = LogLevelEnum.Information,
|
||||
string? entityName = null, string? entityId = null, string? summary = null,
|
||||
object? before = null, object? after = null,
|
||||
string? userId = null, string? userEmail = null, string? ipAddress = null)
|
||||
{
|
||||
// intentionally empty
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace ROLAC.API.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Gates an action/controller on a configurable permission. Usage:
|
||||
/// <c>[HasPermission(Modules.Members, PermissionActions.Write)]</c>.
|
||||
/// Encodes the policy name <c>PERM:<module>:<action></c>, which
|
||||
/// <see cref="PermissionPolicyProvider"/> turns into a <see cref="PermissionRequirement"/>.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
|
||||
public class HasPermissionAttribute : AuthorizeAttribute
|
||||
{
|
||||
public const string PolicyPrefix = "PERM:";
|
||||
|
||||
public HasPermissionAttribute(string module, string action)
|
||||
=> Policy = $"{PolicyPrefix}{module}:{action}";
|
||||
|
||||
/// <summary>Parses a policy name back into (module, action), or null if not a PERM policy.</summary>
|
||||
public static (string Module, string Action)? Parse(string policyName)
|
||||
{
|
||||
if (!policyName.StartsWith(PolicyPrefix, StringComparison.Ordinal))
|
||||
return null;
|
||||
|
||||
var body = policyName[PolicyPrefix.Length..];
|
||||
var split = body.IndexOf(':');
|
||||
if (split <= 0 || split == body.Length - 1)
|
||||
return null;
|
||||
|
||||
return (body[..split], body[(split + 1)..]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
namespace ROLAC.API.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Canonical list of permission-controlled modules. The names are stored verbatim
|
||||
/// in <see cref="Entities.RolePermission.Module"/> and used in <c>[HasPermission]</c>
|
||||
/// attributes, so changing a string here is a breaking change requiring a data update.
|
||||
/// </summary>
|
||||
public static class Modules
|
||||
{
|
||||
public const string Members = "Members";
|
||||
public const string Users = "Users";
|
||||
public const string Givings = "Givings";
|
||||
public const string GivingCategories = "GivingCategories";
|
||||
public const string Expenses = "Expenses";
|
||||
public const string ExpenseCategories = "ExpenseCategories";
|
||||
public const string OfferingSessions = "OfferingSessions";
|
||||
public const string Ministries = "Ministries";
|
||||
public const string FinanceDashboard = "FinanceDashboard";
|
||||
public const string Form990Report = "Form990Report";
|
||||
public const string Form1099 = "Form1099";
|
||||
public const string MonthlyStatements = "MonthlyStatements";
|
||||
public const string ChurchProfile = "ChurchProfile";
|
||||
public const string Disbursements = "Disbursements";
|
||||
public const string MealAttendance = "MealAttendance";
|
||||
public const string Permissions = "Permissions";
|
||||
public const string SystemLogs = "SystemLogs";
|
||||
public const string AuditLogs = "AuditLogs";
|
||||
public const string Settings = "Settings";
|
||||
|
||||
/// <summary>All modules, in display order — drives the admin matrix UI.</summary>
|
||||
public static readonly IReadOnlyList<string> All =
|
||||
[
|
||||
Members,
|
||||
Users,
|
||||
Givings,
|
||||
GivingCategories,
|
||||
Expenses,
|
||||
ExpenseCategories,
|
||||
OfferingSessions,
|
||||
Ministries,
|
||||
FinanceDashboard,
|
||||
Form990Report,
|
||||
Form1099,
|
||||
MonthlyStatements,
|
||||
ChurchProfile,
|
||||
Disbursements,
|
||||
MealAttendance,
|
||||
Permissions,
|
||||
SystemLogs,
|
||||
AuditLogs,
|
||||
Settings,
|
||||
];
|
||||
|
||||
public static bool IsValid(string module) => All.Contains(module);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The four actions a role can be granted on a module. The default HTTP-verb mapping
|
||||
/// is GET→Read, POST/PUT/PATCH→Write, DELETE→Delete; "Approve" is applied explicitly
|
||||
/// to state-transition endpoints (approve / finalize / issue / sign, etc.).
|
||||
/// </summary>
|
||||
public static class PermissionActions
|
||||
{
|
||||
public const string Read = "Read";
|
||||
public const string Write = "Write";
|
||||
public const string Delete = "Delete";
|
||||
public const string Approve = "Approve";
|
||||
|
||||
public static readonly IReadOnlyList<string> All = [Read, Write, Delete, Approve];
|
||||
|
||||
public static bool IsValid(string action) => All.Contains(action);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates <see cref="PermissionRequirement"/> against the user's roles.
|
||||
/// <c>super_admin</c> always passes (bypass); otherwise the requirement succeeds if
|
||||
/// ANY of the user's roles grants the requested module/action (union across roles).
|
||||
/// </summary>
|
||||
public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
|
||||
{
|
||||
public const string SuperAdminRole = "super_admin";
|
||||
|
||||
private readonly IPermissionService _permissions;
|
||||
|
||||
public PermissionAuthorizationHandler(IPermissionService permissions)
|
||||
=> _permissions = permissions;
|
||||
|
||||
protected override async Task HandleRequirementAsync(
|
||||
AuthorizationHandlerContext context, PermissionRequirement requirement)
|
||||
{
|
||||
// Roles live in "role" claims (RoleClaimType = "role", MapInboundClaims = false).
|
||||
var roles = context.User.FindAll("role").Select(claim => claim.Value).ToList();
|
||||
|
||||
if (roles.Contains(SuperAdminRole))
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
return;
|
||||
}
|
||||
|
||||
if (await _permissions.HasPermissionAsync(roles, requirement.Module, requirement.Action))
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ROLAC.API.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Materializes <c>PERM:<module>:<action></c> policies on demand so we never
|
||||
/// have to register every module/action combination at startup. Any other policy name
|
||||
/// (including the default and <c>Roles=</c> policies) is delegated to the framework's
|
||||
/// default provider, so existing <c>[Authorize(Roles=...)]</c> usages keep working.
|
||||
/// </summary>
|
||||
public class PermissionPolicyProvider : IAuthorizationPolicyProvider
|
||||
{
|
||||
private readonly DefaultAuthorizationPolicyProvider _fallback;
|
||||
|
||||
public PermissionPolicyProvider(IOptions<AuthorizationOptions> options)
|
||||
=> _fallback = new DefaultAuthorizationPolicyProvider(options);
|
||||
|
||||
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => _fallback.GetDefaultPolicyAsync();
|
||||
|
||||
public Task<AuthorizationPolicy?> GetFallbackPolicyAsync() => _fallback.GetFallbackPolicyAsync();
|
||||
|
||||
public Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
|
||||
{
|
||||
var parsed = HasPermissionAttribute.Parse(policyName);
|
||||
if (parsed is null)
|
||||
return _fallback.GetPolicyAsync(policyName);
|
||||
|
||||
var policy = new AuthorizationPolicyBuilder()
|
||||
.RequireAuthenticatedUser()
|
||||
.AddRequirements(new PermissionRequirement(parsed.Value.Module, parsed.Value.Action))
|
||||
.Build();
|
||||
|
||||
return Task.FromResult<AuthorizationPolicy?>(policy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace ROLAC.API.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Authorization requirement carrying the module + action a request needs.
|
||||
/// Materialized on demand by <see cref="PermissionPolicyProvider"/> from a policy
|
||||
/// name of the form <c>PERM:<module>:<action></c>.
|
||||
/// </summary>
|
||||
public class PermissionRequirement : IAuthorizationRequirement
|
||||
{
|
||||
public string Module { get; }
|
||||
public string Action { get; }
|
||||
|
||||
public PermissionRequirement(string module, string action)
|
||||
{
|
||||
Module = module;
|
||||
Action = action;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Logging;
|
||||
using ROLAC.API.Services.Logging;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/audit-logs")]
|
||||
[Authorize]
|
||||
public class AuditLogsController : ControllerBase
|
||||
{
|
||||
private readonly IAuditLogQueryService _svc;
|
||||
public AuditLogsController(IAuditLogQueryService svc) => _svc = svc;
|
||||
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.AuditLogs, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetPaged([FromQuery] AuditLogQuery query)
|
||||
=> Ok(await _svc.GetPagedAsync(query));
|
||||
|
||||
[HttpGet("{id:long}")]
|
||||
[HasPermission(Modules.AuditLogs, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetById(long id)
|
||||
{
|
||||
var dto = await _svc.GetByIdAsync(id);
|
||||
return dto is null ? NotFound() : Ok(dto);
|
||||
}
|
||||
|
||||
/// <summary>Category / action / level option lists for the filter UI.</summary>
|
||||
[HttpGet("catalog")]
|
||||
[HasPermission(Modules.AuditLogs, PermissionActions.Read)]
|
||||
public IActionResult GetCatalog() => Ok(_svc.GetCatalog());
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.DTOs.Auth;
|
||||
using ROLAC.API.DTOs.Invitations;
|
||||
using ROLAC.API.Entities;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/auth")]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private const string CookieName = "rolac_rt";
|
||||
private const int CookieMaxAge = 30 * 24 * 60 * 60; // 30 days in seconds
|
||||
|
||||
private readonly IAuthService _authService;
|
||||
private readonly IInvitationService _invitations;
|
||||
private readonly UserManager<AppUser> _userManager;
|
||||
private readonly IWebHostEnvironment _env;
|
||||
|
||||
public AuthController(
|
||||
IAuthService authService, IInvitationService invitations,
|
||||
UserManager<AppUser> userManager, IWebHostEnvironment env)
|
||||
{
|
||||
_authService = authService;
|
||||
_invitations = invitations;
|
||||
_userManager = userManager;
|
||||
_env = env;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// POST /api/auth/login
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>Authenticates a user and returns an access token.</summary>
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(LoginResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var device = Request.Headers.UserAgent.FirstOrDefault();
|
||||
var (response, raw) = await _authService.LoginAsync(request, ip, device);
|
||||
SetRefreshCookie(raw);
|
||||
return Ok(response);
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
return Unauthorized(new { message = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// POST /api/auth/refresh
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Rotates the refresh token (read from the HttpOnly cookie) and returns a
|
||||
/// new access token.
|
||||
/// </summary>
|
||||
[HttpPost("refresh")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(LoginResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Refresh()
|
||||
{
|
||||
var raw = Request.Cookies[CookieName];
|
||||
if (string.IsNullOrEmpty(raw))
|
||||
return Unauthorized(new { message = "Refresh token not found." });
|
||||
|
||||
try
|
||||
{
|
||||
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var (response, newRaw) = await _authService.RefreshAsync(raw, ip);
|
||||
SetRefreshCookie(newRaw);
|
||||
return Ok(response);
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
ClearRefreshCookie();
|
||||
return Unauthorized(new { message = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GET /api/auth/me
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the current user's identity, roles, and effective permissions.
|
||||
/// The SPA calls this on startup and after an admin edits the permission matrix
|
||||
/// to refresh what the UI shows — without forcing a re-login.
|
||||
/// </summary>
|
||||
[HttpGet("me")]
|
||||
[Authorize]
|
||||
[ProducesResponseType(typeof(UserInfo), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetMe()
|
||||
{
|
||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
return Unauthorized();
|
||||
|
||||
var user = await _userManager.FindByIdAsync(userId);
|
||||
if (user is null || !user.IsActive)
|
||||
return Unauthorized();
|
||||
|
||||
var roles = await _userManager.GetRolesAsync(user);
|
||||
return Ok(await _authService.BuildUserInfoAsync(user, roles));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GET /api/auth/claims (dev-only diagnostic)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Returns the raw claims ASP.NET Core parsed from the Bearer token.
|
||||
/// Use this to debug 401 vs 403: if you get 200 here, the JWT validates fine;
|
||||
/// if you then get 403 on a protected endpoint the role/permission isn't matching.
|
||||
/// </summary>
|
||||
[HttpGet("claims")]
|
||||
[Authorize]
|
||||
public IActionResult GetClaims()
|
||||
{
|
||||
var claims = User.Claims
|
||||
.Select(c => new { c.Type, c.Value })
|
||||
.ToList();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
isAuthenticated = User.Identity?.IsAuthenticated,
|
||||
authenticationType = User.Identity?.AuthenticationType,
|
||||
name = User.Identity?.Name,
|
||||
claims,
|
||||
});
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// POST /api/auth/logout
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>Revokes the current refresh token and clears the cookie.</summary>
|
||||
[HttpPost("logout")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
var raw = Request.Cookies[CookieName];
|
||||
if (!string.IsNullOrEmpty(raw))
|
||||
await _authService.LogoutAsync(raw);
|
||||
|
||||
ClearRefreshCookie();
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// POST /api/auth/change-password
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Changes the current user's password. Requires the correct current password and a
|
||||
/// new password meeting the configured policy. On success the user's *other* sessions
|
||||
/// are revoked while the current session stays active.
|
||||
/// </summary>
|
||||
[HttpPost("change-password")]
|
||||
[Authorize]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
|
||||
{
|
||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
return Unauthorized();
|
||||
|
||||
var currentRefresh = Request.Cookies[CookieName];
|
||||
var result = await _authService.ChangePasswordAsync(
|
||||
userId, request.CurrentPassword, request.NewPassword, currentRefresh);
|
||||
|
||||
if (!result.Succeeded)
|
||||
return BadRequest(new
|
||||
{
|
||||
message = string.Join(" ", result.Errors.Select(error => error.Description)),
|
||||
});
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// GET /api/auth/invitation/validate?token=...
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether an invitation token can still be used. Anonymous so the public
|
||||
/// "set your password" page can decide what to show before the member types anything.
|
||||
/// </summary>
|
||||
[HttpGet("invitation/validate")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(ValidateInvitationResult), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> ValidateInvitation([FromQuery] string token)
|
||||
=> Ok(await _invitations.ValidateAsync(token));
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// POST /api/auth/accept-invitation
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Consumes an invitation: sets the account password and, on success, logs the member in
|
||||
/// (issues the access token + refresh cookie) so first login lands straight on the portal.
|
||||
/// </summary>
|
||||
[HttpPost("accept-invitation")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(LoginResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> AcceptInvitation([FromBody] AcceptInvitationRequest request)
|
||||
{
|
||||
var (user, error) = await _invitations.AcceptAsync(request.Token, request.NewPassword);
|
||||
if (user is null)
|
||||
return BadRequest(new { message = error });
|
||||
|
||||
var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
var device = Request.Headers.UserAgent.FirstOrDefault();
|
||||
var (response, raw) = await _authService.IssueSessionAsync(user, ip, device);
|
||||
SetRefreshCookie(raw);
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Private helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// <c>Secure</c> is set to <c>true</c> everywhere except in the local
|
||||
/// Development environment so that the cookie works over plain HTTP during
|
||||
/// dev and smoke-test runs, but is always HTTPS-only in staging/production.
|
||||
/// </summary>
|
||||
private void SetRefreshCookie(string rawToken)
|
||||
=> Response.Cookies.Append(CookieName, rawToken, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = !_env.IsDevelopment(),
|
||||
SameSite = SameSiteMode.Strict,
|
||||
MaxAge = TimeSpan.FromSeconds(CookieMaxAge),
|
||||
Path = "/api/auth",
|
||||
});
|
||||
|
||||
private void ClearRefreshCookie()
|
||||
=> Response.Cookies.Delete(CookieName, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = !_env.IsDevelopment(),
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Path = "/api/auth",
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Disbursement;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/church-profile")]
|
||||
[Authorize]
|
||||
public class ChurchProfileController : ControllerBase
|
||||
{
|
||||
private readonly IChurchProfileService _svc;
|
||||
public ChurchProfileController(IChurchProfileService svc) => _svc = svc;
|
||||
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.ChurchProfile, PermissionActions.Read)]
|
||||
public async Task<IActionResult> Get() => Ok(await _svc.GetAsync());
|
||||
|
||||
[HttpPut]
|
||||
[HasPermission(Modules.ChurchProfile, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Update([FromBody] UpdateChurchProfileRequest r)
|
||||
{
|
||||
await _svc.UpdateAsync(r);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Disbursement;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/disbursements")]
|
||||
[Authorize]
|
||||
public class DisbursementsController : ControllerBase
|
||||
{
|
||||
private readonly IDisbursementService _svc;
|
||||
public DisbursementsController(IDisbursementService svc) => _svc = svc;
|
||||
|
||||
[HttpGet("approved-unpaid")]
|
||||
[HasPermission(Modules.Disbursements, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetApprovedUnpaid()
|
||||
=> Ok(await _svc.GetApprovedUnpaidGroupedAsync());
|
||||
|
||||
[HttpPost("issue")]
|
||||
[HasPermission(Modules.Disbursements, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Issue([FromBody] IssueChecksRequest r)
|
||||
{
|
||||
try { return Ok(await _svc.IssueChecksAsync(r)); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpGet("checks")]
|
||||
[HasPermission(Modules.Disbursements, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetRegister(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, [FromQuery] string? status = null,
|
||||
[FromQuery] string? search = null, [FromQuery] DateOnly? from = null, [FromQuery] DateOnly? to = null)
|
||||
=> Ok(await _svc.GetRegisterAsync(page, pageSize, status, search, from, to));
|
||||
|
||||
[HttpGet("checks/{id:int}")]
|
||||
[HasPermission(Modules.Disbursements, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
var dto = await _svc.GetByIdAsync(id);
|
||||
return dto is null ? NotFound() : Ok(dto);
|
||||
}
|
||||
|
||||
[HttpPost("checks/{id:int}/void")]
|
||||
[HasPermission(Modules.Disbursements, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> Void(int id, [FromBody] VoidCheckRequest r)
|
||||
{
|
||||
try { await _svc.VoidAsync(id, r.Reason); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpGet("checks/{id:int}/pdf")]
|
||||
[HasPermission(Modules.Disbursements, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetPdf(int id)
|
||||
{
|
||||
var result = await _svc.RenderPdfAsync(id);
|
||||
if (result is null) return NotFound();
|
||||
return File(result.Value.stream, result.Value.contentType, result.Value.fileName);
|
||||
}
|
||||
|
||||
[HttpGet("checks/{id:int}/receipt-pdf")]
|
||||
[HasPermission(Modules.Disbursements, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetReceiptPdf(int id)
|
||||
{
|
||||
var result = await _svc.RenderReceiptPdfAsync(id);
|
||||
if (result is null) return NotFound();
|
||||
return File(result.Value.stream, result.Value.contentType, result.Value.fileName);
|
||||
}
|
||||
|
||||
[HttpPost("checks/{id:int}/acknowledge")]
|
||||
[HasPermission(Modules.Disbursements, PermissionActions.Approve)]
|
||||
[RequestSizeLimit(5_242_880)]
|
||||
public async Task<IActionResult> Acknowledge(int id, [FromForm] IFormFile signature, [FromForm] string signedName)
|
||||
{
|
||||
if (signature is null || signature.Length == 0) return BadRequest(new { message = "No signature." });
|
||||
if (string.IsNullOrWhiteSpace(signedName)) return BadRequest(new { message = "Signed name is required." });
|
||||
var allowed = new[] { "image/png", "image/jpeg", "image/webp" };
|
||||
if (!allowed.Contains(signature.ContentType)) return BadRequest(new { message = "Unsupported image type." });
|
||||
try
|
||||
{
|
||||
await using var stream = signature.OpenReadStream();
|
||||
await _svc.AcknowledgeReceiptAsync(id, stream, signature.FileName, signedName.Trim());
|
||||
return NoContent();
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpGet("checks/{id:int}/signature")]
|
||||
[HasPermission(Modules.Disbursements, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetSignature(int id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _svc.OpenSignatureAsync(id);
|
||||
if (result is null) return NotFound();
|
||||
return File(result.Value.stream, result.Value.contentType);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.DTOs.Expense;
|
||||
using ROLAC.API.Services.Ai;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/expense-ai")]
|
||||
[Authorize] // Open to any authenticated user — same audience as the expense-entry form, which any
|
||||
// member filing a reimbursement can reach. The endpoint only reads the category catalog.
|
||||
public class ExpenseAiController : ControllerBase
|
||||
{
|
||||
private readonly IExpenseAiServiceFactory _factory;
|
||||
public ExpenseAiController(IExpenseAiServiceFactory factory) => _factory = factory;
|
||||
|
||||
[HttpPost("assist")]
|
||||
public async Task<IActionResult> Assist([FromBody] ExpenseAiAssistRequest request, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.Text))
|
||||
return BadRequest("Text is required.");
|
||||
|
||||
var svc = await _factory.ResolveAsync(ct);
|
||||
var suggestion = await svc.SuggestAsync(request.Text, request.Amount, ct);
|
||||
return Ok(suggestion);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Expense;
|
||||
using ROLAC.API.Services;
|
||||
using ROLAC.API.Services.Ai;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/expense-categories")]
|
||||
[Authorize] // read (GetAll) is open to any authenticated user — the member self-service
|
||||
// reimbursement form needs the category list. Write actions are finance-only below.
|
||||
public class ExpenseCategoriesController : ControllerBase
|
||||
{
|
||||
private readonly IExpenseCategoryService _svc;
|
||||
private readonly IExpenseCategoryAiServiceFactory _aiFactory;
|
||||
public ExpenseCategoriesController(IExpenseCategoryService svc, IExpenseCategoryAiServiceFactory aiFactory)
|
||||
{
|
||||
_svc = svc;
|
||||
_aiFactory = aiFactory;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll([FromQuery] bool includeInactive = false)
|
||||
=> Ok(await _svc.GetAllAsync(includeInactive));
|
||||
|
||||
// Suggest an English name + Form 990 line for a category being defined. Write-gated: category
|
||||
// editing is finance/admin-only, unlike the member-facing expense-ai/assist endpoint.
|
||||
[HttpPost("ai-suggest")]
|
||||
[HasPermission(Modules.ExpenseCategories, PermissionActions.Write)]
|
||||
public async Task<IActionResult> AiSuggest([FromBody] ExpenseCategoryAiRequest r, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(r.Name_zh) && string.IsNullOrWhiteSpace(r.Name_en))
|
||||
return BadRequest("A name is required.");
|
||||
|
||||
var svc = await _aiFactory.ResolveAsync(ct);
|
||||
return Ok(await svc.SuggestAsync(r, ct));
|
||||
}
|
||||
|
||||
[HttpPost("groups")]
|
||||
[HasPermission(Modules.ExpenseCategories, PermissionActions.Write)]
|
||||
public async Task<IActionResult> CreateGroup([FromBody] CreateExpenseGroupRequest r)
|
||||
=> Ok(new { id = await _svc.CreateGroupAsync(r) });
|
||||
|
||||
[HttpPut("groups/{id:int}")]
|
||||
[HasPermission(Modules.ExpenseCategories, PermissionActions.Write)]
|
||||
public async Task<IActionResult> UpdateGroup(int id, [FromBody] UpdateExpenseGroupRequest r)
|
||||
{ try { await _svc.UpdateGroupAsync(id, r); return NoContent(); } catch (KeyNotFoundException) { return NotFound(); } }
|
||||
|
||||
[HttpDelete("groups/{id:int}")]
|
||||
[HasPermission(Modules.ExpenseCategories, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> DeactivateGroup(int id)
|
||||
{ try { await _svc.DeactivateGroupAsync(id); return NoContent(); } catch (KeyNotFoundException) { return NotFound(); } }
|
||||
|
||||
[HttpPost("subcategories")]
|
||||
[HasPermission(Modules.ExpenseCategories, PermissionActions.Write)]
|
||||
public async Task<IActionResult> CreateSub([FromBody] CreateExpenseSubCategoryRequest r)
|
||||
{ try { return Ok(new { id = await _svc.CreateSubCategoryAsync(r) }); } catch (KeyNotFoundException) { return NotFound(); } }
|
||||
|
||||
[HttpPut("subcategories/{id:int}")]
|
||||
[HasPermission(Modules.ExpenseCategories, PermissionActions.Write)]
|
||||
public async Task<IActionResult> UpdateSub(int id, [FromBody] UpdateExpenseSubCategoryRequest r)
|
||||
{ try { await _svc.UpdateSubCategoryAsync(id, r); return NoContent(); } catch (KeyNotFoundException) { return NotFound(); } }
|
||||
|
||||
[HttpDelete("subcategories/{id:int}")]
|
||||
[HasPermission(Modules.ExpenseCategories, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> DeactivateSub(int id)
|
||||
{ try { await _svc.DeactivateSubCategoryAsync(id); return NoContent(); } catch (KeyNotFoundException) { return NotFound(); } }
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Expense;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
// Snapshots are reusable vendor-payment templates — a finance tool. Every action requires
|
||||
// Expenses:Write (super_admin bypasses), matching who can create vendor payments.
|
||||
[ApiController]
|
||||
[Route("api/expense-snapshots")]
|
||||
[Authorize]
|
||||
public class ExpenseSnapshotsController : ControllerBase
|
||||
{
|
||||
private readonly IExpenseSnapshotService _svc;
|
||||
private readonly IPermissionService _perms;
|
||||
public ExpenseSnapshotsController(IExpenseSnapshotService svc, IPermissionService perms)
|
||||
{
|
||||
_svc = svc;
|
||||
_perms = perms;
|
||||
}
|
||||
|
||||
private List<string> Roles() => User.FindAll("role").Select(claim => claim.Value).ToList();
|
||||
private bool IsSuperAdmin() => User.IsInRole(PermissionAuthorizationHandler.SuperAdminRole);
|
||||
private async Task<bool> CanManageAsync() =>
|
||||
IsSuperAdmin() || await _perms.HasPermissionAsync(Roles(), Modules.Expenses, PermissionActions.Write);
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll()
|
||||
{
|
||||
if (!await CanManageAsync()) return Forbid();
|
||||
return Ok(await _svc.GetAllAsync());
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
if (!await CanManageAsync()) return Forbid();
|
||||
var dto = await _svc.GetByIdAsync(id);
|
||||
return dto is null ? NotFound() : Ok(dto);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateExpenseSnapshotRequest r)
|
||||
{
|
||||
if (!await CanManageAsync()) return Forbid();
|
||||
try { return Ok(new { id = await _svc.CreateAsync(r) }); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] UpdateExpenseSnapshotRequest r)
|
||||
{
|
||||
if (!await CanManageAsync()) return Forbid();
|
||||
try { await _svc.UpdateAsync(id, r); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{
|
||||
if (!await CanManageAsync()) return Forbid();
|
||||
try { await _svc.DeleteAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Expense;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
// Class is [Authorize] only — any authenticated member may submit/view their OWN
|
||||
// reimbursements. Finance-level privileges (view-all, edit-any, approve) are resolved
|
||||
// against the configurable permission matrix on the "Expenses" module.
|
||||
[ApiController]
|
||||
[Route("api/expenses")]
|
||||
[Authorize]
|
||||
public class ExpensesController : ControllerBase
|
||||
{
|
||||
private readonly IExpenseService _svc;
|
||||
private readonly IPermissionService _perms;
|
||||
public ExpensesController(IExpenseService svc, IPermissionService perms)
|
||||
{
|
||||
_svc = svc;
|
||||
_perms = perms;
|
||||
}
|
||||
|
||||
private List<string> Roles() => User.FindAll("role").Select(claim => claim.Value).ToList();
|
||||
private bool IsSuperAdmin() => User.IsInRole(PermissionAuthorizationHandler.SuperAdminRole);
|
||||
|
||||
// Can manage any expense (edit/delete/upload on others' records). Maps to Expenses:Write.
|
||||
private async Task<bool> CanManageAsync() =>
|
||||
IsSuperAdmin() || await _perms.HasPermissionAsync(Roles(), Modules.Expenses, PermissionActions.Write);
|
||||
|
||||
// Can view all expenses (not just own). Maps to Expenses:Read (finance + pastor by default).
|
||||
private async Task<bool> CanViewAllAsync() =>
|
||||
IsSuperAdmin() || await _perms.HasPermissionAsync(Roles(), Modules.Expenses, PermissionActions.Read);
|
||||
|
||||
// User id lives in the "sub" claim (NameClaimType="sub"); NameIdentifier is absent at runtime.
|
||||
private string CurrentUserId() =>
|
||||
User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub") ?? "";
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetPaged(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, [FromQuery] string? search = null,
|
||||
[FromQuery] int? ministryId = null, [FromQuery] int? categoryGroupId = null,
|
||||
[FromQuery] string? status = null, [FromQuery] DateOnly? from = null, [FromQuery] DateOnly? to = null,
|
||||
[FromQuery] int? subCategoryId = null, [FromQuery] string? statuses = null)
|
||||
{
|
||||
if (!await CanViewAllAsync()) return Forbid();
|
||||
return Ok(await _svc.GetPagedAsync(page, pageSize, search, ministryId, categoryGroupId, status, from, to, subCategoryId, statuses));
|
||||
}
|
||||
|
||||
[HttpGet("mine")]
|
||||
public async Task<IActionResult> GetMine([FromQuery] string? status = null, [FromQuery] int page = 1, [FromQuery] int pageSize = 20)
|
||||
{
|
||||
return Ok(await _svc.GetMineAsync(CurrentUserId(), status, page, pageSize));
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
var dto = await _svc.GetByIdAsync(id);
|
||||
if (dto is null) return NotFound();
|
||||
if (!await CanViewAllAsync() && dto.SubmittedBy != CurrentUserId()) return Forbid();
|
||||
return Ok(dto);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateExpenseRequest r)
|
||||
{
|
||||
try { return Ok(new { id = await _svc.CreateAsync(r, await CanManageAsync()) }); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] UpdateExpenseRequest r)
|
||||
{
|
||||
try { await _svc.UpdateAsync(id, r, await CanManageAsync()); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{
|
||||
try { await _svc.DeleteAsync(id, await CanManageAsync()); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:int}/submit")]
|
||||
public async Task<IActionResult> Submit(int id)
|
||||
{
|
||||
try { await _svc.SubmitAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:int}/approve")]
|
||||
[HasPermission(Modules.Expenses, PermissionActions.Approve)]
|
||||
public async Task<IActionResult> Approve(int id)
|
||||
{
|
||||
try { await _svc.ApproveAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:int}/reject")]
|
||||
[HasPermission(Modules.Expenses, PermissionActions.Approve)]
|
||||
public async Task<IActionResult> Reject(int id, [FromBody] RejectExpenseRequest r)
|
||||
{
|
||||
try { await _svc.RejectAsync(id, r.ReviewNotes); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:int}/pay")]
|
||||
[HasPermission(Modules.Expenses, PermissionActions.Approve)]
|
||||
public async Task<IActionResult> Pay(int id, [FromBody] PayExpenseRequest r)
|
||||
{
|
||||
try { await _svc.PayAsync(id, r.CheckNumber, r.PaidAt); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:int}/receipt")]
|
||||
[RequestSizeLimit(10_485_760)]
|
||||
public async Task<IActionResult> UploadReceipt(int id, IFormFile file)
|
||||
{
|
||||
if (file is null || file.Length == 0) return BadRequest(new { message = "No file." });
|
||||
var allowed = new[] { "image/jpeg", "image/png", "image/webp", "application/pdf" };
|
||||
if (!allowed.Contains(file.ContentType)) return BadRequest(new { message = "Unsupported file type." });
|
||||
try
|
||||
{
|
||||
await using var stream = file.OpenReadStream();
|
||||
await _svc.SaveReceiptAsync(id, stream, file.FileName, await CanManageAsync());
|
||||
return NoContent();
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}/receipt")]
|
||||
public async Task<IActionResult> GetReceipt(int id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _svc.OpenReceiptAsync(id, await CanManageAsync());
|
||||
if (result is null) return NotFound();
|
||||
return File(result.Value.stream, result.Value.contentType);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException) { return Forbid(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/finance-dashboard")]
|
||||
[HasPermission(Modules.FinanceDashboard, PermissionActions.Read)]
|
||||
public class FinanceDashboardController : ControllerBase
|
||||
{
|
||||
private readonly IFinanceDashboardService _svc;
|
||||
public FinanceDashboardController(IFinanceDashboardService svc) => _svc = svc;
|
||||
|
||||
[HttpGet("summary")]
|
||||
public async Task<IActionResult> Summary()
|
||||
=> Ok(await _svc.GetSummaryAsync());
|
||||
|
||||
[HttpGet("income-expense")]
|
||||
public async Task<IActionResult> IncomeExpense([FromQuery] DateOnly? from, [FromQuery] DateOnly? to)
|
||||
=> Ok(await _svc.GetIncomeExpenseAsync(from, to));
|
||||
|
||||
[HttpGet("expense-breakdown")]
|
||||
public async Task<IActionResult> ExpenseBreakdown(
|
||||
[FromQuery] DateOnly? from, [FromQuery] DateOnly? to,
|
||||
[FromQuery] int? ministryId, [FromQuery] int? categoryGroupId)
|
||||
=> Ok(await _svc.GetExpenseBreakdownAsync(from, to, ministryId, categoryGroupId));
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/form1099-report")]
|
||||
[HasPermission(Modules.Form1099, PermissionActions.Read)]
|
||||
public class Form1099ReportController : ControllerBase
|
||||
{
|
||||
private readonly IForm1099ReportService _svc;
|
||||
private readonly I1099FormService _form;
|
||||
public Form1099ReportController(IForm1099ReportService svc, I1099FormService form)
|
||||
{
|
||||
_svc = svc;
|
||||
_form = form;
|
||||
}
|
||||
|
||||
[HttpGet("boxes")]
|
||||
public async Task<IActionResult> Boxes() => Ok(await _svc.GetBoxesAsync());
|
||||
|
||||
[HttpGet("summary")]
|
||||
public async Task<IActionResult> Summary([FromQuery] int taxYear)
|
||||
=> Ok(await _svc.GetAnnualSummaryAsync(taxYear));
|
||||
|
||||
[HttpGet("recipient/{payeeId:int}")]
|
||||
public async Task<IActionResult> Recipient(int payeeId, [FromQuery] int taxYear)
|
||||
=> await _svc.GetRecipientDetailAsync(payeeId, taxYear) is { } d ? Ok(d) : NotFound();
|
||||
|
||||
[HttpGet("recipient/{payeeId:int}/copy-b")]
|
||||
public async Task<IActionResult> CopyB(int payeeId, [FromQuery] int taxYear)
|
||||
{
|
||||
var (stream, contentType, fileName) = await _form.RenderCopyBAsync(payeeId, taxYear);
|
||||
return File(stream, contentType, fileName);
|
||||
}
|
||||
|
||||
[HttpGet("export-csv")]
|
||||
public async Task<IActionResult> ExportCsv([FromQuery] int taxYear)
|
||||
{
|
||||
var (stream, contentType, fileName) = await _form.ExportFilingCsvAsync(taxYear);
|
||||
return File(stream, contentType, fileName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/form990-report")]
|
||||
[HasPermission(Modules.Form990Report, PermissionActions.Read)]
|
||||
public class Form990ReportController : ControllerBase
|
||||
{
|
||||
private readonly IForm990ReportService _svc;
|
||||
public Form990ReportController(IForm990ReportService svc) => _svc = svc;
|
||||
|
||||
[HttpGet("lines")]
|
||||
public async Task<IActionResult> Lines() => Ok(await _svc.GetLinesAsync());
|
||||
|
||||
[HttpGet("functional-expenses")]
|
||||
public async Task<IActionResult> FunctionalExpenses([FromQuery] DateOnly? from, [FromQuery] DateOnly? to)
|
||||
=> Ok(await _svc.GetFunctionalExpenseStatementAsync(from, to));
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Giving;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/giving-categories")]
|
||||
[Authorize]
|
||||
public class GivingCategoriesController : ControllerBase
|
||||
{
|
||||
private readonly IGivingCategoryService _svc;
|
||||
public GivingCategoriesController(IGivingCategoryService svc) => _svc = svc;
|
||||
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.GivingCategories, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetAll([FromQuery] bool includeInactive = false)
|
||||
=> Ok(await _svc.GetAllAsync(includeInactive));
|
||||
|
||||
[HttpPost]
|
||||
[HasPermission(Modules.GivingCategories, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateGivingCategoryRequest request)
|
||||
{
|
||||
var id = await _svc.CreateAsync(request);
|
||||
return CreatedAtAction(nameof(GetAll), new { id }, new { id });
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[HasPermission(Modules.GivingCategories, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] UpdateGivingCategoryRequest request)
|
||||
{
|
||||
try { await _svc.UpdateAsync(id, request); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
[HasPermission(Modules.GivingCategories, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> Deactivate(int id)
|
||||
{
|
||||
try { await _svc.DeactivateAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Giving;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/givings")]
|
||||
[Authorize]
|
||||
public class GivingsController : ControllerBase
|
||||
{
|
||||
private readonly IGivingService _svc;
|
||||
public GivingsController(IGivingService svc) => _svc = svc;
|
||||
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.Givings, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetPaged(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20,
|
||||
[FromQuery] string? search = null, [FromQuery] int? categoryId = null,
|
||||
[FromQuery] DateOnly? from = null, [FromQuery] DateOnly? to = null)
|
||||
=> Ok(await _svc.GetPagedAsync(page, pageSize, search, categoryId, from, to));
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
[HasPermission(Modules.Givings, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
var dto = await _svc.GetByIdAsync(id);
|
||||
return dto is null ? NotFound() : Ok(dto);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[HasPermission(Modules.Givings, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateGivingRequest request)
|
||||
{
|
||||
var id = await _svc.CreateAsync(request);
|
||||
return CreatedAtAction(nameof(GetById), new { id }, new { id });
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[HasPermission(Modules.Givings, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] UpdateGivingRequest request)
|
||||
{
|
||||
try { await _svc.UpdateAsync(id, request); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
[HasPermission(Modules.Givings, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{
|
||||
try { await _svc.DeleteAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Data;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/health")]
|
||||
[AllowAnonymous]
|
||||
public class HealthController : ControllerBase
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
public HealthController(AppDbContext db) => _db = db;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get(CancellationToken cancellationToken)
|
||||
{
|
||||
var canConnectToDatabase = await _db.Database.CanConnectAsync(cancellationToken);
|
||||
|
||||
var payload = new
|
||||
{
|
||||
status = canConnectToDatabase ? "healthy" : "degraded",
|
||||
database = canConnectToDatabase ? "up" : "down",
|
||||
time = DateTimeOffset.UtcNow
|
||||
};
|
||||
|
||||
return canConnectToDatabase ? Ok(payload) : StatusCode(503, payload);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Invitations;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Admin endpoints for generating and e-mailing first-login invitation links.
|
||||
/// The public consume/validate endpoints live on <see cref="AuthController"/> so they can set the
|
||||
/// refresh-token cookie and stay anonymous.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/invitations")]
|
||||
[Authorize]
|
||||
public class InvitationsController : ControllerBase
|
||||
{
|
||||
private readonly IInvitationService _invitations;
|
||||
public InvitationsController(IInvitationService invitations) => _invitations = invitations;
|
||||
|
||||
/// <summary>POST /api/invitations — generate a link for a member; returns { token, expiresAt }.</summary>
|
||||
[HttpPost]
|
||||
[HasPermission(Modules.Users, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateInvitationRequest request)
|
||||
{
|
||||
try { return Ok(await _invitations.CreateAsync(request)); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
/// <summary>POST /api/invitations/send — e-mail an already-generated link to the member.</summary>
|
||||
[HttpPost("send")]
|
||||
[HasPermission(Modules.Users, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Send([FromBody] SendInvitationRequest request)
|
||||
{
|
||||
try { await _invitations.SendEmailAsync(request.MemberId, request.Link); return NoContent(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.DTOs.Notifications;
|
||||
using ROLAC.API.Services.Notifications;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Anonymous Line webhook. Verifies the X-Line-Signature over the raw body, then dispatches
|
||||
/// follow/message/join/leave events. Always returns 200 for valid payloads so Line does not retry;
|
||||
/// returns 400 only on signature failure.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/line")]
|
||||
[AllowAnonymous]
|
||||
public sealed class LineWebhookController : ControllerBase
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOpts = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
private readonly ILineNotificationService _line;
|
||||
private readonly IMessageChannel _channel;
|
||||
private readonly INotificationSettingsService _settings;
|
||||
|
||||
public LineWebhookController(
|
||||
ILineNotificationService line, IMessageChannel channel, INotificationSettingsService settings)
|
||||
{
|
||||
_line = line;
|
||||
_channel = channel;
|
||||
_settings = settings;
|
||||
}
|
||||
|
||||
[HttpPost("webhook")]
|
||||
[RequestSizeLimit(262_144)]
|
||||
public async Task<IActionResult> Webhook(CancellationToken ct)
|
||||
{
|
||||
using var reader = new StreamReader(Request.Body, Encoding.UTF8);
|
||||
var rawBody = await reader.ReadToEndAsync(ct);
|
||||
var signature = Request.Headers["X-Line-Signature"].FirstOrDefault();
|
||||
|
||||
if (!LineSignature.IsValid(_settings.GetLine().ChannelSecret, Encoding.UTF8.GetBytes(rawBody), signature))
|
||||
return BadRequest();
|
||||
|
||||
var payload = JsonSerializer.Deserialize<LineWebhookPayload>(rawBody, JsonOpts);
|
||||
if (payload?.Events is not null)
|
||||
foreach (var evt in payload.Events)
|
||||
await DispatchAsync(evt, ct);
|
||||
|
||||
return Ok();
|
||||
}
|
||||
|
||||
private async Task DispatchAsync(LineWebhookEvent evt, CancellationToken ct)
|
||||
{
|
||||
switch (evt.Type)
|
||||
{
|
||||
case "follow":
|
||||
if (evt.ReplyToken is not null)
|
||||
await _channel.ReplyAsync(evt.ReplyToken, "歡迎!請輸入您的綁定碼以連結教會帳號。", ct);
|
||||
break;
|
||||
|
||||
case "message":
|
||||
if (evt.Message?.Type == "text"
|
||||
&& evt.Source?.UserId is { } userId
|
||||
&& evt.Message.Text is { } text)
|
||||
{
|
||||
var result = await _line.TryBindMemberAsync(userId, text, ct);
|
||||
if (evt.ReplyToken is not null)
|
||||
await _channel.ReplyAsync(evt.ReplyToken, result.Message, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case "join":
|
||||
if (evt.Source?.GroupId is { } joinGroupId)
|
||||
{
|
||||
await _line.RegisterGroupAsync(joinGroupId, ct);
|
||||
if (evt.ReplyToken is not null)
|
||||
await _channel.ReplyAsync(evt.ReplyToken, "已加入群組,請至後台命名此群組。", ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case "leave":
|
||||
if (evt.Source?.GroupId is { } leaveGroupId)
|
||||
await _line.DeactivateGroupAsync(leaveGroupId, ct);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.DTOs.MealAttendance;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/meal-attendance")]
|
||||
public class MealAttendanceController : ControllerBase
|
||||
{
|
||||
private readonly IMealAttendanceService _svc;
|
||||
|
||||
public MealAttendanceController(IMealAttendanceService svc) => _svc = svc;
|
||||
|
||||
/// <summary>Today's live counts. Public — feeds the volunteer counter page on first load.</summary>
|
||||
[HttpGet("today")]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> GetToday()
|
||||
=> Ok(await _svc.GetOrCreateAsync(_svc.ServiceDay));
|
||||
|
||||
/// <summary>Daily counts within a date range, for the back-office dashboard chart.</summary>
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> GetRange([FromQuery] DateOnly from, [FromQuery] DateOnly to)
|
||||
=> Ok(await _svc.GetRangeAsync(from, to));
|
||||
|
||||
/// <summary>Overwrite a specific Sunday's counts (back-office editor). Authenticated only.</summary>
|
||||
[HttpPut("{date}")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> SetCounts(DateOnly date, [FromBody] SetAttendanceRequest body)
|
||||
=> Ok(await _svc.SetCountsAsync(date, body.Adult, body.Youth, body.Kid));
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Members;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/members")]
|
||||
[Authorize]
|
||||
public class MembersController : ControllerBase
|
||||
{
|
||||
private readonly IMemberService _members;
|
||||
public MembersController(IMemberService members) => _members = members;
|
||||
|
||||
/// <summary>GET /api/members?page=1&pageSize=20&search=Chen&status=Member&hasUser=false</summary>
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.Members, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetPaged(
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20,
|
||||
[FromQuery] string? search = null,
|
||||
[FromQuery] string? status = null,
|
||||
[FromQuery] bool? hasUser = null)
|
||||
=> Ok(await _members.GetPagedAsync(page, pageSize, search, status, hasUser));
|
||||
|
||||
/// <summary>GET /api/members/{id}</summary>
|
||||
[HttpGet("{id:int}")]
|
||||
[HasPermission(Modules.Members, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
var dto = await _members.GetByIdAsync(id);
|
||||
return dto is null ? NotFound() : Ok(dto);
|
||||
}
|
||||
|
||||
/// <summary>POST /api/members</summary>
|
||||
[HttpPost]
|
||||
[HasPermission(Modules.Members, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateMemberRequest request)
|
||||
{
|
||||
var id = await _members.CreateAsync(request);
|
||||
return CreatedAtAction(nameof(GetById), new { id }, new { id });
|
||||
}
|
||||
|
||||
/// <summary>PUT /api/members/{id}</summary>
|
||||
[HttpPut("{id:int}")]
|
||||
[HasPermission(Modules.Members, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] UpdateMemberRequest request)
|
||||
{
|
||||
try { await _members.UpdateAsync(id, request); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
|
||||
/// <summary>DELETE /api/members/{id} — soft delete</summary>
|
||||
[HttpDelete("{id:int}")]
|
||||
[HasPermission(Modules.Members, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{
|
||||
try { await _members.DeleteAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Ministry;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/ministries")]
|
||||
[Authorize]
|
||||
public class MinistriesController : ControllerBase
|
||||
{
|
||||
private readonly IMinistryService _svc;
|
||||
public MinistriesController(IMinistryService svc) => _svc = svc;
|
||||
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.Ministries, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetAll([FromQuery] bool includeInactive = false)
|
||||
=> Ok(await _svc.GetAllAsync(includeInactive));
|
||||
|
||||
[HttpPost]
|
||||
[HasPermission(Modules.Ministries, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateMinistryRequest request)
|
||||
{
|
||||
var id = await _svc.CreateAsync(request);
|
||||
return CreatedAtAction(nameof(GetAll), new { id }, new { id });
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[HasPermission(Modules.Ministries, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] UpdateMinistryRequest request)
|
||||
{
|
||||
try { await _svc.UpdateAsync(id, request); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
[HasPermission(Modules.Ministries, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> Deactivate(int id)
|
||||
{
|
||||
try { await _svc.DeactivateAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Expense;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/monthly-statements")]
|
||||
[Authorize]
|
||||
public class MonthlyStatementsController : ControllerBase
|
||||
{
|
||||
private readonly IMonthlyStatementService _svc;
|
||||
public MonthlyStatementsController(IMonthlyStatementService svc) => _svc = svc;
|
||||
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.MonthlyStatements, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetAll([FromQuery] int? year = null)
|
||||
=> Ok(await _svc.GetAllAsync(year));
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
[HasPermission(Modules.MonthlyStatements, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
var dto = await _svc.GetByIdAsync(id);
|
||||
return dto is null ? NotFound() : Ok(dto);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[HasPermission(Modules.MonthlyStatements, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateMonthlyStatementRequest r)
|
||||
{
|
||||
try { return Ok(new { id = await _svc.CreateAsync(r) }); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[HasPermission(Modules.MonthlyStatements, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] UpdateMonthlyStatementRequest r)
|
||||
{
|
||||
try { await _svc.UpdateAsync(id, r); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:int}/finalize")]
|
||||
[HasPermission(Modules.MonthlyStatements, PermissionActions.Approve)]
|
||||
public async Task<IActionResult> Finalize(int id)
|
||||
{
|
||||
try { await _svc.FinalizeAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ROLAC.API.Data;
|
||||
using ROLAC.API.DTOs.Notifications;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using ROLAC.API.Services.Notifications;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Admin endpoints for the notification module (API-only phase). Binding-code generation, group
|
||||
/// management, send history, and manual send — the manual send endpoints are the only way to fire
|
||||
/// a message before a UI exists; programmatic callers use the services directly.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/notifications")]
|
||||
[Authorize]
|
||||
public sealed class NotificationsController : ControllerBase
|
||||
{
|
||||
private readonly IEmailService _email;
|
||||
private readonly ILineNotificationService _line;
|
||||
private readonly AppDbContext _db;
|
||||
private readonly CurrentUserAccessor _currentUser;
|
||||
|
||||
public NotificationsController(
|
||||
IEmailService email, ILineNotificationService line,
|
||||
AppDbContext db, CurrentUserAccessor currentUser)
|
||||
{
|
||||
_email = email;
|
||||
_line = line;
|
||||
_db = db;
|
||||
_currentUser = currentUser;
|
||||
}
|
||||
|
||||
[HttpPost("members/{id:int}/line-binding-code")]
|
||||
public async Task<IActionResult> GenerateBindingCode(int id, CancellationToken ct)
|
||||
=> Ok(new { code = await _line.GenerateLineBindingCodeAsync(id, ct) });
|
||||
|
||||
[HttpGet("groups")]
|
||||
public async Task<IActionResult> Groups(CancellationToken ct)
|
||||
=> Ok(await _db.MessagingGroups
|
||||
.OrderBy(g => g.Id)
|
||||
.Select(g => new { g.Id, g.Name, g.IsActive, g.RegisteredAt })
|
||||
.ToListAsync(ct));
|
||||
|
||||
[HttpPut("groups/{id:int}")]
|
||||
public async Task<IActionResult> UpdateGroup(int id, [FromBody] UpdateGroupRequest request, CancellationToken ct)
|
||||
{
|
||||
var group = await _db.MessagingGroups.FirstOrDefaultAsync(g => g.Id == id, ct);
|
||||
if (group is null) return NotFound();
|
||||
|
||||
group.Name = request.Name;
|
||||
group.IsActive = request.IsActive;
|
||||
await _db.SaveChangesAsync(ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpGet("history")]
|
||||
public async Task<IActionResult> History(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 50, CancellationToken ct = default)
|
||||
{
|
||||
var size = Math.Clamp(pageSize, 1, 200);
|
||||
var skip = (Math.Max(page, 1) - 1) * size;
|
||||
|
||||
var query = _db.NotificationLogs.OrderByDescending(l => l.SentAt);
|
||||
var total = await query.CountAsync(ct);
|
||||
var items = await query
|
||||
.Skip(skip).Take(size)
|
||||
.Select(l => new
|
||||
{
|
||||
l.Id, l.Channel, l.TargetType, l.TargetExternalId, l.Subject,
|
||||
l.Status, l.Error, l.SentByUserId, l.SentAt,
|
||||
})
|
||||
.ToListAsync(ct);
|
||||
|
||||
return Ok(new { total, items });
|
||||
}
|
||||
|
||||
[HttpPost("send-line")]
|
||||
public async Task<IActionResult> SendLine([FromBody] SendLineRequest request, CancellationToken ct)
|
||||
=> Ok(await _line.SendLineAsync(
|
||||
request.Body, request.MemberIds ?? [], request.GroupIds ?? [],
|
||||
_currentUser.UserIdOrSystem, ct));
|
||||
|
||||
[HttpPost("send-email")]
|
||||
public async Task<IActionResult> SendEmail([FromBody] SendEmailRequest request, CancellationToken ct)
|
||||
=> Ok(await _email.SendAsync(new EmailMessage(
|
||||
MemberIds: request.MemberIds ?? [],
|
||||
Addresses: request.Addresses ?? [],
|
||||
Subject: request.Subject,
|
||||
HtmlBody: request.HtmlBody,
|
||||
Attachments: null,
|
||||
SentByUserId: _currentUser.UserIdOrSystem), ct));
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using ROLAC.API.DTOs.Giving;
|
||||
using ROLAC.API.DTOs.Members;
|
||||
using ROLAC.API.Hubs;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Anonymous endpoints powering the mobile Sunday offering-entry page. The page
|
||||
/// has no login yet, so it cannot reach the auth-gated members/categories/
|
||||
/// offering-sessions APIs — these expose just what it needs (active categories,
|
||||
/// a name-only member typeahead, and append-one-line).
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/offering-entry")]
|
||||
[AllowAnonymous]
|
||||
public class OfferingEntryController : ControllerBase
|
||||
{
|
||||
private readonly IOfferingSessionService _sessions;
|
||||
private readonly IGivingCategoryService _categories;
|
||||
private readonly IMemberService _members;
|
||||
private readonly IHubContext<OfferingEntryHub> _hub;
|
||||
|
||||
public OfferingEntryController(
|
||||
IOfferingSessionService sessions,
|
||||
IGivingCategoryService categories,
|
||||
IMemberService members,
|
||||
IHubContext<OfferingEntryHub> hub)
|
||||
{
|
||||
_sessions = sessions;
|
||||
_categories = categories;
|
||||
_members = members;
|
||||
_hub = hub;
|
||||
}
|
||||
|
||||
// Seed the page in one round-trip: active categories + today's session state.
|
||||
[HttpGet("bootstrap")]
|
||||
public async Task<IActionResult> Bootstrap([FromQuery] DateOnly date)
|
||||
=> Ok(new OfferingEntryBootstrapDto
|
||||
{
|
||||
SessionDate = date.ToString("yyyy-MM-dd"),
|
||||
Categories = await _categories.GetAllAsync(false),
|
||||
Summary = await _sessions.GetEntrySummaryAsync(date),
|
||||
});
|
||||
|
||||
// Name-only member suggestions for the giver typeahead.
|
||||
[HttpGet("members")]
|
||||
public async Task<IActionResult> SearchMembers([FromQuery] string? search, [FromQuery] int take = 10)
|
||||
=> Ok(await _sessions.SearchMembersForEntryAsync(search, Math.Clamp(take, 1, 25)));
|
||||
|
||||
// Quick-add a giver who isn't on file yet (created as a Visitor). Reuses the
|
||||
// member service directly — role checks live on MembersController, so this
|
||||
// anonymous path is the intended public entry point for the mobile page.
|
||||
[HttpPost("members")]
|
||||
public async Task<IActionResult> QuickAddMember([FromBody] QuickAddMemberRequest request)
|
||||
{
|
||||
var id = await _members.CreateAsync(new CreateMemberRequest
|
||||
{
|
||||
FirstName_en = request.FirstName_en,
|
||||
LastName_en = request.LastName_en,
|
||||
NickName = request.NickName,
|
||||
FirstName_zh = request.FirstName_zh,
|
||||
LastName_zh = request.LastName_zh,
|
||||
Entity = request.Entity,
|
||||
PhoneCell = request.PhoneCell,
|
||||
Status = "Visitor",
|
||||
Country = "USA",
|
||||
LanguagePreference = "en",
|
||||
});
|
||||
return Ok(new MemberTypeaheadDto
|
||||
{
|
||||
Id = id, NickName = request.NickName,
|
||||
FirstName_en = request.FirstName_en, LastName_en = request.LastName_en,
|
||||
Entity = request.Entity,
|
||||
});
|
||||
}
|
||||
|
||||
// Append one offering line to the date's session (find-or-create), then
|
||||
// broadcast it to everyone viewing that date.
|
||||
[HttpPost("lines")]
|
||||
public async Task<IActionResult> AppendLine([FromBody] AppendOfferingLineRequest request)
|
||||
{
|
||||
var result = await _sessions.AppendLineAsync(request.Date, request.Line);
|
||||
await _hub.Clients.Group(result.SessionDate).SendAsync("LineAdded", result);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// ── Paper-proof PDF for the date's session (merged client-side) ──────────
|
||||
// Date-keyed so the anonymous page (which has no session id) can attach the
|
||||
// count sheet / envelope photos. Mirrors OfferingSessionsController's proof
|
||||
// validation; the desktop session page reviews/deletes the result.
|
||||
|
||||
[HttpGet("proof")]
|
||||
public async Task<IActionResult> GetProof([FromQuery] DateOnly date)
|
||||
{
|
||||
var result = await _sessions.OpenProofForDateAsync(date);
|
||||
if (result is null) return NoContent(); // no session/proof yet — client merges nothing
|
||||
return File(result.Value.stream, result.Value.contentType);
|
||||
}
|
||||
|
||||
[HttpPost("proof")]
|
||||
[RequestSizeLimit(52_428_800)] // 50 MB — a merged multi-image PDF is larger than one receipt
|
||||
public async Task<IActionResult> UploadProof([FromForm] DateOnly date, IFormFile file)
|
||||
{
|
||||
if (file is null || file.Length == 0) return BadRequest(new { message = "No file." });
|
||||
if (file.ContentType != "application/pdf") return BadRequest(new { message = "Proof must be a PDF." });
|
||||
await using var stream = file.OpenReadStream();
|
||||
await _sessions.SaveProofForDateAsync(date, stream, file.FileName);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Giving;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/offering-sessions")]
|
||||
[Authorize]
|
||||
public class OfferingSessionsController : ControllerBase
|
||||
{
|
||||
private readonly IOfferingSessionService _svc;
|
||||
public OfferingSessionsController(IOfferingSessionService svc) => _svc = svc;
|
||||
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.OfferingSessions, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetPaged(
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 20,
|
||||
[FromQuery] DateOnly? from = null, [FromQuery] DateOnly? to = null)
|
||||
=> Ok(await _svc.GetPagedAsync(page, pageSize, from, to));
|
||||
|
||||
[HttpGet("check-date")]
|
||||
[HasPermission(Modules.OfferingSessions, PermissionActions.Read)]
|
||||
public async Task<IActionResult> CheckDate([FromQuery] DateOnly date)
|
||||
=> Ok(new { exists = await _svc.DateExistsAsync(date) });
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
[HasPermission(Modules.OfferingSessions, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
var dto = await _svc.GetByIdAsync(id);
|
||||
return dto is null ? NotFound() : Ok(dto);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[HasPermission(Modules.OfferingSessions, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateOfferingSessionRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
var id = await _svc.CreateAsync(request);
|
||||
return CreatedAtAction(nameof(GetById), new { id }, new { id });
|
||||
}
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:int}/reopen")]
|
||||
[HasPermission(Modules.OfferingSessions, PermissionActions.Approve)]
|
||||
public async Task<IActionResult> Reopen(int id)
|
||||
{
|
||||
try { await _svc.ReopenAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[HasPermission(Modules.OfferingSessions, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Replace(int id, [FromBody] CreateOfferingSessionRequest request)
|
||||
{
|
||||
try { await _svc.ReplaceAsync(id, request); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
// ── Paper-proof PDF (merged client-side, one file per session) ───────────
|
||||
|
||||
[HttpPost("{id:int}/proof")]
|
||||
[HasPermission(Modules.OfferingSessions, PermissionActions.Write)]
|
||||
[RequestSizeLimit(52_428_800)] // 50 MB — a merged multi-image PDF is larger than one receipt
|
||||
public async Task<IActionResult> UploadProof(int id, IFormFile file)
|
||||
{
|
||||
if (file is null || file.Length == 0) return BadRequest(new { message = "No file." });
|
||||
if (file.ContentType != "application/pdf") return BadRequest(new { message = "Proof must be a PDF." });
|
||||
try
|
||||
{
|
||||
await using var stream = file.OpenReadStream();
|
||||
await _svc.SaveProofAsync(id, stream, file.FileName);
|
||||
return NoContent();
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}/proof")]
|
||||
[HasPermission(Modules.OfferingSessions, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetProof(int id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _svc.OpenProofAsync(id);
|
||||
if (result is null) return NotFound();
|
||||
return File(result.Value.stream, result.Value.contentType);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}/proof")]
|
||||
[HasPermission(Modules.OfferingSessions, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> DeleteProof(int id)
|
||||
{
|
||||
try { await _svc.DeleteProofAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Payee;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/payee-1099")]
|
||||
[HasPermission(Modules.Form1099, PermissionActions.Read)]
|
||||
public class Payee1099Controller : ControllerBase
|
||||
{
|
||||
private readonly IPayee1099Service _svc;
|
||||
public Payee1099Controller(IPayee1099Service svc) => _svc = svc;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll([FromQuery] bool includeInactive = false)
|
||||
=> Ok(await _svc.GetAllAsync(includeInactive));
|
||||
|
||||
[HttpGet("{id:int}")]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
=> await _svc.GetByIdAsync(id) is { } dto ? Ok(dto) : NotFound();
|
||||
|
||||
[HttpPost]
|
||||
[HasPermission(Modules.Form1099, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Create([FromBody] SavePayee1099Request r)
|
||||
=> Ok(new { id = await _svc.CreateAsync(r) });
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[HasPermission(Modules.Form1099, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] SavePayee1099Request r)
|
||||
{ await _svc.UpdateAsync(id, r); return NoContent(); }
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
[HasPermission(Modules.Form1099, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{ await _svc.DeleteAsync(id); return NoContent(); }
|
||||
|
||||
// Full TIN reveal is gated on Write (a stronger right than Read).
|
||||
[HttpGet("{id:int}/tin")]
|
||||
[HasPermission(Modules.Form1099, PermissionActions.Write)]
|
||||
public async Task<IActionResult> RevealTin(int id)
|
||||
=> Ok(new { tin = await _svc.RevealTinAsync(id) });
|
||||
|
||||
// Mirrors the expense-receipt upload: multipart form file, size-limited, type-checked.
|
||||
[HttpPost("{id:int}/w9")]
|
||||
[HasPermission(Modules.Form1099, PermissionActions.Write)]
|
||||
[RequestSizeLimit(10_485_760)]
|
||||
public async Task<IActionResult> UploadW9(int id, IFormFile file)
|
||||
{
|
||||
if (file is null || file.Length == 0) return BadRequest(new { message = "No file." });
|
||||
var allowed = new[] { "image/jpeg", "image/png", "image/webp", "application/pdf" };
|
||||
if (!allowed.Contains(file.ContentType)) return BadRequest(new { message = "Unsupported file type." });
|
||||
try
|
||||
{
|
||||
await using var stream = file.OpenReadStream();
|
||||
await _svc.SaveW9Async(id, stream, file.FileName);
|
||||
return NoContent();
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
|
||||
// Class-level Read gate covers viewing the stored W-9 (mirrors the receipt GET).
|
||||
[HttpGet("{id:int}/w9")]
|
||||
public async Task<IActionResult> GetW9(int id)
|
||||
{
|
||||
var result = await _svc.OpenW9Async(id);
|
||||
if (result is null) return NotFound();
|
||||
return File(result.Value.stream, result.Value.contentType);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Permissions;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Admin surface for the configurable RBAC matrix. Restricted to super_admin —
|
||||
/// the role that governs who governs everyone else.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/permissions")]
|
||||
[Authorize(Roles = "super_admin")]
|
||||
public class PermissionsController : ControllerBase
|
||||
{
|
||||
private readonly IPermissionService _permissions;
|
||||
public PermissionsController(IPermissionService permissions) => _permissions = permissions;
|
||||
|
||||
/// <summary>GET /api/permissions — the full role × module matrix.</summary>
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetMatrix() => Ok(await _permissions.GetMatrixAsync());
|
||||
|
||||
/// <summary>GET /api/permissions/catalog — module + action names for the grid.</summary>
|
||||
[HttpGet("catalog")]
|
||||
public IActionResult GetCatalog() => Ok(new PermissionCatalogDto
|
||||
{
|
||||
Modules = Modules.All,
|
||||
Actions = PermissionActions.All,
|
||||
});
|
||||
|
||||
/// <summary>PUT /api/permissions/{roleName} — replaces a role's grants.</summary>
|
||||
[HttpPut("{roleName}")]
|
||||
public async Task<IActionResult> UpdateRole(string roleName, [FromBody] UpdateRolePermissionsRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _permissions.UpsertRoleAsync(roleName, request.Modules);
|
||||
return NoContent();
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Settings;
|
||||
using ROLAC.API.Services;
|
||||
using ROLAC.API.Services.Logging;
|
||||
using ROLAC.API.Services.Notifications;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Site-wide and notification (SMTP/Line) settings, surfaced by the Church Profile → Site /
|
||||
/// Notification tabs. Gated by the <c>Settings</c> permission module (super_admin bypasses).
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/settings")]
|
||||
[Authorize]
|
||||
public class SettingsController : ControllerBase
|
||||
{
|
||||
private readonly ISettingsService _settings;
|
||||
private readonly IEmailService _email;
|
||||
private readonly ILineNotificationService _line;
|
||||
private readonly CurrentUserAccessor _currentUser;
|
||||
|
||||
public SettingsController(
|
||||
ISettingsService settings,
|
||||
IEmailService email,
|
||||
ILineNotificationService line,
|
||||
CurrentUserAccessor currentUser)
|
||||
{
|
||||
_settings = settings;
|
||||
_email = email;
|
||||
_line = line;
|
||||
_currentUser = currentUser;
|
||||
}
|
||||
|
||||
// ── Site settings ────────────────────────────────────────────────────────
|
||||
|
||||
[HttpGet("site")]
|
||||
[HasPermission(Modules.Settings, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetSite() => Ok(await _settings.GetSiteAsync());
|
||||
|
||||
[HttpPut("site")]
|
||||
[HasPermission(Modules.Settings, PermissionActions.Write)]
|
||||
public async Task<IActionResult> UpdateSite([FromBody] UpdateSiteSettingRequest request)
|
||||
{
|
||||
await _settings.UpdateSiteAsync(request);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// ── Notification settings ──────────────────────────────────────────────────
|
||||
|
||||
[HttpGet("notification")]
|
||||
[HasPermission(Modules.Settings, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetNotification()
|
||||
{
|
||||
var dto = await _settings.GetNotificationAsync();
|
||||
dto.WebhookUrl = $"{Request.Scheme}://{Request.Host}/api/line/webhook";
|
||||
return Ok(dto);
|
||||
}
|
||||
|
||||
[HttpPut("notification")]
|
||||
[HasPermission(Modules.Settings, PermissionActions.Write)]
|
||||
public async Task<IActionResult> UpdateNotification([FromBody] UpdateNotificationSettingRequest request)
|
||||
{
|
||||
await _settings.UpdateNotificationAsync(request);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("notification/test-email")]
|
||||
[HasPermission(Modules.Settings, PermissionActions.Write)]
|
||||
public async Task<IActionResult> TestEmail([FromBody] TestEmailRequest request, CancellationToken ct)
|
||||
{
|
||||
var to = string.IsNullOrWhiteSpace(request.ToAddress) ? _currentUser.Email : request.ToAddress;
|
||||
if (string.IsNullOrWhiteSpace(to))
|
||||
return BadRequest(new { message = "No recipient — provide an address or set an email on your account." });
|
||||
|
||||
var result = await _email.SendAsync(new EmailMessage(
|
||||
MemberIds: Array.Empty<int>(),
|
||||
Addresses: new[] { to },
|
||||
Subject: "ROLAC test email / 測試郵件",
|
||||
HtmlBody: "<p>This is a test email from ROLAC notification settings.</p>"
|
||||
+ "<p>這是來自 ROLAC 通知設定的測試郵件。</p>",
|
||||
SentByUserId: _currentUser.UserIdOrSystem), ct);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("notification/test-line")]
|
||||
[HasPermission(Modules.Settings, PermissionActions.Write)]
|
||||
public async Task<IActionResult> TestLine([FromBody] TestLineRequest request, CancellationToken ct)
|
||||
{
|
||||
if (request.MemberId is null && request.GroupId is null)
|
||||
return BadRequest(new { message = "Choose a bound member or group to receive the test." });
|
||||
|
||||
var result = await _line.SendLineAsync(
|
||||
body: "ROLAC 測試訊息 / This is a test Line message from ROLAC.",
|
||||
memberIds: request.MemberId is { } m ? new[] { m } : Array.Empty<int>(),
|
||||
groupIds: request.GroupId is { } g ? new[] { g } : Array.Empty<int>(),
|
||||
sentByUserId: _currentUser.UserIdOrSystem,
|
||||
ct);
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Logging;
|
||||
using ROLAC.API.Entities.Logging;
|
||||
using ROLAC.API.Services.Logging;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/system-logs")]
|
||||
[Authorize]
|
||||
public class SystemLogsController : ControllerBase
|
||||
{
|
||||
private readonly ISystemLogQueryService _svc;
|
||||
public SystemLogsController(ISystemLogQueryService svc) => _svc = svc;
|
||||
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.SystemLogs, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetPaged([FromQuery] SystemLogQuery query)
|
||||
=> Ok(await _svc.GetPagedAsync(query));
|
||||
|
||||
[HttpGet("{id:long}")]
|
||||
[HasPermission(Modules.SystemLogs, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetById(long id)
|
||||
{
|
||||
var dto = await _svc.GetByIdAsync(id);
|
||||
return dto is null ? NotFound() : Ok(dto);
|
||||
}
|
||||
|
||||
/// <summary>All six severities, so the UI can offer every filter option regardless of data.</summary>
|
||||
[HttpGet("levels")]
|
||||
[HasPermission(Modules.SystemLogs, PermissionActions.Read)]
|
||||
public IActionResult GetLevels() => Ok(Enum.GetNames<LogLevelEnum>());
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ROLAC.API.Authorization;
|
||||
using ROLAC.API.DTOs.Users;
|
||||
using ROLAC.API.Services;
|
||||
|
||||
namespace ROLAC.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/users")]
|
||||
[Authorize]
|
||||
public class UsersController : ControllerBase
|
||||
{
|
||||
private readonly IUserManagementService _users;
|
||||
public UsersController(IUserManagementService users) => _users = users;
|
||||
|
||||
/// <summary>GET /api/users?page=1&pageSize=20&search=Chris</summary>
|
||||
[HttpGet]
|
||||
[HasPermission(Modules.Users, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetPaged(
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20,
|
||||
[FromQuery] string? search = null)
|
||||
=> Ok(await _users.GetPagedAsync(page, pageSize, search));
|
||||
|
||||
/// <summary>GET /api/users/{id}</summary>
|
||||
[HttpGet("{id}")]
|
||||
[HasPermission(Modules.Users, PermissionActions.Read)]
|
||||
public async Task<IActionResult> GetById(string id)
|
||||
{
|
||||
var dto = await _users.GetByIdAsync(id);
|
||||
return dto is null ? NotFound() : Ok(dto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// POST /api/users — creates account for a Member, returns { userId, tempPassword }.
|
||||
/// TempPassword is returned ONCE — show it to the admin and never log it.
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
[HasPermission(Modules.Users, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateUserRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await _users.CreateAsync(request);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return BadRequest(new { message = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>PUT /api/users/{id} — update email, roles, IsActive</summary>
|
||||
[HttpPut("{id}")]
|
||||
[HasPermission(Modules.Users, PermissionActions.Write)]
|
||||
public async Task<IActionResult> Update(string id, [FromBody] UpdateUserRequest request)
|
||||
{
|
||||
try { await _users.UpdateAsync(id, request); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); }
|
||||
}
|
||||
|
||||
/// <summary>DELETE /api/users/{id} — deactivates account (IsActive=false), does not delete</summary>
|
||||
[HttpDelete("{id}")]
|
||||
[HasPermission(Modules.Users, PermissionActions.Delete)]
|
||||
public async Task<IActionResult> Deactivate(string id)
|
||||
{
|
||||
try { await _users.DeactivateAsync(id); return NoContent(); }
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
|
||||
/// <summary>POST /api/users/{id}/reset-password — returns new temp password</summary>
|
||||
[HttpPost("{id}/reset-password")]
|
||||
[HasPermission(Modules.Users, PermissionActions.Write)]
|
||||
public async Task<IActionResult> ResetPassword(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var pwd = await _users.ResetPasswordAsync(id);
|
||||
return Ok(new { tempPassword = pwd });
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace ROLAC.API.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class WeatherForecastController : ControllerBase
|
||||
{
|
||||
private static readonly string[] Summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
private readonly ILogger<WeatherForecastController> _logger;
|
||||
|
||||
public WeatherForecastController(ILogger<WeatherForecastController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet(Name = "GetWeatherForecast")]
|
||||
public IEnumerable<WeatherForecast> Get()
|
||||
{
|
||||
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
|
||||
{
|
||||
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
||||
TemperatureC = Random.Shared.Next(-20, 55),
|
||||
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace ROLAC.API.DTOs.Auth;
|
||||
|
||||
public class ChangePasswordRequest
|
||||
{
|
||||
[Required]
|
||||
[MaxLength(128)]
|
||||
public string CurrentPassword { get; set; } = null!;
|
||||
|
||||
[Required]
|
||||
[MinLength(8)]
|
||||
[MaxLength(128)]
|
||||
public string NewPassword { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace ROLAC.API.DTOs.Auth;
|
||||
|
||||
public class LoginRequest
|
||||
{
|
||||
[Required]
|
||||
[EmailAddress]
|
||||
[MaxLength(256)]
|
||||
public string Email { get; set; } = null!;
|
||||
|
||||
[Required]
|
||||
[MinLength(8)]
|
||||
[MaxLength(128)]
|
||||
public string Password { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using ROLAC.API.DTOs.Permissions;
|
||||
|
||||
namespace ROLAC.API.DTOs.Auth;
|
||||
|
||||
public class LoginResponse
|
||||
{
|
||||
/// <summary>Short-lived JWT (15 min). Store in memory — never in localStorage.</summary>
|
||||
public string AccessToken { get; set; } = null!;
|
||||
|
||||
/// <summary>Seconds until the access token expires. Always 900 (15 × 60).</summary>
|
||||
public int ExpiresIn { get; set; }
|
||||
|
||||
public UserInfo User { get; set; } = null!;
|
||||
}
|
||||
|
||||
public class UserInfo
|
||||
{
|
||||
public string Id { get; set; } = null!;
|
||||
public string Email { get; set; } = null!;
|
||||
public IList<string> Roles { get; set; } = [];
|
||||
public string LanguagePreference { get; set; } = "en";
|
||||
|
||||
/// <summary>
|
||||
/// Effective permissions (union across the user's roles), keyed by module name.
|
||||
/// Lets the SPA hide nav/buttons. Authoritative enforcement is server-side.
|
||||
/// </summary>
|
||||
public Dictionary<string, ModuleActions> Permissions { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// The church member linked to this login account, or null for admin-only
|
||||
/// accounts (no MemberId) and accounts whose member record was deleted.
|
||||
/// Lets the SPA greet the user by their real name.
|
||||
/// </summary>
|
||||
public MemberInfo? MemberInfo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Minimal member identity for greeting the signed-in user.</summary>
|
||||
public class MemberInfo
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string? NickName { get; set; }
|
||||
public string FirstName_en { get; set; } = "";
|
||||
public string LastName_en { get; set; } = "";
|
||||
public string? FirstName_zh { get; set; }
|
||||
public string? LastName_zh { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Disbursement;
|
||||
|
||||
public class ChurchProfileDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = "";
|
||||
public string? NameZh { get; set; }
|
||||
public string? Phone { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public string? Website { get; set; }
|
||||
public string? Address { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
public string? ZipCode { get; set; }
|
||||
public string? BankName { get; set; }
|
||||
public string? BankAccountNumber { get; set; }
|
||||
public string? BankRoutingNumber { get; set; }
|
||||
public string? PayerEin { get; set; }
|
||||
public int NextCheckNumber { get; set; }
|
||||
public string AiProvider { get; set; } = "Claude";
|
||||
public string? ClaudeModel { get; set; }
|
||||
public string? ClaudeApiKeyMasked { get; set; }
|
||||
public string? GeminiModel { get; set; }
|
||||
public string? GeminiApiKeyMasked { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateChurchProfileRequest
|
||||
{
|
||||
[Required, MaxLength(200)] public string Name { get; set; } = "";
|
||||
[MaxLength(200)] public string? NameZh { get; set; }
|
||||
[MaxLength(50)] public string? Phone { get; set; }
|
||||
[MaxLength(200), EmailAddress] public string? Email { get; set; }
|
||||
[MaxLength(300)] public string? Website { get; set; }
|
||||
[MaxLength(500)] public string? Address { get; set; }
|
||||
[MaxLength(100)] public string? City { get; set; }
|
||||
[MaxLength(50)] public string? State { get; set; }
|
||||
[MaxLength(20)] public string? ZipCode { get; set; }
|
||||
[MaxLength(200)] public string? BankName { get; set; }
|
||||
[MaxLength(50)] public string? BankAccountNumber { get; set; }
|
||||
[MaxLength(50)] public string? BankRoutingNumber { get; set; }
|
||||
[MaxLength(20)] public string? PayerEin { get; set; }
|
||||
[Range(1, int.MaxValue)] public int NextCheckNumber { get; set; }
|
||||
[MaxLength(20)] public string AiProvider { get; set; } = "Claude";
|
||||
[MaxLength(100)] public string? ClaudeModel { get; set; }
|
||||
[MaxLength(500)] public string? ClaudeApiKey { get; set; } // null/blank = leave unchanged
|
||||
[MaxLength(100)] public string? GeminiModel { get; set; }
|
||||
[MaxLength(500)] public string? GeminiApiKey { get; set; } // null/blank = leave unchanged
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Disbursement;
|
||||
|
||||
// ── Approved-unpaid expenses, grouped by payee (the issue-check worklist) ──────
|
||||
|
||||
public class ExpenseLineDto
|
||||
{
|
||||
public int ExpenseId { get; set; }
|
||||
public string ExpenseDate { get; set; } = ""; // yyyy-MM-dd
|
||||
public string Description { get; set; } = "";
|
||||
public decimal Amount { get; set; }
|
||||
public string MinistryName { get; set; } = "";
|
||||
public string CategoryName { get; set; } = "";
|
||||
}
|
||||
|
||||
public class PayeeGroupDto
|
||||
{
|
||||
public string PayeeType { get; set; } = "Vendor"; // Vendor | Member
|
||||
public int? MemberId { get; set; }
|
||||
public string? VendorKey { get; set; } // normalized vendor name (grouping key)
|
||||
public string PayeeName { get; set; } = "";
|
||||
public string? Address { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
public string? Zip { get; set; }
|
||||
public decimal TotalAmount { get; set; }
|
||||
public List<ExpenseLineDto> Lines { get; set; } = [];
|
||||
}
|
||||
|
||||
// ── Issue checks ──────────────────────────────────────────────────────────────
|
||||
|
||||
public class PayeeCheckInstruction
|
||||
{
|
||||
[Required] public string PayeeType { get; set; } = "Vendor";
|
||||
public int? MemberId { get; set; }
|
||||
public string? VendorKey { get; set; }
|
||||
[Required, MaxLength(200)] public string PayeeName { get; set; } = "";
|
||||
[MaxLength(500)] public string? Address { get; set; }
|
||||
[MaxLength(100)] public string? City { get; set; }
|
||||
[MaxLength(50)] public string? State { get; set; }
|
||||
[MaxLength(20)] public string? Zip { get; set; }
|
||||
[MaxLength(50)] public string? CheckNumberOverride { get; set; }
|
||||
[MaxLength(500)] public string? Memo { get; set; }
|
||||
[Required, MinLength(1)] public List<int> ExpenseIds { get; set; } = [];
|
||||
}
|
||||
|
||||
public class IssueChecksRequest
|
||||
{
|
||||
[Required] public DateOnly CheckDate { get; set; }
|
||||
[Required, MinLength(1)] public List<PayeeCheckInstruction> Payees { get; set; } = [];
|
||||
}
|
||||
|
||||
public class IssuedCheckDto
|
||||
{
|
||||
public int CheckId { get; set; }
|
||||
public string CheckNumber { get; set; } = "";
|
||||
public string PayeeName { get; set; } = "";
|
||||
public decimal Amount { get; set; }
|
||||
}
|
||||
|
||||
public class IssueChecksResultDto
|
||||
{
|
||||
public List<IssuedCheckDto> Created { get; set; } = [];
|
||||
}
|
||||
|
||||
// ── Check register / detail ───────────────────────────────────────────────────
|
||||
|
||||
public class CheckListItemDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string CheckNumber { get; set; } = "";
|
||||
public string CheckDate { get; set; } = ""; // yyyy-MM-dd
|
||||
public decimal Amount { get; set; }
|
||||
public string PayeeType { get; set; } = "";
|
||||
public string PayeeName { get; set; } = "";
|
||||
public string Status { get; set; } = "";
|
||||
public int LineCount { get; set; }
|
||||
public bool Signed { get; set; }
|
||||
public string? ReceiptSignedName { get; set; }
|
||||
public DateTimeOffset? ReceiptSignedAt { get; set; }
|
||||
}
|
||||
|
||||
public class CheckLineDto
|
||||
{
|
||||
public int ExpenseId { get; set; }
|
||||
public string Description { get; set; } = "";
|
||||
public decimal Amount { get; set; }
|
||||
}
|
||||
|
||||
public class CheckDetailDto : CheckListItemDto
|
||||
{
|
||||
public int? MemberId { get; set; }
|
||||
public string? Address { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
public string? Zip { get; set; }
|
||||
public string? Memo { get; set; }
|
||||
public string? VoidReason { get; set; }
|
||||
public DateTimeOffset? VoidedAt { get; set; }
|
||||
public DateTimeOffset IssuedAt { get; set; }
|
||||
public List<CheckLineDto> Lines { get; set; } = [];
|
||||
}
|
||||
|
||||
public class VoidCheckRequest
|
||||
{
|
||||
[MaxLength(500)] public string? Reason { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Expense;
|
||||
|
||||
/// <summary>Request body for the expense AI assist endpoint.</summary>
|
||||
public class ExpenseAiAssistRequest
|
||||
{
|
||||
/// <summary>The user's free-text expense description (typically Chinese).</summary>
|
||||
[Required] public string Text { get; set; } = "";
|
||||
/// <summary>The expense amount, used as a hint when classifying the category.</summary>
|
||||
public decimal Amount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AI suggestion for an expense: an English translation of the description plus a proposed
|
||||
/// major category (大項) and sub-category (系項). Category ids are null when the model could
|
||||
/// not confidently classify or returned an id outside the live catalog.
|
||||
/// </summary>
|
||||
public class ExpenseAiSuggestion
|
||||
{
|
||||
public string? EnglishDescription { get; set; }
|
||||
/// <summary>Typo-corrected, refined Traditional Chinese description.</summary>
|
||||
public string? ChineseDescription { get; set; }
|
||||
public int? GroupId { get; set; }
|
||||
public int? SubCategoryId { get; set; }
|
||||
/// <summary>Bilingual label of the suggested group, e.g. "Consumables / 消耗品".</summary>
|
||||
public string? GroupLabel { get; set; }
|
||||
/// <summary>Bilingual label of the suggested sub-category, e.g. "Batteries / 電池".</summary>
|
||||
public string? SubLabel { get; set; }
|
||||
/// <summary>Model self-reported confidence in the classification, 0..1.</summary>
|
||||
public double Confidence { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request body for the expense-category AI assist endpoint: refine the name, translate to English,
|
||||
/// and suggest a Form 990 line for an expense category (大項/小項) being defined or edited.
|
||||
/// </summary>
|
||||
public class ExpenseCategoryAiRequest
|
||||
{
|
||||
/// <summary>The user-typed Chinese name (the primary input).</summary>
|
||||
public string Name_zh { get; set; } = "";
|
||||
/// <summary>The English name, if already typed (extra context for the model).</summary>
|
||||
public string? Name_en { get; set; }
|
||||
/// <summary>"group" (大項) or "sub" (小項); selects the prompt framing.</summary>
|
||||
public string Level { get; set; } = "group";
|
||||
/// <summary>For a sub-category: the parent group's bilingual name, used for context.</summary>
|
||||
public string? ParentGroupName { get; set; }
|
||||
/// <summary>For a sub-category: the parent group's mapped Form 990 line id, used to bias the choice.</summary>
|
||||
public int? ParentForm990LineId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AI suggestion for an expense category: a refined Chinese name, an English translation, and a
|
||||
/// proposed Form 990 line. Line fields are null when the model returned an id outside the live catalog.
|
||||
/// </summary>
|
||||
public class CategoryAiSuggestion
|
||||
{
|
||||
/// <summary>Typo-corrected, refined Traditional Chinese name.</summary>
|
||||
public string? ChineseName { get; set; }
|
||||
public string? EnglishName { get; set; }
|
||||
public int? Form990LineId { get; set; }
|
||||
/// <summary>Bilingual label of the suggested line, e.g. "16 — Occupancy / 場地".</summary>
|
||||
public string? Form990LineLabel { get; set; }
|
||||
/// <summary>Model self-reported confidence in the mapping, 0..1.</summary>
|
||||
public double Confidence { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Expense;
|
||||
|
||||
public class ExpenseSubCategoryDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int GroupId { get; set; }
|
||||
public string Name_en { get; set; } = "";
|
||||
public string? Name_zh { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
public int? Form990LineId { get; set; }
|
||||
public string? Form990LineCode { get; set; }
|
||||
public int? Form1099BoxId { get; set; }
|
||||
public string? Form1099BoxCode { get; set; }
|
||||
}
|
||||
|
||||
public class ExpenseCategoryGroupDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name_en { get; set; } = "";
|
||||
public string? Name_zh { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
public int? Form990LineId { get; set; }
|
||||
public string? Form990LineCode { get; set; }
|
||||
public int? Form1099BoxId { get; set; }
|
||||
public string? Form1099BoxCode { get; set; }
|
||||
public List<ExpenseSubCategoryDto> SubCategories { get; set; } = [];
|
||||
}
|
||||
|
||||
public class CreateExpenseGroupRequest
|
||||
{
|
||||
[Required, MaxLength(200)] public string Name_en { get; set; } = "";
|
||||
[MaxLength(200)] public string? Name_zh { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
public int? Form990LineId { get; set; }
|
||||
public int? Form1099BoxId { get; set; }
|
||||
}
|
||||
public class UpdateExpenseGroupRequest : CreateExpenseGroupRequest
|
||||
{
|
||||
public bool IsActive { get; set; } = true;
|
||||
}
|
||||
|
||||
public class CreateExpenseSubCategoryRequest
|
||||
{
|
||||
[Required] public int GroupId { get; set; }
|
||||
[Required, MaxLength(200)] public string Name_en { get; set; } = "";
|
||||
[MaxLength(200)] public string? Name_zh { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
public int? Form990LineId { get; set; }
|
||||
public int? Form1099BoxId { get; set; }
|
||||
}
|
||||
public class UpdateExpenseSubCategoryRequest : CreateExpenseSubCategoryRequest
|
||||
{
|
||||
public bool IsActive { get; set; } = true;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Expense;
|
||||
|
||||
public class ExpenseLineItemDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int CategoryGroupId { get; set; }
|
||||
public string CategoryGroupName { get; set; } = "";
|
||||
public int SubCategoryId { get; set; }
|
||||
public string SubCategoryName { get; set; } = "";
|
||||
public string? FunctionalClass { get; set; }
|
||||
public decimal Amount { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
|
||||
public class ExpenseListItemDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Type { get; set; } = "";
|
||||
public string Status { get; set; } = "";
|
||||
public decimal Amount { get; set; } // header total = sum of line amounts
|
||||
public string Description { get; set; } = "";
|
||||
public int MinistryId { get; set; }
|
||||
public string MinistryName { get; set; } = "";
|
||||
public int LineCount { get; set; }
|
||||
public string PrimaryCategoryName { get; set; } = ""; // first line's category (list hint; full breakdown via detail)
|
||||
public string? VendorName { get; set; }
|
||||
public int? MemberId { get; set; }
|
||||
public string? MemberName { get; set; } // legal name "FirstName_en LastName_en" (used on the printed check)
|
||||
public string? MemberNickName { get; set; } // "NickName LastName_en"; null when the member has no distinct nickname
|
||||
public string ExpenseDate { get; set; } = ""; // yyyy-MM-dd
|
||||
public bool HasReceipt { get; set; }
|
||||
public string? CheckNumber { get; set; }
|
||||
// Review outcome — surfaced on the list so the Status column can show "Approved/Rejected by X · date".
|
||||
public string? ReviewedByName { get; set; } // resolved Member full name, email fallback
|
||||
public DateTimeOffset? ReviewedAt { get; set; }
|
||||
public string? ReviewNotes { get; set; } // reject reason (or approval note)
|
||||
public int? PayeeId { get; set; }
|
||||
}
|
||||
|
||||
public class ExpenseDto : ExpenseListItemDto
|
||||
{
|
||||
public string? Notes { get; set; }
|
||||
public string? SubmittedBy { get; set; }
|
||||
public DateTimeOffset? SubmittedAt { get; set; }
|
||||
public DateTimeOffset? PaidAt { get; set; }
|
||||
public List<ExpenseLineItemDto> Lines { get; set; } = new();
|
||||
}
|
||||
|
||||
public class ExpenseLineInput
|
||||
{
|
||||
[Required] public int CategoryGroupId { get; set; }
|
||||
[Required] public int SubCategoryId { get; set; }
|
||||
[Range(0.01, 9_999_999)] public decimal Amount { get; set; }
|
||||
[MaxLength(20)] public string? FunctionalClass { get; set; }
|
||||
[MaxLength(500)] public string? Description { get; set; }
|
||||
}
|
||||
|
||||
public class CreateExpenseRequest
|
||||
{
|
||||
[Required] public string Type { get; set; } = "StaffReimbursement"; // VendorPayment|StaffReimbursement
|
||||
[Required] public int MinistryId { get; set; }
|
||||
[Required, MinLength(1)] public List<ExpenseLineInput> Lines { get; set; } = new();
|
||||
[Required, MaxLength(500)] public string Description { get; set; } = "";
|
||||
[MaxLength(200)] public string? VendorName { get; set; }
|
||||
public int? MemberId { get; set; } // ignored for self-service (server uses caller)
|
||||
[MaxLength(50)] public string? CheckNumber { get; set; }
|
||||
[Required] public DateOnly ExpenseDate { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public int? PayeeId { get; set; }
|
||||
}
|
||||
public class UpdateExpenseRequest : CreateExpenseRequest { }
|
||||
|
||||
public class RejectExpenseRequest
|
||||
{
|
||||
[MaxLength(500)] public string? ReviewNotes { get; set; }
|
||||
}
|
||||
public class PayExpenseRequest
|
||||
{
|
||||
[MaxLength(50)] public string? CheckNumber { get; set; }
|
||||
public DateOnly? PaidAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Expense;
|
||||
|
||||
public class ExpenseSnapshotLineDto
|
||||
{
|
||||
public int CategoryGroupId { get; set; }
|
||||
public string CategoryGroupName { get; set; } = "";
|
||||
public int SubCategoryId { get; set; }
|
||||
public string SubCategoryName { get; set; } = "";
|
||||
public string? FunctionalClass { get; set; }
|
||||
public decimal Amount { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
|
||||
public class ExpenseSnapshotDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = "";
|
||||
public int MinistryId { get; set; }
|
||||
public string MinistryName { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
public string? VendorName { get; set; }
|
||||
public string? CheckNumber { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public decimal TotalAmount { get; set; } // sum of line amounts (list hint)
|
||||
public int LineCount { get; set; }
|
||||
public string? CreatedByName { get; set; } // resolved Member full name, email fallback
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
public List<ExpenseSnapshotLineDto> Lines { get; set; } = new();
|
||||
}
|
||||
|
||||
public class CreateExpenseSnapshotRequest
|
||||
{
|
||||
[Required, MaxLength(150)] public string Name { get; set; } = "";
|
||||
[Required] public int MinistryId { get; set; }
|
||||
[Required, MinLength(1)] public List<ExpenseLineInput> Lines { get; set; } = new();
|
||||
[Required, MaxLength(500)] public string Description { get; set; } = "";
|
||||
[MaxLength(200)] public string? VendorName { get; set; }
|
||||
[MaxLength(50)] public string? CheckNumber { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
public class UpdateExpenseSnapshotRequest : CreateExpenseSnapshotRequest { }
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Expense;
|
||||
|
||||
public class MonthlyStatementDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int Year { get; set; }
|
||||
public int Month { get; set; }
|
||||
public decimal OpeningBalance { get; set; }
|
||||
public decimal TotalGiving { get; set; }
|
||||
public decimal TotalOtherIncome { get; set; }
|
||||
public decimal TotalExpenses { get; set; }
|
||||
public decimal CalculatedClosingBalance { get; set; }
|
||||
public decimal BankStatementBalance { get; set; }
|
||||
public decimal Difference { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public bool IsFinalized { get; set; }
|
||||
}
|
||||
|
||||
public class CreateMonthlyStatementRequest
|
||||
{
|
||||
[Range(2000, 2100)] public int Year { get; set; }
|
||||
[Range(1, 12)] public int Month { get; set; }
|
||||
public decimal OpeningBalance { get; set; }
|
||||
public decimal TotalOtherIncome { get; set; }
|
||||
public decimal BankStatementBalance { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
public class UpdateMonthlyStatementRequest
|
||||
{
|
||||
public decimal OpeningBalance { get; set; }
|
||||
public decimal TotalOtherIncome { get; set; }
|
||||
public decimal BankStatementBalance { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace ROLAC.API.DTOs.Finance;
|
||||
|
||||
/// <summary>All-time finance position for the dashboard balance card.</summary>
|
||||
public class FinanceSummaryDto
|
||||
{
|
||||
public decimal TotalIncome { get; set; } // all-time sum of Giving.Amount
|
||||
public decimal TotalExpenses { get; set; } // all-time Paid+Approved expenses
|
||||
public decimal Balance { get; set; } // TotalIncome - TotalExpenses
|
||||
}
|
||||
|
||||
/// <summary>Income vs expense totals for a date range (the income/expense pie).</summary>
|
||||
public class IncomeExpenseDto
|
||||
{
|
||||
public decimal Income { get; set; } // Givings in [from,to]
|
||||
public decimal Expense { get; set; } // Paid+Approved expenses in [from,to]
|
||||
}
|
||||
|
||||
/// <summary>One slice of the expense drill-down pie. Id is a ministry / group / sub-category id by level.</summary>
|
||||
public class BreakdownSliceDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name_en { get; set; } = "";
|
||||
public string? Name_zh { get; set; }
|
||||
public decimal Amount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
namespace ROLAC.API.DTOs.Finance;
|
||||
|
||||
public class Form1099BoxDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string BoxCode { get; set; } = "";
|
||||
public string Name_en { get; set; } = "";
|
||||
public string? Name_zh { get; set; }
|
||||
public string FormType { get; set; } = "";
|
||||
public int SortOrder { get; set; }
|
||||
}
|
||||
|
||||
public class Form1099RecipientRowDto
|
||||
{
|
||||
public int PayeeId { get; set; }
|
||||
public string LegalName { get; set; } = "";
|
||||
public string? TinLast4 { get; set; }
|
||||
public string W9Status { get; set; } = "";
|
||||
public decimal NecTotal { get; set; }
|
||||
public decimal RentsTotal { get; set; }
|
||||
public decimal GrandTotal { get; set; }
|
||||
public bool MeetsThreshold { get; set; }
|
||||
public bool W9Missing { get; set; }
|
||||
}
|
||||
|
||||
public class Form1099SummaryDto
|
||||
{
|
||||
public int TaxYear { get; set; }
|
||||
public List<Form1099RecipientRowDto> Rows { get; set; } = [];
|
||||
public decimal TotalReportable { get; set; }
|
||||
public int RecipientsAtThreshold { get; set; }
|
||||
public int RecipientsMissingW9 { get; set; }
|
||||
}
|
||||
|
||||
public class Form1099PaymentDto
|
||||
{
|
||||
public string PaidDate { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
public string CategoryName { get; set; } = "";
|
||||
public string BoxCode { get; set; } = "";
|
||||
public decimal Amount { get; set; }
|
||||
}
|
||||
|
||||
public class Form1099RecipientDetailDto
|
||||
{
|
||||
public int PayeeId { get; set; }
|
||||
public string LegalName { get; set; } = "";
|
||||
public string? TinLast4 { get; set; }
|
||||
public string W9Status { get; set; } = "";
|
||||
public int TaxYear { get; set; }
|
||||
public List<Form1099PaymentDto> Payments { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace ROLAC.API.DTOs.Finance;
|
||||
|
||||
/// <summary>One Part IX row: a 990 line split across the three functional columns.</summary>
|
||||
public class FunctionalExpenseRowDto
|
||||
{
|
||||
public string LineCode { get; set; } = "";
|
||||
public string Name_en { get; set; } = "";
|
||||
public string? Name_zh { get; set; }
|
||||
public decimal Program { get; set; }
|
||||
public decimal ManagementGeneral { get; set; }
|
||||
public decimal Fundraising { get; set; }
|
||||
public decimal Total { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The full Part IX Statement of Functional Expenses for a date range.</summary>
|
||||
public class FunctionalExpenseStatementDto
|
||||
{
|
||||
public List<FunctionalExpenseRowDto> Rows { get; set; } = [];
|
||||
public decimal ProgramTotal { get; set; }
|
||||
public decimal ManagementGeneralTotal { get; set; }
|
||||
public decimal FundraisingTotal { get; set; }
|
||||
public decimal GrandTotal { get; set; }
|
||||
/// <summary>Expenses with no explicit 990 mapping (counted under line 24). Prompts mapping cleanup.</summary>
|
||||
public int UnmappedExpenseCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A single IRS Form 990 expense line from the catalog (used to populate mapping dropdowns).</summary>
|
||||
public class Form990ExpenseLineDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string LineCode { get; set; } = "";
|
||||
public string Name_en { get; set; } = "";
|
||||
public string? Name_zh { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
// Body of POST /api/offering-entry/lines — one offering line plus the date of the
|
||||
// session it belongs to (find-or-create that day's session, append the line).
|
||||
public class AppendOfferingLineRequest
|
||||
{
|
||||
[Required] public DateOnly Date { get; set; }
|
||||
[Required] public OfferingGivingLineRequest Line { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
public class CreateGivingCategoryRequest
|
||||
{
|
||||
[Required, MaxLength(200)] public string Name_en { get; set; } = "";
|
||||
[MaxLength(200)] public string? Name_zh { get; set; }
|
||||
[MaxLength(500)] public string? Description_en { get; set; }
|
||||
[MaxLength(500)] public string? Description_zh { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
public class CreateGivingRequest
|
||||
{
|
||||
public int? MemberId { get; set; }
|
||||
[Required] public int GivingCategoryId { get; set; }
|
||||
[Range(0.01, 9999999)] public decimal Amount { get; set; }
|
||||
[Required, MaxLength(20)] public string PaymentMethod { get; set; } = "Cash";
|
||||
[MaxLength(50)] public string? CheckNumber { get; set; }
|
||||
[MaxLength(100)] public string? ZelleReferenceCode { get; set; }
|
||||
[MaxLength(100)] public string? PayPalTransactionId { get; set; }
|
||||
public DateOnly GivingDate { get; set; }
|
||||
public bool IsAnonymous { get; set; }
|
||||
[MaxLength(500)] public string? Notes { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
public class CreateOfferingSessionRequest
|
||||
{
|
||||
[Required] public DateOnly SessionDate { get; set; }
|
||||
public decimal CashTotal { get; set; }
|
||||
public decimal CheckTotal { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
public List<OfferingGivingLineRequest> Givings { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
public class GivingCategoryDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name_en { get; set; } = "";
|
||||
public string? Name_zh { get; set; }
|
||||
public string? Description_en { get; set; }
|
||||
public string? Description_zh { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
public class GivingDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int? MemberId { get; set; }
|
||||
public string? MemberName { get; set; }
|
||||
public int GivingCategoryId { get; set; }
|
||||
public int? OfferingSessionId { get; set; }
|
||||
public decimal Amount { get; set; }
|
||||
public string PaymentMethod { get; set; } = "";
|
||||
public string? CheckNumber { get; set; }
|
||||
public string? ZelleReferenceCode { get; set; }
|
||||
public string? PayPalTransactionId { get; set; }
|
||||
public DateOnly GivingDate { get; set; }
|
||||
public bool IsAnonymous { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
public class GivingListItemDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int? MemberId { get; set; }
|
||||
public string? MemberName { get; set; }
|
||||
public int GivingCategoryId { get; set; }
|
||||
public string CategoryName { get; set; } = "";
|
||||
public decimal Amount { get; set; }
|
||||
public string PaymentMethod { get; set; } = "";
|
||||
public string GivingDate { get; set; } = ""; // ISO yyyy-MM-dd
|
||||
public bool IsAnonymous { get; set; }
|
||||
public int? OfferingSessionId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
// Minimal member fields exposed to the anonymous mobile offering-entry page —
|
||||
// just enough for the giver typeahead to render a display name (matches the
|
||||
// Angular memberDisplayName helper: NickName ?? FirstName_en, plus LastName_en).
|
||||
public class MemberTypeaheadDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string? NickName { get; set; }
|
||||
public string FirstName_en { get; set; } = "";
|
||||
public string LastName_en { get; set; } = "";
|
||||
public string? Entity { get; set; } // company / business name (公司行號), if any
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
// One-shot payload that seeds the mobile offering-entry page: the active giving
|
||||
// categories for the Type dropdown and the current state of today's session.
|
||||
public class OfferingEntryBootstrapDto
|
||||
{
|
||||
public string SessionDate { get; set; } = ""; // yyyy-MM-dd
|
||||
public List<GivingCategoryDto> Categories { get; set; } = [];
|
||||
public OfferingEntrySummaryDto Summary { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
// Returned from POST /api/offering-entry/lines and broadcast over the
|
||||
// OfferingEntryHub: the line just added plus the session's new running totals,
|
||||
// so every connected client (other phones + the desktop page) can update live.
|
||||
public class OfferingEntryLineAddedDto
|
||||
{
|
||||
public int SessionId { get; set; }
|
||||
public string SessionDate { get; set; } = ""; // yyyy-MM-dd
|
||||
public string Status { get; set; } = "";
|
||||
public decimal SystemTotal { get; set; }
|
||||
public int LineCount { get; set; }
|
||||
public OfferingGivingLineDto Line { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
// A day's offering session as the mobile page sees it: the running total/line
|
||||
// count plus the lines already recorded. SessionId is null when no session
|
||||
// exists for the date yet (nothing entered today).
|
||||
public class OfferingEntrySummaryDto
|
||||
{
|
||||
public int? SessionId { get; set; }
|
||||
public string SessionDate { get; set; } = ""; // yyyy-MM-dd
|
||||
public string? Status { get; set; } // null when no session yet
|
||||
public decimal SystemTotal { get; set; }
|
||||
public int LineCount { get; set; }
|
||||
public bool HasProof { get; set; } // a merged paper-proof PDF is attached to this session
|
||||
public List<OfferingGivingLineDto> Lines { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace ROLAC.API.DTOs.Giving;
|
||||
|
||||
public class OfferingGivingLineDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int? MemberId { get; set; }
|
||||
public string? MemberName { get; set; }
|
||||
public int GivingCategoryId { get; set; }
|
||||
public string CategoryName { get; set; } = "";
|
||||
public decimal Amount { get; set; }
|
||||
public string PaymentMethod { get; set; } = "";
|
||||
public string? CheckNumber { get; set; }
|
||||
public string? ZelleReferenceCode { get; set; }
|
||||
public string? PayPalTransactionId { get; set; }
|
||||
public bool IsAnonymous { get; set; }
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user