Compare commits
73 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -169,6 +169,48 @@ public class AuthServiceTests
|
|||||||
um.Verify(m => m.UpdateAsync(It.Is<AppUser>(u => u.LastLoginAt != null)), Times.Once);
|
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
|
// Refresh tests
|
||||||
// -----------------------------------------------------------------------
|
// -----------------------------------------------------------------------
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -65,6 +65,8 @@ public class DisbursementServiceTests
|
|||||||
var db = BuildDb(userId);
|
var db = BuildDb(userId);
|
||||||
db.ChurchProfiles.Add(new ChurchProfile { Id = 1, Name = "ROLAC", NextCheckNumber = 1001 });
|
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.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();
|
db.SaveChanges();
|
||||||
var fs = new FakeStorage();
|
var fs = new FakeStorage();
|
||||||
return (SvcAs(db, fs, userId), db, fs);
|
return (SvcAs(db, fs, userId), db, fs);
|
||||||
@@ -73,8 +75,9 @@ public class DisbursementServiceTests
|
|||||||
private static Expense Approved(string type, decimal amount, int? memberId = null, string? vendor = null) => new()
|
private static Expense Approved(string type, decimal amount, int? memberId = null, string? vendor = null) => new()
|
||||||
{
|
{
|
||||||
Type = type, Status = "Approved", Amount = amount, Description = $"{type} {amount}",
|
Type = type, Status = "Approved", Amount = amount, Description = $"{type} {amount}",
|
||||||
MinistryId = 1, CategoryGroupId = 1, SubCategoryId = 1, ExpenseDate = new DateOnly(2026, 6, 1),
|
MinistryId = 1, ExpenseDate = new DateOnly(2026, 6, 1),
|
||||||
MemberId = memberId, VendorName = vendor,
|
MemberId = memberId, VendorName = vendor,
|
||||||
|
Lines = { new ExpenseLine { CategoryGroupId = 1, SubCategoryId = 1, Amount = amount } },
|
||||||
};
|
};
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -97,6 +100,28 @@ public class DisbursementServiceTests
|
|||||||
Assert.Equal("1 Main St", member.Address);
|
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]
|
[Fact]
|
||||||
public async Task Issue_CreatesOneCheckPerPayee_MarksPaid_SequentialNumbers()
|
public async Task Issue_CreatesOneCheckPerPayee_MarksPaid_SequentialNumbers()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -58,4 +58,23 @@ public class ExpenseCategoryServiceTests
|
|||||||
await Assert.ThrowsAsync<KeyNotFoundException>(() =>
|
await Assert.ThrowsAsync<KeyNotFoundException>(() =>
|
||||||
svc.UpdateGroupAsync(999, new UpdateExpenseGroupRequest { Name_en = "X" }));
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,11 @@ using ROLAC.API.Data;
|
|||||||
using ROLAC.API.Data.Interceptors;
|
using ROLAC.API.Data.Interceptors;
|
||||||
using ROLAC.API.DTOs.Expense;
|
using ROLAC.API.DTOs.Expense;
|
||||||
using ROLAC.API.Entities;
|
using ROLAC.API.Entities;
|
||||||
|
using ROLAC.API.Entities.Logging;
|
||||||
using ROLAC.API.Services;
|
using ROLAC.API.Services;
|
||||||
|
using ROLAC.API.Services.Logging;
|
||||||
using ROLAC.API.Services.Storage;
|
using ROLAC.API.Services.Storage;
|
||||||
|
using ROLAC.API.Tests.TestSupport;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace ROLAC.API.Tests.Services;
|
namespace ROLAC.API.Tests.Services;
|
||||||
@@ -55,6 +58,14 @@ public class ExpenseServiceTests
|
|||||||
return new ExpenseService(db, http.Object, fs, ROLAC.API.Tests.TestSupport.NullAuditLogger.Instance);
|
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),
|
// Builds a service whose principal carries ONLY the "sub" claim (no NameIdentifier),
|
||||||
// mirroring the real JWT (NameClaimType="sub", MapInboundClaims=false).
|
// mirroring the real JWT (NameClaimType="sub", MapInboundClaims=false).
|
||||||
private static ExpenseService SvcWithSubClaim(AppDbContext db, FakeStorage fs, string userId)
|
private static ExpenseService SvcWithSubClaim(AppDbContext db, FakeStorage fs, string userId)
|
||||||
@@ -67,14 +78,20 @@ public class ExpenseServiceTests
|
|||||||
|
|
||||||
private static CreateExpenseRequest Reimb() => new()
|
private static CreateExpenseRequest Reimb() => new()
|
||||||
{
|
{
|
||||||
Type = "StaffReimbursement", MinistryId = 1, CategoryGroupId = 1, SubCategoryId = 1,
|
Type = "StaffReimbursement", MinistryId = 1,
|
||||||
Amount = 45.50m, Description = "Batteries", ExpenseDate = new DateOnly(2026, 5, 28),
|
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()
|
private static UpdateExpenseRequest CloneToUpdate(CreateExpenseRequest r) => new()
|
||||||
{
|
{
|
||||||
Type = r.Type, MinistryId = r.MinistryId, CategoryGroupId = r.CategoryGroupId,
|
Type = r.Type, MinistryId = r.MinistryId,
|
||||||
SubCategoryId = r.SubCategoryId, Amount = r.Amount, Description = r.Description,
|
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,
|
VendorName = r.VendorName, MemberId = r.MemberId, CheckNumber = r.CheckNumber,
|
||||||
ExpenseDate = r.ExpenseDate, Notes = r.Notes,
|
ExpenseDate = r.ExpenseDate, Notes = r.Notes,
|
||||||
};
|
};
|
||||||
@@ -207,7 +224,7 @@ public class ExpenseServiceTests
|
|||||||
Assert.Equal("PendingApproval", (await db.Expenses.FindAsync(id))!.Status);
|
Assert.Equal("PendingApproval", (await db.Expenses.FindAsync(id))!.Status);
|
||||||
|
|
||||||
var edit = CloneToUpdate(Reimb());
|
var edit = CloneToUpdate(Reimb());
|
||||||
edit.Amount = 99.99m;
|
edit.Lines[0].Amount = 99.99m;
|
||||||
await svc.UpdateAsync(id, edit, isFinance: false);
|
await svc.UpdateAsync(id, edit, isFinance: false);
|
||||||
|
|
||||||
var e = await db.Expenses.FindAsync(id);
|
var e = await db.Expenses.FindAsync(id);
|
||||||
@@ -248,6 +265,84 @@ public class ExpenseServiceTests
|
|||||||
Assert.Null(await db.Expenses.FirstOrDefaultAsync(e => e.Id == id));
|
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]
|
[Fact]
|
||||||
public async Task Receipt_SaveThenOpen_RoundTrips()
|
public async Task Receipt_SaveThenOpen_RoundTrips()
|
||||||
{
|
{
|
||||||
@@ -258,4 +353,93 @@ public class ExpenseServiceTests
|
|||||||
var got = await svc.OpenReceiptAsync(id, isFinance: true);
|
var got = await svc.OpenReceiptAsync(id, isFinance: true);
|
||||||
Assert.NotNull(got);
|
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,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,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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Http;
|
|||||||
using Moq;
|
using Moq;
|
||||||
using ROLAC.API.Data;
|
using ROLAC.API.Data;
|
||||||
using ROLAC.API.Data.Interceptors;
|
using ROLAC.API.Data.Interceptors;
|
||||||
|
using ROLAC.API.DTOs.Ministry;
|
||||||
using ROLAC.API.Entities;
|
using ROLAC.API.Entities;
|
||||||
using ROLAC.API.Services;
|
using ROLAC.API.Services;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
@@ -41,4 +42,19 @@ public class MinistryServiceTests
|
|||||||
Assert.Equal("A", active[0].Name_en);
|
Assert.Equal("A", active[0].Name_en);
|
||||||
Assert.Equal(3, all.Count);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,8 +42,8 @@ public class MonthlyStatementServiceTests
|
|||||||
db.ExpenseSubCategories.Add(new ExpenseSubCategory { Id = 1, GroupId = 1, Name_en = "Misc" });
|
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 = 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.Givings.Add(new Giving { GivingCategoryId = 1, Amount = 500m, PaymentMethod = "Cash", GivingDate = new DateOnly(2026, 6, 1) });
|
||||||
db.Expenses.Add(new Expense { MinistryId = 1, CategoryGroupId = 1, SubCategoryId = 1, Type = "VendorPayment", Status = "Paid", Amount = 300m, Description = "x", ExpenseDate = new DateOnly(2026, 5, 20) });
|
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, CategoryGroupId = 1, SubCategoryId = 1, Type = "StaffReimbursement", Status = "Approved", Amount = 999m, Description = "not paid", ExpenseDate = new DateOnly(2026, 5, 21) });
|
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();
|
await db.SaveChangesAsync();
|
||||||
var svc = Build(db);
|
var svc = Build(db);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using ROLAC.API.Services.Notifications;
|
using ROLAC.API.Services.Notifications;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
@@ -8,6 +7,14 @@ namespace ROLAC.API.Tests.Services.Notifications;
|
|||||||
|
|
||||||
public class LineMessageChannelTests
|
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.
|
// Captures the outgoing request and returns a canned response.
|
||||||
private sealed class CapturingHandler : HttpMessageHandler
|
private sealed class CapturingHandler : HttpMessageHandler
|
||||||
{
|
{
|
||||||
@@ -28,8 +35,7 @@ public class LineMessageChannelTests
|
|||||||
private static LineMessageChannel BuildChannel(CapturingHandler handler)
|
private static LineMessageChannel BuildChannel(CapturingHandler handler)
|
||||||
{
|
{
|
||||||
var http = new HttpClient(handler);
|
var http = new HttpClient(handler);
|
||||||
var options = Options.Create(new LineOptions { ChannelAccessToken = "tok", ChannelSecret = "sec" });
|
return new LineMessageChannel(http, new StubSettings());
|
||||||
return new LineMessageChannel(http, options);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -164,4 +164,27 @@ public class OfferingSessionServiceTests
|
|||||||
Assert.Equal("PP-456", line.PayPalTransactionId);
|
Assert.Equal("PP-456", line.PayPalTransactionId);
|
||||||
Assert.Equal("C-789", line.CheckNumber);
|
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,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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ public static class Modules
|
|||||||
public const string OfferingSessions = "OfferingSessions";
|
public const string OfferingSessions = "OfferingSessions";
|
||||||
public const string Ministries = "Ministries";
|
public const string Ministries = "Ministries";
|
||||||
public const string FinanceDashboard = "FinanceDashboard";
|
public const string FinanceDashboard = "FinanceDashboard";
|
||||||
|
public const string Form990Report = "Form990Report";
|
||||||
public const string MonthlyStatements = "MonthlyStatements";
|
public const string MonthlyStatements = "MonthlyStatements";
|
||||||
public const string ChurchProfile = "ChurchProfile";
|
public const string ChurchProfile = "ChurchProfile";
|
||||||
public const string Disbursements = "Disbursements";
|
public const string Disbursements = "Disbursements";
|
||||||
@@ -23,6 +24,7 @@ public static class Modules
|
|||||||
public const string Permissions = "Permissions";
|
public const string Permissions = "Permissions";
|
||||||
public const string SystemLogs = "SystemLogs";
|
public const string SystemLogs = "SystemLogs";
|
||||||
public const string AuditLogs = "AuditLogs";
|
public const string AuditLogs = "AuditLogs";
|
||||||
|
public const string Settings = "Settings";
|
||||||
|
|
||||||
/// <summary>All modules, in display order — drives the admin matrix UI.</summary>
|
/// <summary>All modules, in display order — drives the admin matrix UI.</summary>
|
||||||
public static readonly IReadOnlyList<string> All =
|
public static readonly IReadOnlyList<string> All =
|
||||||
@@ -36,6 +38,7 @@ public static class Modules
|
|||||||
OfferingSessions,
|
OfferingSessions,
|
||||||
Ministries,
|
Ministries,
|
||||||
FinanceDashboard,
|
FinanceDashboard,
|
||||||
|
Form990Report,
|
||||||
MonthlyStatements,
|
MonthlyStatements,
|
||||||
ChurchProfile,
|
ChurchProfile,
|
||||||
Disbursements,
|
Disbursements,
|
||||||
@@ -43,6 +46,7 @@ public static class Modules
|
|||||||
Permissions,
|
Permissions,
|
||||||
SystemLogs,
|
SystemLogs,
|
||||||
AuditLogs,
|
AuditLogs,
|
||||||
|
Settings,
|
||||||
];
|
];
|
||||||
|
|
||||||
public static bool IsValid(string module) => All.Contains(module);
|
public static bool IsValid(string module) => All.Contains(module);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization;
|
|||||||
using Microsoft.AspNetCore.Identity;
|
using Microsoft.AspNetCore.Identity;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using ROLAC.API.DTOs.Auth;
|
using ROLAC.API.DTOs.Auth;
|
||||||
|
using ROLAC.API.DTOs.Invitations;
|
||||||
using ROLAC.API.Entities;
|
using ROLAC.API.Entities;
|
||||||
using ROLAC.API.Services;
|
using ROLAC.API.Services;
|
||||||
|
|
||||||
@@ -16,13 +17,16 @@ public class AuthController : ControllerBase
|
|||||||
private const int CookieMaxAge = 30 * 24 * 60 * 60; // 30 days in seconds
|
private const int CookieMaxAge = 30 * 24 * 60 * 60; // 30 days in seconds
|
||||||
|
|
||||||
private readonly IAuthService _authService;
|
private readonly IAuthService _authService;
|
||||||
|
private readonly IInvitationService _invitations;
|
||||||
private readonly UserManager<AppUser> _userManager;
|
private readonly UserManager<AppUser> _userManager;
|
||||||
private readonly IWebHostEnvironment _env;
|
private readonly IWebHostEnvironment _env;
|
||||||
|
|
||||||
public AuthController(
|
public AuthController(
|
||||||
IAuthService authService, UserManager<AppUser> userManager, IWebHostEnvironment env)
|
IAuthService authService, IInvitationService invitations,
|
||||||
|
UserManager<AppUser> userManager, IWebHostEnvironment env)
|
||||||
{
|
{
|
||||||
_authService = authService;
|
_authService = authService;
|
||||||
|
_invitations = invitations;
|
||||||
_userManager = userManager;
|
_userManager = userManager;
|
||||||
_env = env;
|
_env = env;
|
||||||
}
|
}
|
||||||
@@ -186,6 +190,45 @@ public class AuthController : ControllerBase
|
|||||||
return NoContent();
|
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
|
// Private helpers
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
using ROLAC.API.Authorization;
|
using ROLAC.API.Authorization;
|
||||||
using ROLAC.API.DTOs.Expense;
|
using ROLAC.API.DTOs.Expense;
|
||||||
using ROLAC.API.Services;
|
using ROLAC.API.Services;
|
||||||
|
using ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
namespace ROLAC.API.Controllers;
|
namespace ROLAC.API.Controllers;
|
||||||
|
|
||||||
@@ -13,12 +14,30 @@ namespace ROLAC.API.Controllers;
|
|||||||
public class ExpenseCategoriesController : ControllerBase
|
public class ExpenseCategoriesController : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly IExpenseCategoryService _svc;
|
private readonly IExpenseCategoryService _svc;
|
||||||
public ExpenseCategoriesController(IExpenseCategoryService svc) => _svc = svc;
|
private readonly IExpenseCategoryAiServiceFactory _aiFactory;
|
||||||
|
public ExpenseCategoriesController(IExpenseCategoryService svc, IExpenseCategoryAiServiceFactory aiFactory)
|
||||||
|
{
|
||||||
|
_svc = svc;
|
||||||
|
_aiFactory = aiFactory;
|
||||||
|
}
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
public async Task<IActionResult> GetAll([FromQuery] bool includeInactive = false)
|
public async Task<IActionResult> GetAll([FromQuery] bool includeInactive = false)
|
||||||
=> Ok(await _svc.GetAllAsync(includeInactive));
|
=> 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")]
|
[HttpPost("groups")]
|
||||||
[HasPermission(Modules.ExpenseCategories, PermissionActions.Write)]
|
[HasPermission(Modules.ExpenseCategories, PermissionActions.Write)]
|
||||||
public async Task<IActionResult> CreateGroup([FromBody] CreateExpenseGroupRequest r)
|
public async Task<IActionResult> CreateGroup([FromBody] CreateExpenseGroupRequest r)
|
||||||
|
|||||||
@@ -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,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,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 }); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@ using System.Text;
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using ROLAC.API.DTOs.Notifications;
|
using ROLAC.API.DTOs.Notifications;
|
||||||
using ROLAC.API.Services.Notifications;
|
using ROLAC.API.Services.Notifications;
|
||||||
|
|
||||||
@@ -22,14 +21,14 @@ public sealed class LineWebhookController : ControllerBase
|
|||||||
|
|
||||||
private readonly ILineNotificationService _line;
|
private readonly ILineNotificationService _line;
|
||||||
private readonly IMessageChannel _channel;
|
private readonly IMessageChannel _channel;
|
||||||
private readonly LineOptions _options;
|
private readonly INotificationSettingsService _settings;
|
||||||
|
|
||||||
public LineWebhookController(
|
public LineWebhookController(
|
||||||
ILineNotificationService line, IMessageChannel channel, IOptions<LineOptions> options)
|
ILineNotificationService line, IMessageChannel channel, INotificationSettingsService settings)
|
||||||
{
|
{
|
||||||
_line = line;
|
_line = line;
|
||||||
_channel = channel;
|
_channel = channel;
|
||||||
_options = options.Value;
|
_settings = settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("webhook")]
|
[HttpPost("webhook")]
|
||||||
@@ -40,7 +39,7 @@ public sealed class LineWebhookController : ControllerBase
|
|||||||
var rawBody = await reader.ReadToEndAsync(ct);
|
var rawBody = await reader.ReadToEndAsync(ct);
|
||||||
var signature = Request.Headers["X-Line-Signature"].FirstOrDefault();
|
var signature = Request.Headers["X-Line-Signature"].FirstOrDefault();
|
||||||
|
|
||||||
if (!LineSignature.IsValid(_options.ChannelSecret, Encoding.UTF8.GetBytes(rawBody), signature))
|
if (!LineSignature.IsValid(_settings.GetLine().ChannelSecret, Encoding.UTF8.GetBytes(rawBody), signature))
|
||||||
return BadRequest();
|
return BadRequest();
|
||||||
|
|
||||||
var payload = JsonSerializer.Deserialize<LineWebhookPayload>(rawBody, JsonOpts);
|
var payload = JsonSerializer.Deserialize<LineWebhookPayload>(rawBody, JsonOpts);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using ROLAC.API.DTOs.MealAttendance;
|
||||||
using ROLAC.API.Services;
|
using ROLAC.API.Services;
|
||||||
|
|
||||||
namespace ROLAC.API.Controllers;
|
namespace ROLAC.API.Controllers;
|
||||||
@@ -23,4 +24,10 @@ public class MealAttendanceController : ControllerBase
|
|||||||
[Authorize]
|
[Authorize]
|
||||||
public async Task<IActionResult> GetRange([FromQuery] DateOnly from, [FromQuery] DateOnly to)
|
public async Task<IActionResult> GetRange([FromQuery] DateOnly from, [FromQuery] DateOnly to)
|
||||||
=> Ok(await _svc.GetRangeAsync(from, 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));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using ROLAC.API.Authorization;
|
||||||
|
using ROLAC.API.DTOs.Ministry;
|
||||||
using ROLAC.API.Services;
|
using ROLAC.API.Services;
|
||||||
|
|
||||||
namespace ROLAC.API.Controllers;
|
namespace ROLAC.API.Controllers;
|
||||||
@@ -13,6 +15,31 @@ public class MinistriesController : ControllerBase
|
|||||||
public MinistriesController(IMinistryService svc) => _svc = svc;
|
public MinistriesController(IMinistryService svc) => _svc = svc;
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
|
[HasPermission(Modules.Ministries, PermissionActions.Read)]
|
||||||
public async Task<IActionResult> GetAll([FromQuery] bool includeInactive = false)
|
public async Task<IActionResult> GetAll([FromQuery] bool includeInactive = false)
|
||||||
=> Ok(await _svc.GetAllAsync(includeInactive));
|
=> 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(); }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ public class OfferingEntryController : ControllerBase
|
|||||||
NickName = request.NickName,
|
NickName = request.NickName,
|
||||||
FirstName_zh = request.FirstName_zh,
|
FirstName_zh = request.FirstName_zh,
|
||||||
LastName_zh = request.LastName_zh,
|
LastName_zh = request.LastName_zh,
|
||||||
|
Entity = request.Entity,
|
||||||
PhoneCell = request.PhoneCell,
|
PhoneCell = request.PhoneCell,
|
||||||
Status = "Visitor",
|
Status = "Visitor",
|
||||||
Country = "USA",
|
Country = "USA",
|
||||||
@@ -73,6 +74,7 @@ public class OfferingEntryController : ControllerBase
|
|||||||
{
|
{
|
||||||
Id = id, NickName = request.NickName,
|
Id = id, NickName = request.NickName,
|
||||||
FirstName_en = request.FirstName_en, LastName_en = request.LastName_en,
|
FirstName_en = request.FirstName_en, LastName_en = request.LastName_en,
|
||||||
|
Entity = request.Entity,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,4 +25,22 @@ public class UserInfo
|
|||||||
/// Lets the SPA hide nav/buttons. Authoritative enforcement is server-side.
|
/// Lets the SPA hide nav/buttons. Authoritative enforcement is server-side.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Dictionary<string, ModuleActions> Permissions { get; set; } = [];
|
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; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ public class ChurchProfileDto
|
|||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
public string Name { 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? Address { get; set; }
|
||||||
public string? City { get; set; }
|
public string? City { get; set; }
|
||||||
public string? State { get; set; }
|
public string? State { get; set; }
|
||||||
@@ -13,11 +17,20 @@ public class ChurchProfileDto
|
|||||||
public string? BankAccountNumber { get; set; }
|
public string? BankAccountNumber { get; set; }
|
||||||
public string? BankRoutingNumber { get; set; }
|
public string? BankRoutingNumber { get; set; }
|
||||||
public int NextCheckNumber { 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
|
public class UpdateChurchProfileRequest
|
||||||
{
|
{
|
||||||
[Required, MaxLength(200)] public string Name { get; set; } = "";
|
[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(500)] public string? Address { get; set; }
|
||||||
[MaxLength(100)] public string? City { get; set; }
|
[MaxLength(100)] public string? City { get; set; }
|
||||||
[MaxLength(50)] public string? State { get; set; }
|
[MaxLength(50)] public string? State { get; set; }
|
||||||
@@ -26,4 +39,9 @@ public class UpdateChurchProfileRequest
|
|||||||
[MaxLength(50)] public string? BankAccountNumber { get; set; }
|
[MaxLength(50)] public string? BankAccountNumber { get; set; }
|
||||||
[MaxLength(50)] public string? BankRoutingNumber { get; set; }
|
[MaxLength(50)] public string? BankRoutingNumber { get; set; }
|
||||||
[Range(1, int.MaxValue)] public int NextCheckNumber { 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,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; }
|
||||||
|
}
|
||||||
@@ -9,6 +9,8 @@ public class ExpenseSubCategoryDto
|
|||||||
public string? Name_zh { get; set; }
|
public string? Name_zh { get; set; }
|
||||||
public int SortOrder { get; set; }
|
public int SortOrder { get; set; }
|
||||||
public bool IsActive { get; set; }
|
public bool IsActive { get; set; }
|
||||||
|
public int? Form990LineId { get; set; }
|
||||||
|
public string? Form990LineCode { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ExpenseCategoryGroupDto
|
public class ExpenseCategoryGroupDto
|
||||||
@@ -18,6 +20,8 @@ public class ExpenseCategoryGroupDto
|
|||||||
public string? Name_zh { get; set; }
|
public string? Name_zh { get; set; }
|
||||||
public int SortOrder { get; set; }
|
public int SortOrder { get; set; }
|
||||||
public bool IsActive { get; set; }
|
public bool IsActive { get; set; }
|
||||||
|
public int? Form990LineId { get; set; }
|
||||||
|
public string? Form990LineCode { get; set; }
|
||||||
public List<ExpenseSubCategoryDto> SubCategories { get; set; } = [];
|
public List<ExpenseSubCategoryDto> SubCategories { get; set; } = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,6 +30,7 @@ public class CreateExpenseGroupRequest
|
|||||||
[Required, MaxLength(200)] public string Name_en { get; set; } = "";
|
[Required, MaxLength(200)] public string Name_en { get; set; } = "";
|
||||||
[MaxLength(200)] public string? Name_zh { get; set; }
|
[MaxLength(200)] public string? Name_zh { get; set; }
|
||||||
public int SortOrder { get; set; }
|
public int SortOrder { get; set; }
|
||||||
|
public int? Form990LineId { get; set; }
|
||||||
}
|
}
|
||||||
public class UpdateExpenseGroupRequest : CreateExpenseGroupRequest
|
public class UpdateExpenseGroupRequest : CreateExpenseGroupRequest
|
||||||
{
|
{
|
||||||
@@ -38,6 +43,7 @@ public class CreateExpenseSubCategoryRequest
|
|||||||
[Required, MaxLength(200)] public string Name_en { get; set; } = "";
|
[Required, MaxLength(200)] public string Name_en { get; set; } = "";
|
||||||
[MaxLength(200)] public string? Name_zh { get; set; }
|
[MaxLength(200)] public string? Name_zh { get; set; }
|
||||||
public int SortOrder { get; set; }
|
public int SortOrder { get; set; }
|
||||||
|
public int? Form990LineId { get; set; }
|
||||||
}
|
}
|
||||||
public class UpdateExpenseSubCategoryRequest : CreateExpenseSubCategoryRequest
|
public class UpdateExpenseSubCategoryRequest : CreateExpenseSubCategoryRequest
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,44 +1,65 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
namespace ROLAC.API.DTOs.Expense;
|
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 class ExpenseListItemDto
|
||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
public string Type { get; set; } = "";
|
public string Type { get; set; } = "";
|
||||||
public string Status { get; set; } = "";
|
public string Status { get; set; } = "";
|
||||||
public decimal Amount { get; set; }
|
public decimal Amount { get; set; } // header total = sum of line amounts
|
||||||
public string Description { get; set; } = "";
|
public string Description { get; set; } = "";
|
||||||
public int MinistryId { get; set; }
|
public int MinistryId { get; set; }
|
||||||
public string MinistryName { get; set; } = "";
|
public string MinistryName { get; set; } = "";
|
||||||
public int CategoryGroupId { get; set; }
|
public int LineCount { get; set; }
|
||||||
public string CategoryGroupName { get; set; } = "";
|
public string PrimaryCategoryName { get; set; } = ""; // first line's category (list hint; full breakdown via detail)
|
||||||
public int SubCategoryId { get; set; }
|
|
||||||
public string SubCategoryName { get; set; } = "";
|
|
||||||
public string? VendorName { get; set; }
|
public string? VendorName { get; set; }
|
||||||
public int? MemberId { get; set; }
|
public int? MemberId { get; set; }
|
||||||
public string? MemberName { 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 string ExpenseDate { get; set; } = ""; // yyyy-MM-dd
|
||||||
public bool HasReceipt { get; set; }
|
public bool HasReceipt { get; set; }
|
||||||
public string? CheckNumber { 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 class ExpenseDto : ExpenseListItemDto
|
public class ExpenseDto : ExpenseListItemDto
|
||||||
{
|
{
|
||||||
public string? Notes { get; set; }
|
public string? Notes { get; set; }
|
||||||
public string? ReviewNotes { get; set; }
|
|
||||||
public string? SubmittedBy { get; set; }
|
public string? SubmittedBy { get; set; }
|
||||||
public DateTimeOffset? SubmittedAt { get; set; }
|
public DateTimeOffset? SubmittedAt { get; set; }
|
||||||
public DateTimeOffset? ReviewedAt { get; set; }
|
|
||||||
public DateTimeOffset? PaidAt { 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
|
public class CreateExpenseRequest
|
||||||
{
|
{
|
||||||
[Required] public string Type { get; set; } = "StaffReimbursement"; // VendorPayment|StaffReimbursement
|
[Required] public string Type { get; set; } = "StaffReimbursement"; // VendorPayment|StaffReimbursement
|
||||||
[Required] public int MinistryId { get; set; }
|
[Required] public int MinistryId { get; set; }
|
||||||
[Required] public int CategoryGroupId { get; set; }
|
[Required, MinLength(1)] public List<ExpenseLineInput> Lines { get; set; } = new();
|
||||||
[Required] public int SubCategoryId { get; set; }
|
|
||||||
[Range(0.01, 9_999_999)] public decimal Amount { get; set; }
|
|
||||||
[Required, MaxLength(500)] public string Description { get; set; } = "";
|
[Required, MaxLength(500)] public string Description { get; set; } = "";
|
||||||
[MaxLength(200)] public string? VendorName { get; set; }
|
[MaxLength(200)] public string? VendorName { get; set; }
|
||||||
public int? MemberId { get; set; } // ignored for self-service (server uses caller)
|
public int? MemberId { get; set; } // ignored for self-service (server uses caller)
|
||||||
|
|||||||
@@ -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 @@
|
|||||||
|
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; }
|
||||||
|
}
|
||||||
@@ -9,4 +9,5 @@ public class MemberTypeaheadDto
|
|||||||
public string? NickName { get; set; }
|
public string? NickName { get; set; }
|
||||||
public string FirstName_en { get; set; } = "";
|
public string FirstName_en { get; set; } = "";
|
||||||
public string LastName_en { get; set; } = "";
|
public string LastName_en { get; set; } = "";
|
||||||
|
public string? Entity { get; set; } // company / business name (公司行號), if any
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,4 +11,5 @@ public class OfferingSessionListItemDto
|
|||||||
public decimal Difference { get; set; }
|
public decimal Difference { get; set; }
|
||||||
public int LineCount { get; set; }
|
public int LineCount { get; set; }
|
||||||
public bool HasProof { get; set; }
|
public bool HasProof { get; set; }
|
||||||
|
public int? SundayAttendanceCount { get; set; } // null = no attendance recorded for the date
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,5 +11,6 @@ public class QuickAddMemberRequest
|
|||||||
[MaxLength(100)] public string? NickName { get; set; }
|
[MaxLength(100)] public string? NickName { get; set; }
|
||||||
[MaxLength(100)] public string? FirstName_zh { get; set; }
|
[MaxLength(100)] public string? FirstName_zh { get; set; }
|
||||||
[MaxLength(100)] public string? LastName_zh { get; set; }
|
[MaxLength(100)] public string? LastName_zh { get; set; }
|
||||||
|
[MaxLength(200)] public string? Entity { get; set; }
|
||||||
[MaxLength(30)] public string? PhoneCell { get; set; }
|
[MaxLength(30)] public string? PhoneCell { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace ROLAC.API.DTOs.Invitations;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Admin request to generate a first-login invitation link for a member. If the member has no
|
||||||
|
/// account yet, one is auto-created (no password) using <see cref="Email"/> or the member's email.
|
||||||
|
/// </summary>
|
||||||
|
public class CreateInvitationRequest
|
||||||
|
{
|
||||||
|
[Required]
|
||||||
|
public int MemberId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Optional override for the login email when the member has none on file.</summary>
|
||||||
|
public string? Email { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Roles to assign when an account is created. Defaults to ["member"].</summary>
|
||||||
|
public List<string>? Roles { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Result of generating an invitation — the raw token is returned ONCE.</summary>
|
||||||
|
public class CreateInvitationResult
|
||||||
|
{
|
||||||
|
public string Token { get; set; } = null!;
|
||||||
|
public DateTime ExpiresAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Admin request to e-mail an already-generated invitation link to the member.</summary>
|
||||||
|
public class SendInvitationRequest
|
||||||
|
{
|
||||||
|
[Required]
|
||||||
|
public int MemberId { get; set; }
|
||||||
|
|
||||||
|
[Required]
|
||||||
|
public string Link { get; set; } = null!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Public result describing whether an invitation token can still be used.</summary>
|
||||||
|
public class ValidateInvitationResult
|
||||||
|
{
|
||||||
|
public bool Valid { get; set; }
|
||||||
|
public bool Expired { get; set; }
|
||||||
|
public string? MemberName { get; set; }
|
||||||
|
public string? Email { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Public request to consume an invitation and set the account password.</summary>
|
||||||
|
public class AcceptInvitationRequest
|
||||||
|
{
|
||||||
|
[Required]
|
||||||
|
public string Token { get; set; } = null!;
|
||||||
|
|
||||||
|
[Required]
|
||||||
|
[StringLength(128, MinimumLength = 8)]
|
||||||
|
public string NewPassword { get; set; } = null!;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace ROLAC.API.DTOs.MealAttendance;
|
||||||
|
|
||||||
|
/// <summary>Absolute head-counts to write for one Sunday, from the back-office editor.</summary>
|
||||||
|
public class SetAttendanceRequest
|
||||||
|
{
|
||||||
|
public int Adult { get; set; }
|
||||||
|
public int Youth { get; set; }
|
||||||
|
public int Kid { get; set; }
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ public class CreateMemberRequest
|
|||||||
[MaxLength(100)] public string? NickName { get; set; }
|
[MaxLength(100)] public string? NickName { get; set; }
|
||||||
[MaxLength(100)] public string? FirstName_zh { get; set; }
|
[MaxLength(100)] public string? FirstName_zh { get; set; }
|
||||||
[MaxLength(100)] public string? LastName_zh { get; set; }
|
[MaxLength(100)] public string? LastName_zh { get; set; }
|
||||||
|
[MaxLength(200)] public string? Entity { get; set; }
|
||||||
[MaxLength(10)] public string? Gender { get; set; }
|
[MaxLength(10)] public string? Gender { get; set; }
|
||||||
public DateOnly? DateOfBirth { get; set; }
|
public DateOnly? DateOfBirth { get; set; }
|
||||||
public DateOnly? BaptismDate { get; set; }
|
public DateOnly? BaptismDate { get; set; }
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ public class MemberListItemDto
|
|||||||
public string? NickName { get; set; }
|
public string? NickName { get; set; }
|
||||||
public string? FirstName_zh { get; set; }
|
public string? FirstName_zh { get; set; }
|
||||||
public string? LastName_zh { get; set; }
|
public string? LastName_zh { get; set; }
|
||||||
|
public string? Entity { get; set; }
|
||||||
public string Status { get; set; } = "";
|
public string Status { get; set; } = "";
|
||||||
public string? Email { get; set; }
|
public string? Email { get; set; }
|
||||||
public string? PhoneCell { get; set; }
|
public string? PhoneCell { get; set; }
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
namespace ROLAC.API.DTOs.Ministry;
|
||||||
|
|
||||||
|
public class CreateMinistryRequest
|
||||||
|
{
|
||||||
|
[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; }
|
||||||
|
[MaxLength(20)] public string? DefaultFunctionalClass { get; set; }
|
||||||
|
}
|
||||||
@@ -5,6 +5,9 @@ public class MinistryDto
|
|||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
public string Name_en { get; set; } = "";
|
public string Name_en { get; set; } = "";
|
||||||
public string? Name_zh { get; set; }
|
public string? Name_zh { get; set; }
|
||||||
|
public string? Description_en { get; set; }
|
||||||
|
public string? Description_zh { get; set; }
|
||||||
public int SortOrder { get; set; }
|
public int SortOrder { get; set; }
|
||||||
public bool IsActive { get; set; }
|
public bool IsActive { get; set; }
|
||||||
|
public string DefaultFunctionalClass { get; set; } = "Program";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
namespace ROLAC.API.DTOs.Ministry;
|
||||||
|
|
||||||
|
public class UpdateMinistryRequest
|
||||||
|
{
|
||||||
|
[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 bool IsActive { get; set; } = true;
|
||||||
|
public int SortOrder { get; set; }
|
||||||
|
[MaxLength(20)] public string? DefaultFunctionalClass { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
namespace ROLAC.API.DTOs.Settings;
|
||||||
|
|
||||||
|
// ── Site settings ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
public class SiteSettingDto
|
||||||
|
{
|
||||||
|
public string SiteTitle { get; set; } = "";
|
||||||
|
public string? SiteTitleZh { get; set; }
|
||||||
|
public string DefaultLanguage { get; set; } = "en";
|
||||||
|
public string TimeZone { get; set; } = "";
|
||||||
|
public string DateFormat { get; set; } = "";
|
||||||
|
public string Currency { get; set; } = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UpdateSiteSettingRequest
|
||||||
|
{
|
||||||
|
[Required, MaxLength(200)] public string SiteTitle { get; set; } = "";
|
||||||
|
[MaxLength(200)] public string? SiteTitleZh { get; set; }
|
||||||
|
[Required, MaxLength(10)] public string DefaultLanguage { get; set; } = "en";
|
||||||
|
[Required, MaxLength(100)] public string TimeZone { get; set; } = "";
|
||||||
|
[Required, MaxLength(50)] public string DateFormat { get; set; } = "";
|
||||||
|
[Required, MaxLength(10)] public string Currency { get; set; } = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Notification settings ──────────────────────────────────────────────────
|
||||||
|
// Secrets are never returned. The DTO exposes only whether each secret is configured; the UI
|
||||||
|
// shows a write-only field where a blank value on update means "keep the stored secret".
|
||||||
|
|
||||||
|
public class NotificationSettingDto
|
||||||
|
{
|
||||||
|
public bool EnableEmail { get; set; }
|
||||||
|
public string SmtpHost { get; set; } = "";
|
||||||
|
public int SmtpPort { get; set; }
|
||||||
|
public bool SmtpUseSsl { get; set; }
|
||||||
|
public string SmtpUser { get; set; } = "";
|
||||||
|
public string FromAddress { get; set; } = "";
|
||||||
|
public string FromName { get; set; } = "";
|
||||||
|
public bool HasSmtpPassword { get; set; }
|
||||||
|
|
||||||
|
public bool EnableLine { get; set; }
|
||||||
|
public bool HasLineChannelAccessToken { get; set; }
|
||||||
|
public bool HasLineChannelSecret { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Read-only webhook URL to register in the Line console (derived from the request).</summary>
|
||||||
|
public string WebhookUrl { get; set; } = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UpdateNotificationSettingRequest
|
||||||
|
{
|
||||||
|
public bool EnableEmail { get; set; }
|
||||||
|
[MaxLength(200)] public string SmtpHost { get; set; } = "";
|
||||||
|
[Range(0, 65535)] public int SmtpPort { get; set; } = 587;
|
||||||
|
public bool SmtpUseSsl { get; set; } = true;
|
||||||
|
[MaxLength(200)] public string SmtpUser { get; set; } = "";
|
||||||
|
[MaxLength(200)] public string? FromAddress { get; set; }
|
||||||
|
[MaxLength(200)] public string? FromName { get; set; }
|
||||||
|
/// <summary>Blank = keep the stored password unchanged.</summary>
|
||||||
|
[MaxLength(500)] public string? SmtpPassword { get; set; }
|
||||||
|
|
||||||
|
public bool EnableLine { get; set; }
|
||||||
|
/// <summary>Blank = keep the stored token unchanged.</summary>
|
||||||
|
[MaxLength(500)] public string? LineChannelAccessToken { get; set; }
|
||||||
|
/// <summary>Blank = keep the stored secret unchanged.</summary>
|
||||||
|
[MaxLength(200)] public string? LineChannelSecret { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test-send requests ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
public class TestEmailRequest
|
||||||
|
{
|
||||||
|
/// <summary>Optional override; defaults to the current user's email when omitted.</summary>
|
||||||
|
[MaxLength(200), EmailAddress] public string? ToAddress { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class TestLineRequest
|
||||||
|
{
|
||||||
|
public int? MemberId { get; set; }
|
||||||
|
public int? GroupId { get; set; }
|
||||||
|
}
|
||||||
@@ -10,7 +10,8 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
{
|
{
|
||||||
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
|
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
|
||||||
|
|
||||||
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
|
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
|
||||||
|
public DbSet<UserInvitation> UserInvitations => Set<UserInvitation>();
|
||||||
public DbSet<Member> Members => Set<Member>();
|
public DbSet<Member> Members => Set<Member>();
|
||||||
public DbSet<FamilyUnit> FamilyUnits => Set<FamilyUnit>();
|
public DbSet<FamilyUnit> FamilyUnits => Set<FamilyUnit>();
|
||||||
public DbSet<GivingCategory> GivingCategories => Set<GivingCategory>();
|
public DbSet<GivingCategory> GivingCategories => Set<GivingCategory>();
|
||||||
@@ -19,7 +20,11 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
public DbSet<Ministry> Ministries => Set<Ministry>();
|
public DbSet<Ministry> Ministries => Set<Ministry>();
|
||||||
public DbSet<ExpenseCategoryGroup> ExpenseCategoryGroups => Set<ExpenseCategoryGroup>();
|
public DbSet<ExpenseCategoryGroup> ExpenseCategoryGroups => Set<ExpenseCategoryGroup>();
|
||||||
public DbSet<ExpenseSubCategory> ExpenseSubCategories => Set<ExpenseSubCategory>();
|
public DbSet<ExpenseSubCategory> ExpenseSubCategories => Set<ExpenseSubCategory>();
|
||||||
|
public DbSet<Form990ExpenseLine> Form990ExpenseLines => Set<Form990ExpenseLine>();
|
||||||
public DbSet<Expense> Expenses => Set<Expense>();
|
public DbSet<Expense> Expenses => Set<Expense>();
|
||||||
|
public DbSet<ExpenseLine> ExpenseLines => Set<ExpenseLine>();
|
||||||
|
public DbSet<ExpenseSnapshot> ExpenseSnapshots => Set<ExpenseSnapshot>();
|
||||||
|
public DbSet<ExpenseSnapshotLine> ExpenseSnapshotLines => Set<ExpenseSnapshotLine>();
|
||||||
public DbSet<MonthlyStatement> MonthlyStatements => Set<MonthlyStatement>();
|
public DbSet<MonthlyStatement> MonthlyStatements => Set<MonthlyStatement>();
|
||||||
public DbSet<ChurchProfile> ChurchProfiles => Set<ChurchProfile>();
|
public DbSet<ChurchProfile> ChurchProfiles => Set<ChurchProfile>();
|
||||||
public DbSet<Check> Checks => Set<Check>();
|
public DbSet<Check> Checks => Set<Check>();
|
||||||
@@ -32,6 +37,9 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
public DbSet<MessagingGroup> MessagingGroups => Set<MessagingGroup>();
|
public DbSet<MessagingGroup> MessagingGroups => Set<MessagingGroup>();
|
||||||
public DbSet<NotificationLog> NotificationLogs => Set<NotificationLog>();
|
public DbSet<NotificationLog> NotificationLogs => Set<NotificationLog>();
|
||||||
|
|
||||||
|
public DbSet<SiteSetting> SiteSettings => Set<SiteSetting>();
|
||||||
|
public DbSet<NotificationSetting> NotificationSettings => Set<NotificationSetting>();
|
||||||
|
|
||||||
protected override void OnModelCreating(ModelBuilder builder)
|
protected override void OnModelCreating(ModelBuilder builder)
|
||||||
{
|
{
|
||||||
base.OnModelCreating(builder);
|
base.OnModelCreating(builder);
|
||||||
@@ -53,6 +61,23 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
entity.Ignore(e => e.IsActive);
|
entity.Ignore(e => e.IsActive);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── UserInvitation (single-use, expiring first-login links) ─────────
|
||||||
|
builder.Entity<UserInvitation>(entity =>
|
||||||
|
{
|
||||||
|
entity.HasKey(e => e.Id);
|
||||||
|
entity.HasIndex(e => e.TokenHash).IsUnique();
|
||||||
|
entity.Property(e => e.TokenHash).HasMaxLength(64).IsRequired();
|
||||||
|
entity.Property(e => e.UserId).HasMaxLength(450).IsRequired();
|
||||||
|
entity.Property(e => e.CreatedBy).HasMaxLength(450).IsRequired();
|
||||||
|
entity.HasIndex(e => e.UserId);
|
||||||
|
entity.HasOne(e => e.User).WithMany()
|
||||||
|
.HasForeignKey(e => e.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
entity.Ignore(e => e.IsExpired);
|
||||||
|
entity.Ignore(e => e.IsUsed);
|
||||||
|
entity.Ignore(e => e.IsRevoked);
|
||||||
|
entity.Ignore(e => e.IsActive);
|
||||||
|
});
|
||||||
|
|
||||||
// ── AppUser (unchanged + new unique index on MemberId) ──────────────
|
// ── AppUser (unchanged + new unique index on MemberId) ──────────────
|
||||||
builder.Entity<AppUser>(entity =>
|
builder.Entity<AppUser>(entity =>
|
||||||
{
|
{
|
||||||
@@ -97,6 +122,7 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
entity.Property(e => e.NickName).HasMaxLength(100);
|
entity.Property(e => e.NickName).HasMaxLength(100);
|
||||||
entity.Property(e => e.FirstName_zh).HasMaxLength(100);
|
entity.Property(e => e.FirstName_zh).HasMaxLength(100);
|
||||||
entity.Property(e => e.LastName_zh).HasMaxLength(100);
|
entity.Property(e => e.LastName_zh).HasMaxLength(100);
|
||||||
|
entity.Property(e => e.Entity).HasMaxLength(200);
|
||||||
entity.Property(e => e.Gender).HasMaxLength(10);
|
entity.Property(e => e.Gender).HasMaxLength(10);
|
||||||
entity.Property(e => e.BaptismChurch).HasMaxLength(200);
|
entity.Property(e => e.BaptismChurch).HasMaxLength(200);
|
||||||
entity.Property(e => e.Email).HasMaxLength(200);
|
entity.Property(e => e.Email).HasMaxLength(200);
|
||||||
@@ -178,6 +204,18 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
{
|
{
|
||||||
entity.Property(e => e.Name_en).HasMaxLength(200).IsRequired();
|
entity.Property(e => e.Name_en).HasMaxLength(200).IsRequired();
|
||||||
entity.Property(e => e.Name_zh).HasMaxLength(200);
|
entity.Property(e => e.Name_zh).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.DefaultFunctionalClass).HasMaxLength(20).HasDefaultValue("Program");
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Form990ExpenseLine (Part IX natural-expense line catalog) ─────────
|
||||||
|
builder.Entity<Form990ExpenseLine>(entity =>
|
||||||
|
{
|
||||||
|
entity.Property(e => e.LineCode).HasMaxLength(10).IsRequired();
|
||||||
|
entity.Property(e => e.Name_en).HasMaxLength(200).IsRequired();
|
||||||
|
entity.Property(e => e.Name_zh).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
||||||
|
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
||||||
|
entity.HasIndex(e => e.LineCode).IsUnique();
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── ExpenseCategoryGroup ─────────────────────────────────────────────
|
// ── ExpenseCategoryGroup ─────────────────────────────────────────────
|
||||||
@@ -187,6 +225,8 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
entity.Property(e => e.Name_zh).HasMaxLength(200);
|
entity.Property(e => e.Name_zh).HasMaxLength(200);
|
||||||
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
||||||
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
||||||
|
entity.HasOne(e => e.Form990Line).WithMany()
|
||||||
|
.HasForeignKey(e => e.Form990LineId).OnDelete(DeleteBehavior.SetNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── ExpenseSubCategory ───────────────────────────────────────────────
|
// ── ExpenseSubCategory ───────────────────────────────────────────────
|
||||||
@@ -198,6 +238,8 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
||||||
entity.HasOne(e => e.Group).WithMany(g => g.SubCategories)
|
entity.HasOne(e => e.Group).WithMany(g => g.SubCategories)
|
||||||
.HasForeignKey(e => e.GroupId).OnDelete(DeleteBehavior.Restrict);
|
.HasForeignKey(e => e.GroupId).OnDelete(DeleteBehavior.Restrict);
|
||||||
|
entity.HasOne(e => e.Form990Line).WithMany()
|
||||||
|
.HasForeignKey(e => e.Form990LineId).OnDelete(DeleteBehavior.SetNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Expense ──────────────────────────────────────────────────────────
|
// ── Expense ──────────────────────────────────────────────────────────
|
||||||
@@ -226,12 +268,71 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
|
|
||||||
entity.HasOne(e => e.Ministry).WithMany()
|
entity.HasOne(e => e.Ministry).WithMany()
|
||||||
.HasForeignKey(e => e.MinistryId).OnDelete(DeleteBehavior.Restrict);
|
.HasForeignKey(e => e.MinistryId).OnDelete(DeleteBehavior.Restrict);
|
||||||
|
entity.HasOne(e => e.Member).WithMany()
|
||||||
|
.HasForeignKey(e => e.MemberId).OnDelete(DeleteBehavior.SetNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── ExpenseLine (category breakdown of one Expense) ──────────────────
|
||||||
|
builder.Entity<ExpenseLine>(entity =>
|
||||||
|
{
|
||||||
|
// Mirror the parent Expense's soft-delete filter (required relationship).
|
||||||
|
entity.HasQueryFilter(l => !l.Expense!.IsDeleted);
|
||||||
|
|
||||||
|
entity.Property(e => e.FunctionalClass).HasMaxLength(20);
|
||||||
|
entity.Property(e => e.Amount).HasColumnType("decimal(18,2)");
|
||||||
|
entity.Property(e => e.Description).HasMaxLength(500);
|
||||||
|
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
||||||
|
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
||||||
|
|
||||||
|
entity.HasIndex(e => e.ExpenseId);
|
||||||
|
|
||||||
|
entity.HasOne(e => e.Expense).WithMany(x => x.Lines)
|
||||||
|
.HasForeignKey(e => e.ExpenseId).OnDelete(DeleteBehavior.Cascade);
|
||||||
|
entity.HasOne(e => e.CategoryGroup).WithMany()
|
||||||
|
.HasForeignKey(e => e.CategoryGroupId).OnDelete(DeleteBehavior.Restrict);
|
||||||
|
entity.HasOne(e => e.SubCategory).WithMany()
|
||||||
|
.HasForeignKey(e => e.SubCategoryId).OnDelete(DeleteBehavior.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── ExpenseSnapshot (reusable vendor-payment template) ───────────────
|
||||||
|
builder.Entity<ExpenseSnapshot>(entity =>
|
||||||
|
{
|
||||||
|
entity.HasQueryFilter(s => !s.IsDeleted);
|
||||||
|
|
||||||
|
entity.Property(e => e.Name).HasMaxLength(150).IsRequired();
|
||||||
|
entity.Property(e => e.Description).HasMaxLength(500).IsRequired();
|
||||||
|
entity.Property(e => e.VendorName).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.CheckNumber).HasMaxLength(50);
|
||||||
|
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
||||||
|
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
||||||
|
entity.Property(e => e.DeletedBy).HasMaxLength(450);
|
||||||
|
|
||||||
|
entity.HasIndex(e => e.CreatedAt);
|
||||||
|
|
||||||
|
entity.HasOne(e => e.Ministry).WithMany()
|
||||||
|
.HasForeignKey(e => e.MinistryId).OnDelete(DeleteBehavior.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── ExpenseSnapshotLine (category breakdown of one snapshot) ─────────
|
||||||
|
builder.Entity<ExpenseSnapshotLine>(entity =>
|
||||||
|
{
|
||||||
|
// Mirror the parent snapshot's soft-delete filter (required relationship).
|
||||||
|
entity.HasQueryFilter(l => !l.Snapshot!.IsDeleted);
|
||||||
|
|
||||||
|
entity.Property(e => e.FunctionalClass).HasMaxLength(20);
|
||||||
|
entity.Property(e => e.Amount).HasColumnType("decimal(18,2)");
|
||||||
|
entity.Property(e => e.Description).HasMaxLength(500);
|
||||||
|
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
||||||
|
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
||||||
|
|
||||||
|
entity.HasIndex(e => e.SnapshotId);
|
||||||
|
|
||||||
|
entity.HasOne(e => e.Snapshot).WithMany(x => x.Lines)
|
||||||
|
.HasForeignKey(e => e.SnapshotId).OnDelete(DeleteBehavior.Cascade);
|
||||||
entity.HasOne(e => e.CategoryGroup).WithMany()
|
entity.HasOne(e => e.CategoryGroup).WithMany()
|
||||||
.HasForeignKey(e => e.CategoryGroupId).OnDelete(DeleteBehavior.Restrict);
|
.HasForeignKey(e => e.CategoryGroupId).OnDelete(DeleteBehavior.Restrict);
|
||||||
entity.HasOne(e => e.SubCategory).WithMany()
|
entity.HasOne(e => e.SubCategory).WithMany()
|
||||||
.HasForeignKey(e => e.SubCategoryId).OnDelete(DeleteBehavior.Restrict);
|
.HasForeignKey(e => e.SubCategoryId).OnDelete(DeleteBehavior.Restrict);
|
||||||
entity.HasOne(e => e.Member).WithMany()
|
|
||||||
.HasForeignKey(e => e.MemberId).OnDelete(DeleteBehavior.SetNull);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── ChurchProfile (singleton settings) ───────────────────────────────
|
// ── ChurchProfile (singleton settings) ───────────────────────────────
|
||||||
@@ -245,12 +346,48 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, string>
|
|||||||
entity.Property(e => e.BankName).HasMaxLength(200);
|
entity.Property(e => e.BankName).HasMaxLength(200);
|
||||||
entity.Property(e => e.BankAccountNumber).HasMaxLength(50);
|
entity.Property(e => e.BankAccountNumber).HasMaxLength(50);
|
||||||
entity.Property(e => e.BankRoutingNumber).HasMaxLength(50);
|
entity.Property(e => e.BankRoutingNumber).HasMaxLength(50);
|
||||||
|
entity.Property(e => e.NameZh).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.Phone).HasMaxLength(50);
|
||||||
|
entity.Property(e => e.Email).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.Website).HasMaxLength(300);
|
||||||
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
||||||
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
||||||
|
entity.Property(e => e.AiProvider).HasMaxLength(20).HasDefaultValue("Claude");
|
||||||
|
entity.Property(e => e.ClaudeModel).HasMaxLength(100).HasDefaultValue("claude-haiku-4-5-20251001");
|
||||||
|
entity.Property(e => e.ClaudeApiKey).HasMaxLength(500);
|
||||||
|
entity.Property(e => e.GeminiModel).HasMaxLength(100).HasDefaultValue("gemini-2.5-flash-lite");
|
||||||
|
entity.Property(e => e.GeminiApiKey).HasMaxLength(500);
|
||||||
// Optimistic-concurrency token for safe check-number allocation.
|
// Optimistic-concurrency token for safe check-number allocation.
|
||||||
entity.Property(e => e.xmin).IsRowVersion();
|
entity.Property(e => e.xmin).IsRowVersion();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── SiteSetting (singleton presentation/locale settings) ─────────────
|
||||||
|
builder.Entity<SiteSetting>(entity =>
|
||||||
|
{
|
||||||
|
entity.Property(e => e.SiteTitle).HasMaxLength(200).IsRequired();
|
||||||
|
entity.Property(e => e.SiteTitleZh).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.DefaultLanguage).HasMaxLength(10).IsRequired();
|
||||||
|
entity.Property(e => e.TimeZone).HasMaxLength(100).IsRequired();
|
||||||
|
entity.Property(e => e.DateFormat).HasMaxLength(50).IsRequired();
|
||||||
|
entity.Property(e => e.Currency).HasMaxLength(10).IsRequired();
|
||||||
|
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
||||||
|
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── NotificationSetting (singleton SMTP + Line settings) ─────────────
|
||||||
|
builder.Entity<NotificationSetting>(entity =>
|
||||||
|
{
|
||||||
|
entity.Property(e => e.SmtpHost).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.SmtpUser).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.SmtpPassword).HasMaxLength(500);
|
||||||
|
entity.Property(e => e.FromAddress).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.FromName).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.LineChannelAccessToken).HasMaxLength(500);
|
||||||
|
entity.Property(e => e.LineChannelSecret).HasMaxLength(200);
|
||||||
|
entity.Property(e => e.CreatedBy).HasMaxLength(450);
|
||||||
|
entity.Property(e => e.UpdatedBy).HasMaxLength(450);
|
||||||
|
});
|
||||||
|
|
||||||
// ── Check (disbursement) ─────────────────────────────────────────────
|
// ── Check (disbursement) ─────────────────────────────────────────────
|
||||||
builder.Entity<Check>(entity =>
|
builder.Entity<Check>(entity =>
|
||||||
{
|
{
|
||||||
|
|||||||
+242
-11
@@ -28,6 +28,8 @@ public static class DbSeeder
|
|||||||
("Hospitality", "招待", 8),
|
("Hospitality", "招待", 8),
|
||||||
("Children", "兒牧", 9),
|
("Children", "兒牧", 9),
|
||||||
("Catering", "餐飲", 10),
|
("Catering", "餐飲", 10),
|
||||||
|
("Cell Groups", "小組牧養", 11),
|
||||||
|
("Special Events", "特別活動", 12),
|
||||||
];
|
];
|
||||||
|
|
||||||
// (GroupEn, GroupZh, Sort, SubItems[(SubEn, SubZh)])
|
// (GroupEn, GroupZh, Sort, SubItems[(SubEn, SubZh)])
|
||||||
@@ -35,15 +37,115 @@ public static class DbSeeder
|
|||||||
[
|
[
|
||||||
("Equipment", "設備", 1, [("Purchase","購置"),("Rental","租借"),("Maintenance & Repair","維修")]),
|
("Equipment", "設備", 1, [("Purchase","購置"),("Rental","租借"),("Maintenance & Repair","維修")]),
|
||||||
("Consumables", "消耗品", 2, [("Batteries","電池"),("Accessories","配件"),("Cleaning Supplies","清潔用品"),("Office Supplies","文具")]),
|
("Consumables", "消耗品", 2, [("Batteries","電池"),("Accessories","配件"),("Cleaning Supplies","清潔用品"),("Office Supplies","文具")]),
|
||||||
("Food & Beverage", "餐飲", 3, [("Catering","出餐費用"),("Food Ingredients","食材採購"),("Utensils","器具"),("Consumables","消耗品")]),
|
("Food & Beverage", "餐飲", 3, [("Catering","出餐費用"),("Food Ingredients","食材採購"),("Utensils","器具"),("Disposable Tableware","一次性餐具")]),
|
||||||
("Training", "培訓", 4, [("Course Fees","課程費用"),("Books","書籍"),("Conference","研討會"),("Travel","差旅")]),
|
("Training", "培訓", 4, [("Course Fees","課程費用"),("Books","書籍"),("Conference","研討會"),("Travel","差旅")]),
|
||||||
("Materials", "教材", 5, [("Printing","印刷費用"),("Craft Supplies","手工材料"),("Copyright & Licensing","版權購買")]),
|
("Materials", "教材", 5, [("Curriculum Printing","教材印刷"),("Craft Supplies","手工材料"),("Copyright & Licensing","版權購買")]),
|
||||||
("Facility", "場地", 6, [("Rent","場地租金"),("Utilities","水電"),("Property Insurance","財產保險"),("Decoration","裝飾")]),
|
("Facility", "場地", 6, [("Rent","場地租金"),("Utilities","水電"),("Property Insurance","財產保險"),("Decoration","裝飾"),("Repairs & Maintenance","修繕維護")]),
|
||||||
("Printing", "印刷", 7, [("Bulletins","週報"),("Order of Service","程序單"),("Posters","海報")]),
|
("Printing", "印刷", 7, [("Bulletins","週報"),("Order of Service","程序單"),("Posters","海報"),("Advertising & Promotion","廣告推廣")]),
|
||||||
("Missions", "宣教", 8, [("Offering Transfer","奉獻轉帳"),("Missionary Support","宣教士支援"),("Travel","差旅")]),
|
("Missions", "宣教", 8, [("Offering Transfer","奉獻轉帳"),("Missionary Support","宣教士支援"),("Foreign Missions Support","國外宣教支援"),("Travel","差旅")]),
|
||||||
("Benevolence", "關懷救助", 9, [("Emergency Aid","急難救助"),("Condolence Gifts","慰問禮品"),("Visit Expenses","探訪費用")]),
|
("Benevolence", "關懷救助", 9, [("Emergency Aid","急難救助"),("Condolence Gifts","慰問禮品"),("Visit Expenses","探訪費用")]),
|
||||||
("Other", "其他", 10, [("Miscellaneous","雜支")]),
|
("Other", "其他", 10, [("Miscellaneous","雜支"),("Gifts","禮品")]),
|
||||||
("Personnel", "人事", 11, [("Salary & Wages","薪資"),("Payroll Taxes","薪資稅費"),("Employee Benefits","員工福利"),("Workers Compensation","勞工保險"),("Honorarium","酬庸"),("Staff Training","同工進修"),("Contract Labor","外包勞務")]),
|
("Personnel", "人事", 11, [("Officer / Key Employee Compensation","主要職員薪酬"),("Salary & Wages","薪資"),("Payroll Taxes","薪資稅費"),("Employee Benefits","員工福利"),("Retirement / Pension","退休金"),("Workers Compensation","勞工保險"),("Honorarium","酬庸"),("Staff Training","同工進修"),("Contract Labor","外包勞務")]),
|
||||||
|
("Professional Services", "專業服務", 12, [("Legal","法律服務"),("Accounting & Audit","會計與審計"),("Other Professional","其他專業服務")]),
|
||||||
|
("Information Technology", "資訊科技", 13, [("Software & Subscriptions","軟體與訂閱"),("Website & Hosting","網站與主機"),("Internet & Telecom","網路與電信")]),
|
||||||
|
("Finance & Banking", "財務與銀行", 14, [("Interest","利息支出"),("Bank & Processing Fees","銀行/金流手續費")]),
|
||||||
|
];
|
||||||
|
|
||||||
|
// (LineCode, Name_en, Name_zh, Sort)
|
||||||
|
private static readonly (string Code, string En, string Zh, int Sort)[] Form990LineSeed =
|
||||||
|
[
|
||||||
|
("1", "Grants to domestic organizations", "對國內機構之捐贈", 1),
|
||||||
|
("2", "Grants to domestic individuals", "對國內個人之捐贈", 2),
|
||||||
|
("3", "Grants to foreign organizations/individuals", "對國外之捐贈", 3),
|
||||||
|
("5", "Compensation of current officers / key employees", "主要職員/負責人薪酬", 4),
|
||||||
|
("7", "Other salaries and wages", "薪資", 5),
|
||||||
|
("8", "Pension plan accruals and contributions", "退休金提撥", 6),
|
||||||
|
("9", "Other employee benefits", "員工福利", 7),
|
||||||
|
("10", "Payroll taxes", "薪資稅", 8),
|
||||||
|
("11b", "Legal fees", "法律服務費", 9),
|
||||||
|
("11c", "Accounting fees", "會計與審計費", 10),
|
||||||
|
("11g", "Other fees for services (non-employee)", "其他勞務報酬(非員工)", 11),
|
||||||
|
("12", "Advertising and promotion", "廣告與推廣", 12),
|
||||||
|
("13", "Office expenses", "辦公費用", 13),
|
||||||
|
("14", "Information technology", "資訊科技", 14),
|
||||||
|
("16", "Occupancy", "場地佔用", 15),
|
||||||
|
("17", "Travel", "差旅", 16),
|
||||||
|
("19", "Conferences, conventions, and meetings", "會議與研習", 17),
|
||||||
|
("20", "Interest", "利息", 18),
|
||||||
|
("22", "Depreciation", "折舊", 19),
|
||||||
|
("23", "Insurance", "保險", 20),
|
||||||
|
("24", "Other expenses", "其他費用", 21),
|
||||||
|
];
|
||||||
|
|
||||||
|
// (GroupEn, SubEn, LineCode) — default natural-category → 990 line mapping.
|
||||||
|
private static readonly (string GroupEn, string SubEn, string Code)[] Form990SubMappingSeed =
|
||||||
|
[
|
||||||
|
("Personnel", "Officer / Key Employee Compensation", "5"),
|
||||||
|
("Personnel", "Salary & Wages", "7"),
|
||||||
|
("Personnel", "Payroll Taxes", "10"),
|
||||||
|
("Personnel", "Employee Benefits", "9"),
|
||||||
|
("Personnel", "Retirement / Pension","8"),
|
||||||
|
("Personnel", "Workers Compensation","9"),
|
||||||
|
("Personnel", "Honorarium", "11g"),
|
||||||
|
("Personnel", "Contract Labor", "11g"),
|
||||||
|
("Personnel", "Staff Training", "19"),
|
||||||
|
("Facility", "Rent", "16"),
|
||||||
|
("Facility", "Utilities", "16"),
|
||||||
|
("Facility", "Property Insurance", "23"),
|
||||||
|
("Facility", "Decoration", "24"),
|
||||||
|
// Building repairs & maintenance (plumbing, electrical, painting) are part of Occupancy.
|
||||||
|
("Facility", "Repairs & Maintenance", "16"),
|
||||||
|
("Training", "Course Fees", "19"),
|
||||||
|
("Training", "Conference", "19"),
|
||||||
|
("Training", "Books", "24"),
|
||||||
|
("Training", "Travel", "17"),
|
||||||
|
("Missions", "Travel", "17"),
|
||||||
|
// Domestic missions support is paid to individual missionaries/families → line 2 (grants to individuals).
|
||||||
|
("Missions", "Offering Transfer", "2"),
|
||||||
|
("Missions", "Missionary Support", "2"),
|
||||||
|
("Missions", "Foreign Missions Support", "3"),
|
||||||
|
("Benevolence", "Emergency Aid", "2"),
|
||||||
|
("Benevolence", "Condolence Gifts", "2"),
|
||||||
|
// Visitation is the church's own travel/program cost, not a grant to an individual.
|
||||||
|
("Benevolence", "Visit Expenses", "17"),
|
||||||
|
("Consumables", "Office Supplies", "13"),
|
||||||
|
// General supplies belong with office expenses (line 13), not the "Other" catch-all.
|
||||||
|
("Consumables", "Batteries", "13"),
|
||||||
|
("Consumables", "Accessories", "13"),
|
||||||
|
("Consumables", "Cleaning Supplies", "13"),
|
||||||
|
// IRS line 13 covers equipment rental and maintenance.
|
||||||
|
("Equipment", "Rental", "13"),
|
||||||
|
("Equipment", "Maintenance & Repair", "13"),
|
||||||
|
("Printing", "Bulletins", "13"),
|
||||||
|
("Printing", "Order of Service", "13"),
|
||||||
|
("Printing", "Posters", "12"),
|
||||||
|
("Printing", "Advertising & Promotion", "12"),
|
||||||
|
("Materials", "Curriculum Printing", "13"),
|
||||||
|
// Classroom/craft supplies fall under IRS line 13 office expenses ("supplies… classroom…").
|
||||||
|
("Materials", "Craft Supplies", "13"),
|
||||||
|
("Professional Services", "Legal", "11b"),
|
||||||
|
("Professional Services", "Accounting & Audit", "11c"),
|
||||||
|
("Professional Services", "Other Professional", "11g"),
|
||||||
|
("Information Technology", "Software & Subscriptions", "14"),
|
||||||
|
("Information Technology", "Website & Hosting", "14"),
|
||||||
|
("Information Technology", "Internet & Telecom", "14"),
|
||||||
|
("Finance & Banking", "Interest", "20"),
|
||||||
|
// Bank/processing fees are office expenses per IRS line 13 (consistent with Interest → 20).
|
||||||
|
("Finance & Banking", "Bank & Processing Fees", "13"),
|
||||||
|
// Appreciation/outreach gifts have no natural 990 line; mapped to 24 explicitly so this
|
||||||
|
// deliberate "Other" choice doesn't inflate UnmappedExpenseCount. (Benevolence gifts → line 2.)
|
||||||
|
("Other", "Gifts", "24"),
|
||||||
|
];
|
||||||
|
|
||||||
|
// One-time corrections for subcategories that were mapped to the WRONG line in an earlier
|
||||||
|
// seed. The normal mapping loop below only fills NULLs, so it cannot fix an existing bad
|
||||||
|
// value — this block does. Idempotent: each row fires only while the subcategory still holds
|
||||||
|
// the OLD line, so it never clobbers a deliberate admin re-mapping. (GroupEn, SubEn, Old, New)
|
||||||
|
private static readonly (string GroupEn, string SubEn, string OldCode, string NewCode)[] Form990RemapSeed =
|
||||||
|
[
|
||||||
|
("Benevolence", "Visit Expenses", "2", "17"),
|
||||||
|
("Missions", "Missionary Support", "1", "2"),
|
||||||
|
("Missions", "Offering Transfer", "1", "2"),
|
||||||
];
|
];
|
||||||
|
|
||||||
private static readonly (string Name, string Description)[] Roles =
|
private static readonly (string Name, string Description)[] Roles =
|
||||||
@@ -87,13 +189,32 @@ public static class DbSeeder
|
|||||||
("finance", Modules.MonthlyStatements, true, true, false, true),
|
("finance", Modules.MonthlyStatements, true, true, false, true),
|
||||||
("finance", Modules.ChurchProfile, true, true, false, false),
|
("finance", Modules.ChurchProfile, true, true, false, false),
|
||||||
("finance", Modules.Disbursements, true, true, true, true),
|
("finance", Modules.Disbursements, true, true, true, true),
|
||||||
|
("finance", Modules.Form990Report, true, false, false, false),
|
||||||
|
|
||||||
// Logs — read-only. System logs are technical (pastor only); audit logs have
|
// Logs — read-only. System logs are technical (pastor only); audit logs have
|
||||||
// governance value, so finance and board members can read them too.
|
// governance value, so finance and board members can read them too.
|
||||||
("pastor", Modules.SystemLogs, true, false, false, false),
|
("pastor", Modules.SystemLogs, true, false, false, false),
|
||||||
("pastor", Modules.AuditLogs, true, false, false, false),
|
("pastor", Modules.AuditLogs, true, false, false, false),
|
||||||
("finance", Modules.AuditLogs, true, false, false, false),
|
("finance", Modules.AuditLogs, true, false, false, false),
|
||||||
("board_member", Modules.AuditLogs, true, false, false, false),
|
("board_member", Modules.AuditLogs, true, false, false, false),
|
||||||
|
("pastor", Modules.Form990Report, true, false, false, false),
|
||||||
|
("board_member", Modules.Form990Report, true, false, false, false),
|
||||||
|
|
||||||
|
// Ministries — secretary maintains the list; coworker_chair edits; ministry
|
||||||
|
// leaders and pastor read.
|
||||||
|
("secretary", Modules.Ministries, true, true, true, false),
|
||||||
|
("coworker_chair", Modules.Ministries, true, true, false, false),
|
||||||
|
("ministry_leader", Modules.Ministries, true, false, false, false),
|
||||||
|
("pastor", Modules.Ministries, true, false, false, false),
|
||||||
|
|
||||||
|
// Meal attendance — secretary and coworkers record; finance and pastor read.
|
||||||
|
("secretary", Modules.MealAttendance, true, true, false, false),
|
||||||
|
("coworker", Modules.MealAttendance, true, true, false, false),
|
||||||
|
("finance", Modules.MealAttendance, true, false, false, false),
|
||||||
|
("pastor", Modules.MealAttendance, true, false, false, false),
|
||||||
|
|
||||||
|
// Users, Permissions, and Settings are intentionally super_admin-only:
|
||||||
|
// super_admin bypasses all checks, so no seed rows are needed here.
|
||||||
];
|
];
|
||||||
|
|
||||||
public static async Task SeedRolePermissionsAsync(AppDbContext db)
|
public static async Task SeedRolePermissionsAsync(AppDbContext db)
|
||||||
@@ -163,13 +284,35 @@ public static class DbSeeder
|
|||||||
foreach (var (en, zh, sort) in MinistrySeed)
|
foreach (var (en, zh, sort) in MinistrySeed)
|
||||||
{
|
{
|
||||||
if (!await db.Ministries.AnyAsync(m => m.Name_en == en))
|
if (!await db.Ministries.AnyAsync(m => m.Name_en == en))
|
||||||
db.Ministries.Add(new Ministry { Name_en = en, Name_zh = zh, SortOrder = sort, IsActive = true });
|
db.Ministries.Add(new Ministry
|
||||||
|
{
|
||||||
|
Name_en = en, Name_zh = zh, SortOrder = sort, IsActive = true,
|
||||||
|
DefaultFunctionalClass = en == "Administration"
|
||||||
|
? FunctionalClasses.ManagementGeneral
|
||||||
|
: FunctionalClasses.Program,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task SeedExpenseCategoriesAsync(AppDbContext db)
|
public static async Task SeedExpenseCategoriesAsync(AppDbContext db)
|
||||||
{
|
{
|
||||||
|
// One-time renames to remove same-name-different-parent ambiguity. Idempotent:
|
||||||
|
// only fires while the old name still exists. (New installs never hit this.)
|
||||||
|
var renames = new (string GroupEn, string OldSub, string NewEn, string NewZh)[]
|
||||||
|
{
|
||||||
|
("Food & Beverage", "Consumables", "Disposable Tableware", "一次性餐具"),
|
||||||
|
("Materials", "Printing", "Curriculum Printing", "教材印刷"),
|
||||||
|
};
|
||||||
|
foreach (var (groupEn, oldSub, newEn, newZh) in renames)
|
||||||
|
{
|
||||||
|
var grp = await db.ExpenseCategoryGroups.FirstOrDefaultAsync(g => g.Name_en == groupEn);
|
||||||
|
if (grp is null) continue;
|
||||||
|
var sub = await db.ExpenseSubCategories.FirstOrDefaultAsync(s => s.GroupId == grp.Id && s.Name_en == oldSub);
|
||||||
|
if (sub is not null) { sub.Name_en = newEn; sub.Name_zh = newZh; }
|
||||||
|
}
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
foreach (var (gEn, gZh, gSort, subs) in ExpenseCategorySeed)
|
foreach (var (gEn, gZh, gSort, subs) in ExpenseCategorySeed)
|
||||||
{
|
{
|
||||||
var group = await db.ExpenseCategoryGroups.FirstOrDefaultAsync(g => g.Name_en == gEn);
|
var group = await db.ExpenseCategoryGroups.FirstOrDefaultAsync(g => g.Name_en == gEn);
|
||||||
@@ -192,6 +335,46 @@ public static class DbSeeder
|
|||||||
await db.SaveChangesAsync();
|
await db.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static async Task SeedForm990ExpenseLinesAsync(AppDbContext db)
|
||||||
|
{
|
||||||
|
foreach (var (code, en, zh, sort) in Form990LineSeed)
|
||||||
|
{
|
||||||
|
if (!await db.Form990ExpenseLines.AnyAsync(l => l.LineCode == code))
|
||||||
|
db.Form990ExpenseLines.Add(new Form990ExpenseLine
|
||||||
|
{ LineCode = code, Name_en = en, Name_zh = zh, SortOrder = sort, IsActive = true });
|
||||||
|
}
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
|
||||||
|
var linesByCode = await db.Form990ExpenseLines.ToDictionaryAsync(l => l.LineCode, l => l.Id);
|
||||||
|
var fallbackId = linesByCode["24"];
|
||||||
|
|
||||||
|
// Every group defaults to line 24 (safety net); precise mapping lives on subcategories.
|
||||||
|
foreach (var group in await db.ExpenseCategoryGroups.ToListAsync())
|
||||||
|
group.Form990LineId ??= fallbackId;
|
||||||
|
|
||||||
|
// Subcategory default mappings — only set when not already mapped (never clobber an admin edit).
|
||||||
|
var subsByKey = await db.ExpenseSubCategories.Include(s => s.Group).ToListAsync();
|
||||||
|
foreach (var (groupEn, subEn, code) in Form990SubMappingSeed)
|
||||||
|
{
|
||||||
|
var sub = subsByKey.FirstOrDefault(s => s.Group!.Name_en == groupEn && s.Name_en == subEn);
|
||||||
|
if (sub is not null && sub.Form990LineId is null && linesByCode.TryGetValue(code, out var lineId))
|
||||||
|
sub.Form990LineId = lineId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Correct earlier mis-mappings on existing databases (see Form990RemapSeed). Only fires
|
||||||
|
// while the subcategory still holds the OLD line, so a later admin edit is never clobbered.
|
||||||
|
foreach (var (groupEn, subEn, oldCode, newCode) in Form990RemapSeed)
|
||||||
|
{
|
||||||
|
var sub = subsByKey.FirstOrDefault(s => s.Group!.Name_en == groupEn && s.Name_en == subEn);
|
||||||
|
if (sub is null) continue;
|
||||||
|
if (linesByCode.TryGetValue(oldCode, out var oldId)
|
||||||
|
&& linesByCode.TryGetValue(newCode, out var newId)
|
||||||
|
&& sub.Form990LineId == oldId)
|
||||||
|
sub.Form990LineId = newId;
|
||||||
|
}
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
public static async Task SeedChurchProfileAsync(AppDbContext db)
|
public static async Task SeedChurchProfileAsync(AppDbContext db)
|
||||||
{
|
{
|
||||||
// Singleton row used by the disbursement module (issuer info + check counter).
|
// Singleton row used by the disbursement module (issuer info + check counter).
|
||||||
@@ -208,6 +391,50 @@ public static class DbSeeder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static async Task SeedSiteSettingAsync(AppDbContext db)
|
||||||
|
{
|
||||||
|
// Singleton row holding site-wide presentation/locale settings.
|
||||||
|
if (!await db.SiteSettings.AnyAsync())
|
||||||
|
{
|
||||||
|
db.SiteSettings.Add(new SiteSetting
|
||||||
|
{
|
||||||
|
SiteTitle = "River Of Life Christian Church",
|
||||||
|
SiteTitleZh = "生命河靈糧堂",
|
||||||
|
DefaultLanguage = "en",
|
||||||
|
TimeZone = "America/Los_Angeles",
|
||||||
|
DateFormat = "yyyy-MM-dd",
|
||||||
|
Currency = "USD",
|
||||||
|
});
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task SeedNotificationSettingAsync(AppDbContext db, IConfiguration config)
|
||||||
|
{
|
||||||
|
// Singleton row that becomes the runtime source of truth for SMTP + Line. Seed it once
|
||||||
|
// from the legacy "Smtp"/"Line" appsettings sections so existing config carries over.
|
||||||
|
if (!await db.NotificationSettings.AnyAsync())
|
||||||
|
{
|
||||||
|
var smtp = config.GetSection("Smtp");
|
||||||
|
var line = config.GetSection("Line");
|
||||||
|
db.NotificationSettings.Add(new NotificationSetting
|
||||||
|
{
|
||||||
|
EnableEmail = !string.IsNullOrWhiteSpace(smtp["Host"]),
|
||||||
|
SmtpHost = smtp["Host"] ?? "",
|
||||||
|
SmtpPort = int.TryParse(smtp["Port"], out var port) ? port : 587,
|
||||||
|
SmtpUseSsl = !bool.TryParse(smtp["UseSsl"], out var ssl) || ssl,
|
||||||
|
SmtpUser = smtp["User"] ?? "",
|
||||||
|
SmtpPassword = smtp["Password"] ?? "",
|
||||||
|
FromAddress = smtp["FromAddress"] ?? "",
|
||||||
|
FromName = smtp["FromName"] ?? "",
|
||||||
|
EnableLine = !string.IsNullOrWhiteSpace(line["ChannelAccessToken"]),
|
||||||
|
LineChannelAccessToken = line["ChannelAccessToken"] ?? "",
|
||||||
|
LineChannelSecret = line["ChannelSecret"] ?? "",
|
||||||
|
});
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Seeds roles and (in Development) the default admin account.
|
/// Seeds roles and (in Development) the default admin account.
|
||||||
/// Called once on application startup after migrations have been applied.
|
/// Called once on application startup after migrations have been applied.
|
||||||
@@ -217,6 +444,7 @@ public static class DbSeeder
|
|||||||
var roleManager = services.GetRequiredService<RoleManager<AppRole>>();
|
var roleManager = services.GetRequiredService<RoleManager<AppRole>>();
|
||||||
var userManager = services.GetRequiredService<UserManager<AppUser>>();
|
var userManager = services.GetRequiredService<UserManager<AppUser>>();
|
||||||
var env = services.GetRequiredService<IWebHostEnvironment>();
|
var env = services.GetRequiredService<IWebHostEnvironment>();
|
||||||
|
var config = services.GetRequiredService<IConfiguration>();
|
||||||
|
|
||||||
await SeedRolesAsync(roleManager);
|
await SeedRolesAsync(roleManager);
|
||||||
|
|
||||||
@@ -225,7 +453,10 @@ public static class DbSeeder
|
|||||||
await SeedGivingCategoriesAsync(db);
|
await SeedGivingCategoriesAsync(db);
|
||||||
await SeedMinistriesAsync(db);
|
await SeedMinistriesAsync(db);
|
||||||
await SeedExpenseCategoriesAsync(db);
|
await SeedExpenseCategoriesAsync(db);
|
||||||
|
await SeedForm990ExpenseLinesAsync(db);
|
||||||
await SeedChurchProfileAsync(db);
|
await SeedChurchProfileAsync(db);
|
||||||
|
await SeedSiteSettingAsync(db);
|
||||||
|
await SeedNotificationSettingAsync(db, config);
|
||||||
|
|
||||||
if (env.IsDevelopment())
|
if (env.IsDevelopment())
|
||||||
await SeedAdminUserAsync(userManager);
|
await SeedAdminUserAsync(userManager);
|
||||||
|
|||||||
@@ -157,6 +157,8 @@ rows AS (
|
|||||||
mi."Id" AS ministry_id,
|
mi."Id" AS ministry_id,
|
||||||
gp."Id" AS group_id,
|
gp."Id" AS group_id,
|
||||||
sc."Id" AS sub_id,
|
sc."Id" AS sub_id,
|
||||||
|
-- pre-allocate the expense id so the matching ExpenseLine can reference it
|
||||||
|
nextval(pg_get_serial_sequence('"Expenses"','Id')) AS new_id,
|
||||||
sp.is_reimb,
|
sp.is_reimb,
|
||||||
sp.vendor,
|
sp.vendor,
|
||||||
sp.descr,
|
sp.descr,
|
||||||
@@ -172,13 +174,14 @@ rows AS (
|
|||||||
JOIN "ExpenseCategoryGroups" gp ON gp."Name_en" = sp.grp
|
JOIN "ExpenseCategoryGroups" gp ON gp."Name_en" = sp.grp
|
||||||
JOIN "ExpenseSubCategories" sc ON sc."Name_en" = sp.sub AND sc."GroupId" = gp."Id"
|
JOIN "ExpenseSubCategories" sc ON sc."Name_en" = sp.sub AND sc."GroupId" = gp."Id"
|
||||||
)
|
)
|
||||||
|
, ins_exp AS (
|
||||||
INSERT INTO "Expenses"
|
INSERT INTO "Expenses"
|
||||||
("MinistryId","CategoryGroupId","SubCategoryId","Type","Status","Amount",
|
("Id","MinistryId","Type","Status","Amount",
|
||||||
"Description","VendorName","MemberId","CheckNumber","ExpenseDate",
|
"Description","VendorName","MemberId","CheckNumber","ExpenseDate",
|
||||||
"Notes","SubmittedBy","SubmittedAt","ReviewedBy","ReviewedAt","PaidBy","PaidAt",
|
"Notes","SubmittedBy","SubmittedAt","ReviewedBy","ReviewedAt","PaidBy","PaidAt",
|
||||||
"CreatedAt","CreatedBy","UpdatedAt","UpdatedBy","IsDeleted")
|
"CreatedAt","CreatedBy","UpdatedAt","UpdatedBy","IsDeleted")
|
||||||
SELECT
|
SELECT
|
||||||
r.ministry_id, r.group_id, r.sub_id,
|
r.new_id, r.ministry_id,
|
||||||
CASE WHEN r.is_reimb THEN 'StaffReimbursement' ELSE 'VendorPayment' END,
|
CASE WHEN r.is_reimb THEN 'StaffReimbursement' ELSE 'VendorPayment' END,
|
||||||
r.status,
|
r.status,
|
||||||
r.amount,
|
r.amount,
|
||||||
@@ -196,6 +199,15 @@ SELECT
|
|||||||
CASE WHEN r.status = 'Paid' THEN 'mockdata' END,
|
CASE WHEN r.status = 'Paid' THEN 'mockdata' END,
|
||||||
CASE WHEN r.status = 'Paid' THEN r.expense_date::timestamptz END,
|
CASE WHEN r.status = 'Paid' THEN r.expense_date::timestamptz END,
|
||||||
r.expense_date::timestamptz, 'mockdata', r.expense_date::timestamptz, 'mockdata', false
|
r.expense_date::timestamptz, 'mockdata', r.expense_date::timestamptz, 'mockdata', false
|
||||||
|
FROM rows r
|
||||||
|
)
|
||||||
|
-- one line per mock expense (single-category), mirroring the migrated production shape
|
||||||
|
INSERT INTO "ExpenseLines"
|
||||||
|
("ExpenseId","CategoryGroupId","SubCategoryId","FunctionalClass","Amount","Description",
|
||||||
|
"CreatedAt","CreatedBy","UpdatedAt","UpdatedBy")
|
||||||
|
SELECT
|
||||||
|
r.new_id, r.group_id, r.sub_id, NULL, r.amount, NULL,
|
||||||
|
r.expense_date::timestamptz, 'mockdata', r.expense_date::timestamptz, 'mockdata'
|
||||||
FROM rows r;
|
FROM rows r;
|
||||||
|
|
||||||
COMMIT;
|
COMMIT;
|
||||||
|
|||||||
@@ -9,6 +9,10 @@ public class ChurchProfile : AuditableEntity, IAuditable
|
|||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
public string Name { get; set; } = null!;
|
public string Name { get; set; } = null!;
|
||||||
|
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? Address { get; set; }
|
||||||
public string? City { get; set; }
|
public string? City { get; set; }
|
||||||
public string? State { get; set; }
|
public string? State { get; set; }
|
||||||
@@ -17,6 +21,13 @@ public class ChurchProfile : AuditableEntity, IAuditable
|
|||||||
public string? BankAccountNumber { get; set; }
|
public string? BankAccountNumber { get; set; }
|
||||||
public string? BankRoutingNumber { get; set; }
|
public string? BankRoutingNumber { get; set; }
|
||||||
|
|
||||||
|
// ── AI assist provider settings (editable via Church Profile → AI 設定 tab) ──
|
||||||
|
public string AiProvider { get; set; } = "Claude"; // "Claude" | "Gemini"
|
||||||
|
public string? ClaudeModel { get; set; } = "claude-haiku-4-5-20251001";
|
||||||
|
public string? ClaudeApiKey { get; set; } // secret, stored plaintext
|
||||||
|
public string? GeminiModel { get; set; } = "gemini-2.5-flash-lite";
|
||||||
|
public string? GeminiApiKey { get; set; } // secret, stored plaintext
|
||||||
|
|
||||||
/// <summary>Next check number to allocate; consumed (++) when a check is issued.</summary>
|
/// <summary>Next check number to allocate; consumed (++) when a check is issued.</summary>
|
||||||
public int NextCheckNumber { get; set; } = 1001;
|
public int NextCheckNumber { get; set; } = 1001;
|
||||||
|
|
||||||
|
|||||||
@@ -5,11 +5,9 @@ public class Expense : SoftDeleteEntity, IAuditable
|
|||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
public int MinistryId { get; set; }
|
public int MinistryId { get; set; }
|
||||||
public int CategoryGroupId { get; set; }
|
|
||||||
public int SubCategoryId { get; set; }
|
|
||||||
public string Type { get; set; } = "StaffReimbursement"; // VendorPayment | StaffReimbursement
|
public string Type { get; set; } = "StaffReimbursement"; // VendorPayment | StaffReimbursement
|
||||||
public string Status { get; set; } = "Draft"; // see state machine
|
public string Status { get; set; } = "Draft"; // see state machine
|
||||||
public decimal Amount { get; set; }
|
public decimal Amount { get; set; } // denormalized total = SUM(Lines.Amount), recomputed server-side
|
||||||
public string Description { get; set; } = null!;
|
public string Description { get; set; } = null!;
|
||||||
public string? VendorName { get; set; }
|
public string? VendorName { get; set; }
|
||||||
public int? MemberId { get; set; }
|
public int? MemberId { get; set; }
|
||||||
@@ -25,8 +23,7 @@ public class Expense : SoftDeleteEntity, IAuditable
|
|||||||
public DateTimeOffset? PaidAt { get; set; }
|
public DateTimeOffset? PaidAt { get; set; }
|
||||||
public string? PaidBy { get; set; }
|
public string? PaidBy { get; set; }
|
||||||
|
|
||||||
public Ministry? Ministry { get; set; }
|
public Ministry? Ministry { get; set; }
|
||||||
public ExpenseCategoryGroup? CategoryGroup { get; set; }
|
public Member? Member { get; set; }
|
||||||
public ExpenseSubCategory? SubCategory { get; set; }
|
public List<ExpenseLine> Lines { get; set; } = new();
|
||||||
public Member? Member { get; set; }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,5 +9,8 @@ public class ExpenseCategoryGroup : AuditableEntity, IAuditable
|
|||||||
public int SortOrder { get; set; }
|
public int SortOrder { get; set; }
|
||||||
public bool IsActive { get; set; } = true;
|
public bool IsActive { get; set; } = true;
|
||||||
|
|
||||||
|
public int? Form990LineId { get; set; }
|
||||||
|
public Form990ExpenseLine? Form990Line { get; set; }
|
||||||
|
|
||||||
public List<ExpenseSubCategory> SubCategories { get; set; } = [];
|
public List<ExpenseSubCategory> SubCategories { get; set; } = [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using ROLAC.API.Entities.Base;
|
||||||
|
namespace ROLAC.API.Entities;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One category line of an <see cref="Expense"/>. A single invoice/payment can span
|
||||||
|
/// multiple expense categories, so the category / amount / functional-class axis lives
|
||||||
|
/// here per line; the Expense header keeps payment-level info and a denormalized total.
|
||||||
|
/// Lines are wholly owned by the header (replaced as a set on update, like CheckLine).
|
||||||
|
/// </summary>
|
||||||
|
public class ExpenseLine : AuditableEntity
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int ExpenseId { get; set; }
|
||||||
|
public int CategoryGroupId { get; set; }
|
||||||
|
public int SubCategoryId { get; set; }
|
||||||
|
public string? FunctionalClass { get; set; } // null = inherit Ministry.DefaultFunctionalClass
|
||||||
|
public decimal Amount { get; set; }
|
||||||
|
public string? Description { get; set; } // optional per-line note (header description is authoritative for check printing)
|
||||||
|
|
||||||
|
public Expense? Expense { get; set; }
|
||||||
|
public ExpenseCategoryGroup? CategoryGroup { get; set; }
|
||||||
|
public ExpenseSubCategory? SubCategory { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using ROLAC.API.Entities.Base;
|
||||||
|
namespace ROLAC.API.Entities;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A reusable template of a vendor payment. Lets finance save a recurring fixed expense
|
||||||
|
/// (rent, internet, a fixed catered-meal cost) and re-apply it later, pre-filling everything
|
||||||
|
/// except the ExpenseDate. Shared church-wide; the creator is the auditable CreatedBy.
|
||||||
|
/// Lines are wholly owned by the header (replaced as a set on update, like ExpenseLine).
|
||||||
|
/// </summary>
|
||||||
|
public class ExpenseSnapshot : SoftDeleteEntity
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string Name { get; set; } = null!; // user label, e.g. "Monthly Rent — Landlord X"
|
||||||
|
public int MinistryId { get; set; }
|
||||||
|
public string Description { get; set; } = null!;
|
||||||
|
public string? VendorName { get; set; }
|
||||||
|
public string? CheckNumber { get; set; }
|
||||||
|
public string? Notes { get; set; }
|
||||||
|
|
||||||
|
public Ministry? Ministry { get; set; }
|
||||||
|
public List<ExpenseSnapshotLine> Lines { get; set; } = new();
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using ROLAC.API.Entities.Base;
|
||||||
|
namespace ROLAC.API.Entities;
|
||||||
|
|
||||||
|
/// <summary>One category line of an <see cref="ExpenseSnapshot"/>, mirroring <see cref="ExpenseLine"/>.</summary>
|
||||||
|
public class ExpenseSnapshotLine : AuditableEntity
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public int SnapshotId { get; set; }
|
||||||
|
public int CategoryGroupId { get; set; }
|
||||||
|
public int SubCategoryId { get; set; }
|
||||||
|
public string? FunctionalClass { get; set; } // null = inherit Ministry.DefaultFunctionalClass
|
||||||
|
public decimal Amount { get; set; }
|
||||||
|
public string? Description { get; set; }
|
||||||
|
|
||||||
|
public ExpenseSnapshot? Snapshot { get; set; }
|
||||||
|
public ExpenseCategoryGroup? CategoryGroup { get; set; }
|
||||||
|
public ExpenseSubCategory? SubCategory { get; set; }
|
||||||
|
}
|
||||||
@@ -10,5 +10,8 @@ public class ExpenseSubCategory : AuditableEntity, IAuditable
|
|||||||
public int SortOrder { get; set; }
|
public int SortOrder { get; set; }
|
||||||
public bool IsActive { get; set; } = true;
|
public bool IsActive { get; set; } = true;
|
||||||
|
|
||||||
|
public int? Form990LineId { get; set; }
|
||||||
|
public Form990ExpenseLine? Form990Line { get; set; }
|
||||||
|
|
||||||
public ExpenseCategoryGroup? Group { get; set; }
|
public ExpenseCategoryGroup? Group { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using ROLAC.API.Entities.Base;
|
||||||
|
namespace ROLAC.API.Entities;
|
||||||
|
|
||||||
|
/// <summary>A row of IRS Form 990 Part IX (natural expense line), e.g. "7 — Other salaries and wages".</summary>
|
||||||
|
public class Form990ExpenseLine : AuditableEntity, IAuditable
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string LineCode { get; set; } = null!; // "7", "11b", "16", "24"
|
||||||
|
public string Name_en { get; set; } = null!;
|
||||||
|
public string? Name_zh { get; set; }
|
||||||
|
public int SortOrder { get; set; }
|
||||||
|
public bool IsActive { get; set; } = true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
namespace ROLAC.API.Entities;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The three IRS Form 990 Part IX functional-expense columns. Stored verbatim in
|
||||||
|
/// Ministry.DefaultFunctionalClass and ExpenseLine.FunctionalClass.
|
||||||
|
/// </summary>
|
||||||
|
public static class FunctionalClasses
|
||||||
|
{
|
||||||
|
public const string Program = "Program";
|
||||||
|
public const string ManagementGeneral = "ManagementGeneral";
|
||||||
|
public const string Fundraising = "Fundraising";
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<string> All = [Program, ManagementGeneral, Fundraising];
|
||||||
|
|
||||||
|
/// <summary>Returns the value if valid, otherwise Program (the safe default).</summary>
|
||||||
|
public static string Normalize(string? value) =>
|
||||||
|
value is not null && All.Contains(value) ? value : Program;
|
||||||
|
}
|
||||||
@@ -48,16 +48,20 @@ public static class AuditActions
|
|||||||
public const string PasswordChanged = "PasswordChanged";
|
public const string PasswordChanged = "PasswordChanged";
|
||||||
public const string UserDeactivated = "UserDeactivated";
|
public const string UserDeactivated = "UserDeactivated";
|
||||||
public const string PermissionChanged = "PermissionChanged";
|
public const string PermissionChanged = "PermissionChanged";
|
||||||
|
public const string InvitationCreated = "InvitationCreated";
|
||||||
|
public const string InvitationAccepted = "InvitationAccepted";
|
||||||
public const string CheckIssued = "CheckIssued";
|
public const string CheckIssued = "CheckIssued";
|
||||||
public const string CheckVoided = "CheckVoided";
|
public const string CheckVoided = "CheckVoided";
|
||||||
public const string ExpenseApproved = "ExpenseApproved";
|
public const string ExpenseApproved = "ExpenseApproved";
|
||||||
|
public const string ExpenseRejected = "ExpenseRejected";
|
||||||
public const string StatementFinalized = "StatementFinalized";
|
public const string StatementFinalized = "StatementFinalized";
|
||||||
|
|
||||||
public static readonly IReadOnlyList<string> All =
|
public static readonly IReadOnlyList<string> All =
|
||||||
[
|
[
|
||||||
Create, Update, Delete, Login, Logout, LoginFailed, RoleChanged,
|
Create, Update, Delete, Login, Logout, LoginFailed, RoleChanged,
|
||||||
PasswordChanged, UserDeactivated, PermissionChanged, CheckIssued,
|
PasswordChanged, UserDeactivated, PermissionChanged,
|
||||||
CheckVoided, ExpenseApproved, StatementFinalized,
|
InvitationCreated, InvitationAccepted, CheckIssued,
|
||||||
|
CheckVoided, ExpenseApproved, ExpenseRejected, StatementFinalized,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ public class Member : SoftDeleteEntity, IAuditable
|
|||||||
public string? NickName { get; set; }
|
public string? NickName { get; set; }
|
||||||
public string? FirstName_zh { get; set; }
|
public string? FirstName_zh { get; set; }
|
||||||
public string? LastName_zh { get; set; }
|
public string? LastName_zh { get; set; }
|
||||||
|
public string? Entity { get; set; } // company / business name (公司行號) — used for company-check offerings
|
||||||
public string? Gender { get; set; } // 'M' | 'F' | 'Other'
|
public string? Gender { get; set; } // 'M' | 'F' | 'Other'
|
||||||
public DateOnly? DateOfBirth { get; set; }
|
public DateOnly? DateOfBirth { get; set; }
|
||||||
public DateOnly? BaptismDate { get; set; }
|
public DateOnly? BaptismDate { get; set; }
|
||||||
|
|||||||
@@ -11,4 +11,5 @@ public class Ministry : IAuditable
|
|||||||
public string? Description_zh { get; set; }
|
public string? Description_zh { get; set; }
|
||||||
public int SortOrder { get; set; }
|
public int SortOrder { get; set; }
|
||||||
public bool IsActive { get; set; } = true;
|
public bool IsActive { get; set; } = true;
|
||||||
|
public string DefaultFunctionalClass { get; set; } = "Program";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using ROLAC.API.Entities.Base;
|
||||||
|
namespace ROLAC.API.Entities;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Singleton (Id == 1) holding the editable SMTP + Line notification settings. This row — not the
|
||||||
|
/// "Smtp"/"Line" appsettings sections — is the runtime source of truth; those sections only seed
|
||||||
|
/// this row once on first startup. Read at send time via <c>INotificationSettingsService</c> so
|
||||||
|
/// edits apply without restarting the API.
|
||||||
|
///
|
||||||
|
/// Secrets (<see cref="SmtpPassword"/>, <see cref="LineChannelAccessToken"/>,
|
||||||
|
/// <see cref="LineChannelSecret"/>) are stored plaintext and protected by RBAC (the <c>Settings</c>
|
||||||
|
/// module / super_admin) per the project decision for this small single-VM internal app.
|
||||||
|
/// </summary>
|
||||||
|
public class NotificationSetting : AuditableEntity, IAuditable
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
// ── Email (SMTP) ─────────────────────────────────────────────────────────
|
||||||
|
public bool EnableEmail { get; set; }
|
||||||
|
public string SmtpHost { get; set; } = "";
|
||||||
|
public int SmtpPort { get; set; } = 587;
|
||||||
|
public bool SmtpUseSsl { get; set; } = true; // true → STARTTLS
|
||||||
|
public string SmtpUser { get; set; } = "";
|
||||||
|
public string SmtpPassword { get; set; } = "";
|
||||||
|
public string FromAddress { get; set; } = "";
|
||||||
|
public string FromName { get; set; } = "";
|
||||||
|
|
||||||
|
// ── Line ─────────────────────────────────────────────────────────────────
|
||||||
|
public bool EnableLine { get; set; }
|
||||||
|
public string LineChannelAccessToken { get; set; } = "";
|
||||||
|
public string LineChannelSecret { get; set; } = "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using ROLAC.API.Entities.Base;
|
||||||
|
namespace ROLAC.API.Entities;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Singleton (Id == 1) holding site-wide presentation and locale settings, edited from the
|
||||||
|
/// Church Profile → Site Settings tab (gated by the <c>Settings</c> permission module).
|
||||||
|
/// Seeded with sensible defaults on startup.
|
||||||
|
/// </summary>
|
||||||
|
public class SiteSetting : AuditableEntity, IAuditable
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
public string SiteTitle { get; set; } = "";
|
||||||
|
public string? SiteTitleZh { get; set; }
|
||||||
|
public string DefaultLanguage { get; set; } = "en"; // "en" | "zh"
|
||||||
|
public string TimeZone { get; set; } = "America/Los_Angeles";
|
||||||
|
public string DateFormat { get; set; } = "yyyy-MM-dd";
|
||||||
|
public string Currency { get; set; } = "USD";
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
namespace ROLAC.API.Entities;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A single-use, expiring invitation that lets a member set their own password and log in for
|
||||||
|
/// the first time — without an admin-generated temporary password. The raw token is e-mailed /
|
||||||
|
/// copied to the member; only its SHA-256 hash is stored here (same scheme as RefreshToken).
|
||||||
|
/// </summary>
|
||||||
|
public class UserInvitation
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
public string UserId { get; set; } = null!;
|
||||||
|
public AppUser User { get; set; } = null!;
|
||||||
|
|
||||||
|
/// <summary>SHA-256 hex of the raw invitation token. Never store raw tokens.</summary>
|
||||||
|
public string TokenHash { get; set; } = null!;
|
||||||
|
|
||||||
|
public DateTime ExpiresAt { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Id of the admin who generated the link.</summary>
|
||||||
|
public string CreatedBy { get; set; } = null!;
|
||||||
|
|
||||||
|
/// <summary>Set when the member consumes the link to set their password (single-use).</summary>
|
||||||
|
public DateTime? UsedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Set when superseded by a newer invitation for the same user (re-issue).</summary>
|
||||||
|
public DateTime? RevokedAt { get; set; }
|
||||||
|
|
||||||
|
// Computed helpers — NOT mapped to DB columns (ignored in OnModelCreating)
|
||||||
|
public bool IsExpired => DateTime.UtcNow >= ExpiresAt;
|
||||||
|
public bool IsUsed => UsedAt.HasValue;
|
||||||
|
public bool IsRevoked => RevokedAt.HasValue;
|
||||||
|
public bool IsActive => !IsUsed && !IsRevoked && !IsExpired;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,59 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace ROLAC.API.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddUserInvitations : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "UserInvitations",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<int>(type: "integer", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
UserId = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||||
|
TokenHash = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
|
||||||
|
ExpiresAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
|
||||||
|
CreatedBy = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||||
|
UsedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true),
|
||||||
|
RevokedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_UserInvitations", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_UserInvitations_AspNetUsers_UserId",
|
||||||
|
column: x => x.UserId,
|
||||||
|
principalTable: "AspNetUsers",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_UserInvitations_TokenHash",
|
||||||
|
table: "UserInvitations",
|
||||||
|
column: "TokenHash",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_UserInvitations_UserId",
|
||||||
|
table: "UserInvitations",
|
||||||
|
column: "UserId");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "UserInvitations");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+2202
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,135 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace ROLAC.API.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddForm990FunctionalExpenses : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "DefaultFunctionalClass",
|
||||||
|
table: "Ministries",
|
||||||
|
type: "character varying(20)",
|
||||||
|
maxLength: 20,
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: "Program");
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<int>(
|
||||||
|
name: "Form990LineId",
|
||||||
|
table: "ExpenseSubCategories",
|
||||||
|
type: "integer",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "FunctionalClass",
|
||||||
|
table: "Expenses",
|
||||||
|
type: "character varying(20)",
|
||||||
|
maxLength: 20,
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<int>(
|
||||||
|
name: "Form990LineId",
|
||||||
|
table: "ExpenseCategoryGroups",
|
||||||
|
type: "integer",
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "Form990ExpenseLines",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<int>(type: "integer", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
LineCode = table.Column<string>(type: "character varying(10)", maxLength: 10, nullable: false),
|
||||||
|
Name_en = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||||
|
Name_zh = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
|
||||||
|
SortOrder = table.Column<int>(type: "integer", nullable: false),
|
||||||
|
IsActive = table.Column<bool>(type: "boolean", nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||||
|
CreatedBy = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||||
|
UpdatedBy = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_Form990ExpenseLines", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ExpenseSubCategories_Form990LineId",
|
||||||
|
table: "ExpenseSubCategories",
|
||||||
|
column: "Form990LineId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ExpenseCategoryGroups_Form990LineId",
|
||||||
|
table: "ExpenseCategoryGroups",
|
||||||
|
column: "Form990LineId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_Form990ExpenseLines_LineCode",
|
||||||
|
table: "Form990ExpenseLines",
|
||||||
|
column: "LineCode",
|
||||||
|
unique: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddForeignKey(
|
||||||
|
name: "FK_ExpenseCategoryGroups_Form990ExpenseLines_Form990LineId",
|
||||||
|
table: "ExpenseCategoryGroups",
|
||||||
|
column: "Form990LineId",
|
||||||
|
principalTable: "Form990ExpenseLines",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.SetNull);
|
||||||
|
|
||||||
|
migrationBuilder.AddForeignKey(
|
||||||
|
name: "FK_ExpenseSubCategories_Form990ExpenseLines_Form990LineId",
|
||||||
|
table: "ExpenseSubCategories",
|
||||||
|
column: "Form990LineId",
|
||||||
|
principalTable: "Form990ExpenseLines",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.SetNull);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropForeignKey(
|
||||||
|
name: "FK_ExpenseCategoryGroups_Form990ExpenseLines_Form990LineId",
|
||||||
|
table: "ExpenseCategoryGroups");
|
||||||
|
|
||||||
|
migrationBuilder.DropForeignKey(
|
||||||
|
name: "FK_ExpenseSubCategories_Form990ExpenseLines_Form990LineId",
|
||||||
|
table: "ExpenseSubCategories");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "Form990ExpenseLines");
|
||||||
|
|
||||||
|
migrationBuilder.DropIndex(
|
||||||
|
name: "IX_ExpenseSubCategories_Form990LineId",
|
||||||
|
table: "ExpenseSubCategories");
|
||||||
|
|
||||||
|
migrationBuilder.DropIndex(
|
||||||
|
name: "IX_ExpenseCategoryGroups_Form990LineId",
|
||||||
|
table: "ExpenseCategoryGroups");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "DefaultFunctionalClass",
|
||||||
|
table: "Ministries");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "Form990LineId",
|
||||||
|
table: "ExpenseSubCategories");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "FunctionalClass",
|
||||||
|
table: "Expenses");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "Form990LineId",
|
||||||
|
table: "ExpenseCategoryGroups");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,76 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace ROLAC.API.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddChurchAiSettings : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "AiProvider",
|
||||||
|
table: "ChurchProfiles",
|
||||||
|
type: "character varying(20)",
|
||||||
|
maxLength: 20,
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: "Claude");
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "ClaudeApiKey",
|
||||||
|
table: "ChurchProfiles",
|
||||||
|
type: "character varying(500)",
|
||||||
|
maxLength: 500,
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "ClaudeModel",
|
||||||
|
table: "ChurchProfiles",
|
||||||
|
type: "character varying(100)",
|
||||||
|
maxLength: 100,
|
||||||
|
nullable: true,
|
||||||
|
defaultValue: "claude-haiku-4-5-20251001");
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "GeminiApiKey",
|
||||||
|
table: "ChurchProfiles",
|
||||||
|
type: "character varying(500)",
|
||||||
|
maxLength: 500,
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "GeminiModel",
|
||||||
|
table: "ChurchProfiles",
|
||||||
|
type: "character varying(100)",
|
||||||
|
maxLength: 100,
|
||||||
|
nullable: true,
|
||||||
|
defaultValue: "gemini-2.5-flash-lite");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "AiProvider",
|
||||||
|
table: "ChurchProfiles");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "ClaudeApiKey",
|
||||||
|
table: "ChurchProfiles");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "ClaudeModel",
|
||||||
|
table: "ChurchProfiles");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "GeminiApiKey",
|
||||||
|
table: "ChurchProfiles");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "GeminiModel",
|
||||||
|
table: "ChurchProfiles");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,122 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace ROLAC.API.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddExpenseSnapshots : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "ExpenseSnapshots",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<int>(type: "integer", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
Name = table.Column<string>(type: "character varying(150)", maxLength: 150, nullable: false),
|
||||||
|
MinistryId = table.Column<int>(type: "integer", nullable: false),
|
||||||
|
Description = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
|
||||||
|
VendorName = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
|
||||||
|
CheckNumber = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
|
||||||
|
Notes = table.Column<string>(type: "text", nullable: true),
|
||||||
|
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||||
|
CreatedBy = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||||
|
UpdatedBy = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||||
|
IsDeleted = table.Column<bool>(type: "boolean", nullable: false),
|
||||||
|
DeletedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||||
|
DeletedBy = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: true)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_ExpenseSnapshots", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_ExpenseSnapshots_Ministries_MinistryId",
|
||||||
|
column: x => x.MinistryId,
|
||||||
|
principalTable: "Ministries",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "ExpenseSnapshotLines",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<int>(type: "integer", nullable: false)
|
||||||
|
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||||
|
SnapshotId = table.Column<int>(type: "integer", nullable: false),
|
||||||
|
CategoryGroupId = table.Column<int>(type: "integer", nullable: false),
|
||||||
|
SubCategoryId = table.Column<int>(type: "integer", nullable: false),
|
||||||
|
FunctionalClass = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: true),
|
||||||
|
Amount = table.Column<decimal>(type: "numeric(18,2)", nullable: false),
|
||||||
|
Description = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: true),
|
||||||
|
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||||
|
CreatedBy = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false),
|
||||||
|
UpdatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||||
|
UpdatedBy = table.Column<string>(type: "character varying(450)", maxLength: 450, nullable: false)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_ExpenseSnapshotLines", x => x.Id);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_ExpenseSnapshotLines_ExpenseCategoryGroups_CategoryGroupId",
|
||||||
|
column: x => x.CategoryGroupId,
|
||||||
|
principalTable: "ExpenseCategoryGroups",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Restrict);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_ExpenseSnapshotLines_ExpenseSnapshots_SnapshotId",
|
||||||
|
column: x => x.SnapshotId,
|
||||||
|
principalTable: "ExpenseSnapshots",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Cascade);
|
||||||
|
table.ForeignKey(
|
||||||
|
name: "FK_ExpenseSnapshotLines_ExpenseSubCategories_SubCategoryId",
|
||||||
|
column: x => x.SubCategoryId,
|
||||||
|
principalTable: "ExpenseSubCategories",
|
||||||
|
principalColumn: "Id",
|
||||||
|
onDelete: ReferentialAction.Restrict);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ExpenseSnapshotLines_CategoryGroupId",
|
||||||
|
table: "ExpenseSnapshotLines",
|
||||||
|
column: "CategoryGroupId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ExpenseSnapshotLines_SnapshotId",
|
||||||
|
table: "ExpenseSnapshotLines",
|
||||||
|
column: "SnapshotId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ExpenseSnapshotLines_SubCategoryId",
|
||||||
|
table: "ExpenseSnapshotLines",
|
||||||
|
column: "SubCategoryId");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ExpenseSnapshots_CreatedAt",
|
||||||
|
table: "ExpenseSnapshots",
|
||||||
|
column: "CreatedAt");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_ExpenseSnapshots_MinistryId",
|
||||||
|
table: "ExpenseSnapshots",
|
||||||
|
column: "MinistryId");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "ExpenseSnapshotLines");
|
||||||
|
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "ExpenseSnapshots");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -439,6 +439,13 @@ namespace ROLAC.API.Migrations
|
|||||||
.HasMaxLength(500)
|
.HasMaxLength(500)
|
||||||
.HasColumnType("character varying(500)");
|
.HasColumnType("character varying(500)");
|
||||||
|
|
||||||
|
b.Property<string>("AiProvider")
|
||||||
|
.IsRequired()
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasMaxLength(20)
|
||||||
|
.HasColumnType("character varying(20)")
|
||||||
|
.HasDefaultValue("Claude");
|
||||||
|
|
||||||
b.Property<string>("BankAccountNumber")
|
b.Property<string>("BankAccountNumber")
|
||||||
.HasMaxLength(50)
|
.HasMaxLength(50)
|
||||||
.HasColumnType("character varying(50)");
|
.HasColumnType("character varying(50)");
|
||||||
@@ -455,6 +462,16 @@ namespace ROLAC.API.Migrations
|
|||||||
.HasMaxLength(100)
|
.HasMaxLength(100)
|
||||||
.HasColumnType("character varying(100)");
|
.HasColumnType("character varying(100)");
|
||||||
|
|
||||||
|
b.Property<string>("ClaudeApiKey")
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("character varying(500)");
|
||||||
|
|
||||||
|
b.Property<string>("ClaudeModel")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("character varying(100)")
|
||||||
|
.HasDefaultValue("claude-haiku-4-5-20251001");
|
||||||
|
|
||||||
b.Property<DateTimeOffset>("CreatedAt")
|
b.Property<DateTimeOffset>("CreatedAt")
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
@@ -463,14 +480,36 @@ namespace ROLAC.API.Migrations
|
|||||||
.HasMaxLength(450)
|
.HasMaxLength(450)
|
||||||
.HasColumnType("character varying(450)");
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<string>("Email")
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("GeminiApiKey")
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("character varying(500)");
|
||||||
|
|
||||||
|
b.Property<string>("GeminiModel")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("character varying(100)")
|
||||||
|
.HasDefaultValue("gemini-2.5-flash-lite");
|
||||||
|
|
||||||
b.Property<string>("Name")
|
b.Property<string>("Name")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasMaxLength(200)
|
.HasMaxLength(200)
|
||||||
.HasColumnType("character varying(200)");
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("NameZh")
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
b.Property<int>("NextCheckNumber")
|
b.Property<int>("NextCheckNumber")
|
||||||
.HasColumnType("integer");
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<string>("Phone")
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("character varying(50)");
|
||||||
|
|
||||||
b.Property<string>("State")
|
b.Property<string>("State")
|
||||||
.HasMaxLength(50)
|
.HasMaxLength(50)
|
||||||
.HasColumnType("character varying(50)");
|
.HasColumnType("character varying(50)");
|
||||||
@@ -483,6 +522,10 @@ namespace ROLAC.API.Migrations
|
|||||||
.HasMaxLength(450)
|
.HasMaxLength(450)
|
||||||
.HasColumnType("character varying(450)");
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<string>("Website")
|
||||||
|
.HasMaxLength(300)
|
||||||
|
.HasColumnType("character varying(300)");
|
||||||
|
|
||||||
b.Property<string>("ZipCode")
|
b.Property<string>("ZipCode")
|
||||||
.HasMaxLength(20)
|
.HasMaxLength(20)
|
||||||
.HasColumnType("character varying(20)");
|
.HasColumnType("character varying(20)");
|
||||||
@@ -509,9 +552,6 @@ namespace ROLAC.API.Migrations
|
|||||||
b.Property<decimal>("Amount")
|
b.Property<decimal>("Amount")
|
||||||
.HasColumnType("decimal(18,2)");
|
.HasColumnType("decimal(18,2)");
|
||||||
|
|
||||||
b.Property<int>("CategoryGroupId")
|
|
||||||
.HasColumnType("integer");
|
|
||||||
|
|
||||||
b.Property<string>("CheckNumber")
|
b.Property<string>("CheckNumber")
|
||||||
.HasMaxLength(50)
|
.HasMaxLength(50)
|
||||||
.HasColumnType("character varying(50)");
|
.HasColumnType("character varying(50)");
|
||||||
@@ -580,9 +620,6 @@ namespace ROLAC.API.Migrations
|
|||||||
.HasColumnType("character varying(30)")
|
.HasColumnType("character varying(30)")
|
||||||
.HasDefaultValue("Draft");
|
.HasDefaultValue("Draft");
|
||||||
|
|
||||||
b.Property<int>("SubCategoryId")
|
|
||||||
.HasColumnType("integer");
|
|
||||||
|
|
||||||
b.Property<DateTimeOffset?>("SubmittedAt")
|
b.Property<DateTimeOffset?>("SubmittedAt")
|
||||||
.HasColumnType("timestamp with time zone");
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
@@ -609,8 +646,6 @@ namespace ROLAC.API.Migrations
|
|||||||
|
|
||||||
b.HasKey("Id");
|
b.HasKey("Id");
|
||||||
|
|
||||||
b.HasIndex("CategoryGroupId");
|
|
||||||
|
|
||||||
b.HasIndex("ExpenseDate");
|
b.HasIndex("ExpenseDate");
|
||||||
|
|
||||||
b.HasIndex("MemberId");
|
b.HasIndex("MemberId");
|
||||||
@@ -620,8 +655,6 @@ namespace ROLAC.API.Migrations
|
|||||||
b.HasIndex("Status")
|
b.HasIndex("Status")
|
||||||
.HasFilter("\"IsDeleted\" = false");
|
.HasFilter("\"IsDeleted\" = false");
|
||||||
|
|
||||||
b.HasIndex("SubCategoryId");
|
|
||||||
|
|
||||||
b.ToTable("Expenses");
|
b.ToTable("Expenses");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -641,6 +674,9 @@ namespace ROLAC.API.Migrations
|
|||||||
.HasMaxLength(450)
|
.HasMaxLength(450)
|
||||||
.HasColumnType("character varying(450)");
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<int?>("Form990LineId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
b.Property<bool>("IsActive")
|
b.Property<bool>("IsActive")
|
||||||
.HasColumnType("boolean");
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
@@ -666,9 +702,188 @@ namespace ROLAC.API.Migrations
|
|||||||
|
|
||||||
b.HasKey("Id");
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("Form990LineId");
|
||||||
|
|
||||||
b.ToTable("ExpenseCategoryGroups");
|
b.ToTable("ExpenseCategoryGroups");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseLine", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<decimal>("Amount")
|
||||||
|
.HasColumnType("decimal(18,2)");
|
||||||
|
|
||||||
|
b.Property<int>("CategoryGroupId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("CreatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("character varying(500)");
|
||||||
|
|
||||||
|
b.Property<int>("ExpenseId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<string>("FunctionalClass")
|
||||||
|
.HasMaxLength(20)
|
||||||
|
.HasColumnType("character varying(20)");
|
||||||
|
|
||||||
|
b.Property<int>("SubCategoryId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("UpdatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("UpdatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("CategoryGroupId");
|
||||||
|
|
||||||
|
b.HasIndex("ExpenseId");
|
||||||
|
|
||||||
|
b.HasIndex("SubCategoryId");
|
||||||
|
|
||||||
|
b.ToTable("ExpenseLines");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseSnapshot", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<string>("CheckNumber")
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("character varying(50)");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("CreatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("DeletedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("DeletedBy")
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("character varying(500)");
|
||||||
|
|
||||||
|
b.Property<bool>("IsDeleted")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<int>("MinistryId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(150)
|
||||||
|
.HasColumnType("character varying(150)");
|
||||||
|
|
||||||
|
b.Property<string>("Notes")
|
||||||
|
.HasColumnType("text");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("UpdatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("UpdatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<string>("VendorName")
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("CreatedAt");
|
||||||
|
|
||||||
|
b.HasIndex("MinistryId");
|
||||||
|
|
||||||
|
b.ToTable("ExpenseSnapshots");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseSnapshotLine", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<decimal>("Amount")
|
||||||
|
.HasColumnType("decimal(18,2)");
|
||||||
|
|
||||||
|
b.Property<int>("CategoryGroupId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("CreatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<string>("Description")
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("character varying(500)");
|
||||||
|
|
||||||
|
b.Property<string>("FunctionalClass")
|
||||||
|
.HasMaxLength(20)
|
||||||
|
.HasColumnType("character varying(20)");
|
||||||
|
|
||||||
|
b.Property<int>("SnapshotId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<int>("SubCategoryId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("UpdatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("UpdatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("CategoryGroupId");
|
||||||
|
|
||||||
|
b.HasIndex("SnapshotId");
|
||||||
|
|
||||||
|
b.HasIndex("SubCategoryId");
|
||||||
|
|
||||||
|
b.ToTable("ExpenseSnapshotLines");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("ROLAC.API.Entities.ExpenseSubCategory", b =>
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseSubCategory", b =>
|
||||||
{
|
{
|
||||||
b.Property<int>("Id")
|
b.Property<int>("Id")
|
||||||
@@ -685,6 +900,9 @@ namespace ROLAC.API.Migrations
|
|||||||
.HasMaxLength(450)
|
.HasMaxLength(450)
|
||||||
.HasColumnType("character varying(450)");
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<int?>("Form990LineId")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
b.Property<int>("GroupId")
|
b.Property<int>("GroupId")
|
||||||
.HasColumnType("integer");
|
.HasColumnType("integer");
|
||||||
|
|
||||||
@@ -713,6 +931,8 @@ namespace ROLAC.API.Migrations
|
|||||||
|
|
||||||
b.HasKey("Id");
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("Form990LineId");
|
||||||
|
|
||||||
b.HasIndex("GroupId");
|
b.HasIndex("GroupId");
|
||||||
|
|
||||||
b.ToTable("ExpenseSubCategories");
|
b.ToTable("ExpenseSubCategories");
|
||||||
@@ -756,6 +976,58 @@ namespace ROLAC.API.Migrations
|
|||||||
b.ToTable("FamilyUnits");
|
b.ToTable("FamilyUnits");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.Form990ExpenseLine", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("CreatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<bool>("IsActive")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<string>("LineCode")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(10)
|
||||||
|
.HasColumnType("character varying(10)");
|
||||||
|
|
||||||
|
b.Property<string>("Name_en")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("Name_zh")
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<int>("SortOrder")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("UpdatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("UpdatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("LineCode")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("Form990ExpenseLines");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("ROLAC.API.Entities.Giving", b =>
|
modelBuilder.Entity("ROLAC.API.Entities.Giving", b =>
|
||||||
{
|
{
|
||||||
b.Property<int>("Id")
|
b.Property<int>("Id")
|
||||||
@@ -1124,6 +1396,10 @@ namespace ROLAC.API.Migrations
|
|||||||
.HasMaxLength(200)
|
.HasMaxLength(200)
|
||||||
.HasColumnType("character varying(200)");
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("Entity")
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
b.Property<int?>("FamilyUnitId")
|
b.Property<int?>("FamilyUnitId")
|
||||||
.HasColumnType("integer");
|
.HasColumnType("integer");
|
||||||
|
|
||||||
@@ -1225,6 +1501,13 @@ namespace ROLAC.API.Migrations
|
|||||||
|
|
||||||
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<string>("DefaultFunctionalClass")
|
||||||
|
.IsRequired()
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasMaxLength(20)
|
||||||
|
.HasColumnType("character varying(20)")
|
||||||
|
.HasDefaultValue("Program");
|
||||||
|
|
||||||
b.Property<string>("Description_en")
|
b.Property<string>("Description_en")
|
||||||
.HasColumnType("text");
|
.HasColumnType("text");
|
||||||
|
|
||||||
@@ -1323,6 +1606,82 @@ namespace ROLAC.API.Migrations
|
|||||||
b.ToTable("MonthlyStatements");
|
b.ToTable("MonthlyStatements");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.NotificationSetting", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("CreatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<bool>("EnableEmail")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<bool>("EnableLine")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<string>("FromAddress")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("FromName")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("LineChannelAccessToken")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("character varying(500)");
|
||||||
|
|
||||||
|
b.Property<string>("LineChannelSecret")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("SmtpHost")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("SmtpPassword")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("character varying(500)");
|
||||||
|
|
||||||
|
b.Property<int>("SmtpPort")
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
b.Property<bool>("SmtpUseSsl")
|
||||||
|
.HasColumnType("boolean");
|
||||||
|
|
||||||
|
b.Property<string>("SmtpUser")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("UpdatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("UpdatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("NotificationSettings");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("ROLAC.API.Entities.Notifications.LineBindingCode", b =>
|
modelBuilder.Entity("ROLAC.API.Entities.Notifications.LineBindingCode", b =>
|
||||||
{
|
{
|
||||||
b.Property<int>("Id")
|
b.Property<int>("Id")
|
||||||
@@ -1653,6 +2012,109 @@ namespace ROLAC.API.Migrations
|
|||||||
b.ToTable("RolePermissions");
|
b.ToTable("RolePermissions");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.SiteSetting", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("CreatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<string>("Currency")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(10)
|
||||||
|
.HasColumnType("character varying(10)");
|
||||||
|
|
||||||
|
b.Property<string>("DateFormat")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(50)
|
||||||
|
.HasColumnType("character varying(50)");
|
||||||
|
|
||||||
|
b.Property<string>("DefaultLanguage")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(10)
|
||||||
|
.HasColumnType("character varying(10)");
|
||||||
|
|
||||||
|
b.Property<string>("SiteTitle")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("SiteTitleZh")
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)");
|
||||||
|
|
||||||
|
b.Property<string>("TimeZone")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("character varying(100)");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("UpdatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("UpdatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("SiteSettings");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.UserInvitation", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("integer");
|
||||||
|
|
||||||
|
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("CreatedBy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.Property<DateTime>("ExpiresAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("RevokedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("TokenHash")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("character varying(64)");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("UsedAt")
|
||||||
|
.HasColumnType("timestamp with time zone");
|
||||||
|
|
||||||
|
b.Property<string>("UserId")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(450)
|
||||||
|
.HasColumnType("character varying(450)");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("TokenHash")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.HasIndex("UserId");
|
||||||
|
|
||||||
|
b.ToTable("UserInvitations");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
|
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("ROLAC.API.Entities.AppRole", null)
|
b.HasOne("ROLAC.API.Entities.AppRole", null)
|
||||||
@@ -1735,12 +2197,6 @@ namespace ROLAC.API.Migrations
|
|||||||
|
|
||||||
modelBuilder.Entity("ROLAC.API.Entities.Expense", b =>
|
modelBuilder.Entity("ROLAC.API.Entities.Expense", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("ROLAC.API.Entities.ExpenseCategoryGroup", "CategoryGroup")
|
|
||||||
.WithMany()
|
|
||||||
.HasForeignKey("CategoryGroupId")
|
|
||||||
.OnDelete(DeleteBehavior.Restrict)
|
|
||||||
.IsRequired();
|
|
||||||
|
|
||||||
b.HasOne("ROLAC.API.Entities.Member", "Member")
|
b.HasOne("ROLAC.API.Entities.Member", "Member")
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey("MemberId")
|
.HasForeignKey("MemberId")
|
||||||
@@ -1752,6 +2208,35 @@ namespace ROLAC.API.Migrations
|
|||||||
.OnDelete(DeleteBehavior.Restrict)
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
.IsRequired();
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Member");
|
||||||
|
|
||||||
|
b.Navigation("Ministry");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseCategoryGroup", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("ROLAC.API.Entities.Form990ExpenseLine", "Form990Line")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("Form990LineId")
|
||||||
|
.OnDelete(DeleteBehavior.SetNull);
|
||||||
|
|
||||||
|
b.Navigation("Form990Line");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseLine", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("ROLAC.API.Entities.ExpenseCategoryGroup", "CategoryGroup")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("CategoryGroupId")
|
||||||
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("ROLAC.API.Entities.Expense", "Expense")
|
||||||
|
.WithMany("Lines")
|
||||||
|
.HasForeignKey("ExpenseId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
b.HasOne("ROLAC.API.Entities.ExpenseSubCategory", "SubCategory")
|
b.HasOne("ROLAC.API.Entities.ExpenseSubCategory", "SubCategory")
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey("SubCategoryId")
|
.HasForeignKey("SubCategoryId")
|
||||||
@@ -1760,21 +2245,64 @@ namespace ROLAC.API.Migrations
|
|||||||
|
|
||||||
b.Navigation("CategoryGroup");
|
b.Navigation("CategoryGroup");
|
||||||
|
|
||||||
b.Navigation("Member");
|
b.Navigation("Expense");
|
||||||
|
|
||||||
|
b.Navigation("SubCategory");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseSnapshot", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("ROLAC.API.Entities.Ministry", "Ministry")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("MinistryId")
|
||||||
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
b.Navigation("Ministry");
|
b.Navigation("Ministry");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseSnapshotLine", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("ROLAC.API.Entities.ExpenseCategoryGroup", "CategoryGroup")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("CategoryGroupId")
|
||||||
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("ROLAC.API.Entities.ExpenseSnapshot", "Snapshot")
|
||||||
|
.WithMany("Lines")
|
||||||
|
.HasForeignKey("SnapshotId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.HasOne("ROLAC.API.Entities.ExpenseSubCategory", "SubCategory")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("SubCategoryId")
|
||||||
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("CategoryGroup");
|
||||||
|
|
||||||
|
b.Navigation("Snapshot");
|
||||||
|
|
||||||
b.Navigation("SubCategory");
|
b.Navigation("SubCategory");
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("ROLAC.API.Entities.ExpenseSubCategory", b =>
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseSubCategory", b =>
|
||||||
{
|
{
|
||||||
|
b.HasOne("ROLAC.API.Entities.Form990ExpenseLine", "Form990Line")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("Form990LineId")
|
||||||
|
.OnDelete(DeleteBehavior.SetNull);
|
||||||
|
|
||||||
b.HasOne("ROLAC.API.Entities.ExpenseCategoryGroup", "Group")
|
b.HasOne("ROLAC.API.Entities.ExpenseCategoryGroup", "Group")
|
||||||
.WithMany("SubCategories")
|
.WithMany("SubCategories")
|
||||||
.HasForeignKey("GroupId")
|
.HasForeignKey("GroupId")
|
||||||
.OnDelete(DeleteBehavior.Restrict)
|
.OnDelete(DeleteBehavior.Restrict)
|
||||||
.IsRequired();
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("Form990Line");
|
||||||
|
|
||||||
b.Navigation("Group");
|
b.Navigation("Group");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1874,6 +2402,17 @@ namespace ROLAC.API.Migrations
|
|||||||
b.Navigation("Role");
|
b.Navigation("Role");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.UserInvitation", b =>
|
||||||
|
{
|
||||||
|
b.HasOne("ROLAC.API.Entities.AppUser", "User")
|
||||||
|
.WithMany()
|
||||||
|
.HasForeignKey("UserId")
|
||||||
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
.IsRequired();
|
||||||
|
|
||||||
|
b.Navigation("User");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("ROLAC.API.Entities.AppUser", b =>
|
modelBuilder.Entity("ROLAC.API.Entities.AppUser", b =>
|
||||||
{
|
{
|
||||||
b.Navigation("RefreshTokens");
|
b.Navigation("RefreshTokens");
|
||||||
@@ -1884,11 +2423,21 @@ namespace ROLAC.API.Migrations
|
|||||||
b.Navigation("Lines");
|
b.Navigation("Lines");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.Expense", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Lines");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("ROLAC.API.Entities.ExpenseCategoryGroup", b =>
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseCategoryGroup", b =>
|
||||||
{
|
{
|
||||||
b.Navigation("SubCategories");
|
b.Navigation("SubCategories");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("ROLAC.API.Entities.ExpenseSnapshot", b =>
|
||||||
|
{
|
||||||
|
b.Navigation("Lines");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("ROLAC.API.Entities.OfferingSession", b =>
|
modelBuilder.Entity("ROLAC.API.Entities.OfferingSession", b =>
|
||||||
{
|
{
|
||||||
b.Navigation("Givings");
|
b.Navigation("Givings");
|
||||||
|
|||||||
@@ -144,6 +144,7 @@ builder.Services.AddScoped<ITokenService, TokenService>();
|
|||||||
builder.Services.AddScoped<IAuthService, AuthService>();
|
builder.Services.AddScoped<IAuthService, AuthService>();
|
||||||
builder.Services.AddScoped<IMemberService, MemberService>();
|
builder.Services.AddScoped<IMemberService, MemberService>();
|
||||||
builder.Services.AddScoped<IUserManagementService, UserManagementService>();
|
builder.Services.AddScoped<IUserManagementService, UserManagementService>();
|
||||||
|
builder.Services.AddScoped<IInvitationService, InvitationService>();
|
||||||
builder.Services.AddScoped<IGivingCategoryService, GivingCategoryService>();
|
builder.Services.AddScoped<IGivingCategoryService, GivingCategoryService>();
|
||||||
builder.Services.AddScoped<IGivingService, GivingService>();
|
builder.Services.AddScoped<IGivingService, GivingService>();
|
||||||
builder.Services.AddScoped<IOfferingSessionService, OfferingSessionService>();
|
builder.Services.AddScoped<IOfferingSessionService, OfferingSessionService>();
|
||||||
@@ -152,17 +153,24 @@ builder.Services.AddScoped<ROLAC.API.Services.Storage.IFileStorage,
|
|||||||
ROLAC.API.Services.Storage.LocalDiskFileStorage>();
|
ROLAC.API.Services.Storage.LocalDiskFileStorage>();
|
||||||
builder.Services.AddScoped<IExpenseCategoryService, ExpenseCategoryService>();
|
builder.Services.AddScoped<IExpenseCategoryService, ExpenseCategoryService>();
|
||||||
builder.Services.AddScoped<IExpenseService, ExpenseService>();
|
builder.Services.AddScoped<IExpenseService, ExpenseService>();
|
||||||
|
builder.Services.AddScoped<IExpenseSnapshotService, ExpenseSnapshotService>();
|
||||||
builder.Services.AddScoped<IMonthlyStatementService, MonthlyStatementService>();
|
builder.Services.AddScoped<IMonthlyStatementService, MonthlyStatementService>();
|
||||||
builder.Services.AddScoped<IFinanceDashboardService, FinanceDashboardService>();
|
builder.Services.AddScoped<IFinanceDashboardService, FinanceDashboardService>();
|
||||||
|
builder.Services.AddScoped<IForm990ReportService, Form990ReportService>();
|
||||||
builder.Services.AddScoped<IChurchProfileService, ChurchProfileService>();
|
builder.Services.AddScoped<IChurchProfileService, ChurchProfileService>();
|
||||||
|
builder.Services.AddScoped<ISettingsService, SettingsService>();
|
||||||
builder.Services.AddScoped<IDisbursementService, DisbursementService>();
|
builder.Services.AddScoped<IDisbursementService, DisbursementService>();
|
||||||
builder.Services.AddScoped<ROLAC.API.Services.Disbursement.ICheckPrintService,
|
builder.Services.AddScoped<ROLAC.API.Services.Disbursement.ICheckPrintService,
|
||||||
ROLAC.API.Services.Disbursement.CheckPrintService>();
|
ROLAC.API.Services.Disbursement.CheckPrintService>();
|
||||||
builder.Services.AddScoped<IMealAttendanceService, MealAttendanceService>();
|
builder.Services.AddScoped<IMealAttendanceService, MealAttendanceService>();
|
||||||
|
|
||||||
// ── Notifications (email via SMTP + Line) ──────────────────────────────────
|
// ── Notifications (email via SMTP + Line) ──────────────────────────────────
|
||||||
|
// IOptions binding stays only as the one-time seed/fallback; the runtime source of truth is the
|
||||||
|
// DB-backed NotificationSetting row, read (and hot-reloaded) via INotificationSettingsService.
|
||||||
builder.Services.Configure<ROLAC.API.Services.Notifications.SmtpOptions>(config.GetSection("Smtp"));
|
builder.Services.Configure<ROLAC.API.Services.Notifications.SmtpOptions>(config.GetSection("Smtp"));
|
||||||
builder.Services.Configure<ROLAC.API.Services.Notifications.LineOptions>(config.GetSection("Line"));
|
builder.Services.Configure<ROLAC.API.Services.Notifications.LineOptions>(config.GetSection("Line"));
|
||||||
|
builder.Services.AddSingleton<ROLAC.API.Services.Notifications.INotificationSettingsService,
|
||||||
|
ROLAC.API.Services.Notifications.NotificationSettingsService>();
|
||||||
builder.Services.AddScoped<ROLAC.API.Services.Notifications.ISmtpDispatcher,
|
builder.Services.AddScoped<ROLAC.API.Services.Notifications.ISmtpDispatcher,
|
||||||
ROLAC.API.Services.Notifications.MailKitSmtpDispatcher>();
|
ROLAC.API.Services.Notifications.MailKitSmtpDispatcher>();
|
||||||
builder.Services.AddScoped<ROLAC.API.Services.Notifications.IEmailService,
|
builder.Services.AddScoped<ROLAC.API.Services.Notifications.IEmailService,
|
||||||
@@ -172,6 +180,23 @@ builder.Services.AddScoped<ROLAC.API.Services.Notifications.ILineNotificationSer
|
|||||||
builder.Services.AddHttpClient<ROLAC.API.Services.Notifications.IMessageChannel,
|
builder.Services.AddHttpClient<ROLAC.API.Services.Notifications.IMessageChannel,
|
||||||
ROLAC.API.Services.Notifications.LineMessageChannel>();
|
ROLAC.API.Services.Notifications.LineMessageChannel>();
|
||||||
|
|
||||||
|
// ── AI assist (expense translation + category suggestion) ──────────────────
|
||||||
|
// Backend proxy so the API key stays server-side. Provider + model + key come from the
|
||||||
|
// ChurchProfile DB record (editable via Church Profile → AI 設定); the factory picks Claude
|
||||||
|
// or Gemini per request based on ChurchProfile.AiProvider.
|
||||||
|
builder.Services.AddHttpClient<ROLAC.API.Services.Ai.GeminiExpenseAiService>();
|
||||||
|
builder.Services.AddHttpClient<ROLAC.API.Services.Ai.ClaudeExpenseAiService>();
|
||||||
|
builder.Services.AddScoped<ROLAC.API.Services.Ai.IChurchAiConfigProvider,
|
||||||
|
ROLAC.API.Services.Ai.ChurchAiConfigProvider>();
|
||||||
|
builder.Services.AddScoped<ROLAC.API.Services.Ai.IExpenseAiServiceFactory,
|
||||||
|
ROLAC.API.Services.Ai.ExpenseAiServiceFactory>();
|
||||||
|
|
||||||
|
// Category-mapping AI (define a 大項/小項: refine name + translate + suggest Form 990 line).
|
||||||
|
builder.Services.AddHttpClient<ROLAC.API.Services.Ai.GeminiExpenseCategoryAiService>();
|
||||||
|
builder.Services.AddHttpClient<ROLAC.API.Services.Ai.ClaudeExpenseCategoryAiService>();
|
||||||
|
builder.Services.AddScoped<ROLAC.API.Services.Ai.IExpenseCategoryAiServiceFactory,
|
||||||
|
ROLAC.API.Services.Ai.ExpenseCategoryAiServiceFactory>();
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Configurable role-based permissions (RBAC matrix)
|
// Configurable role-based permissions (RBAC matrix)
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>Active AI configuration resolved from the ChurchProfile singleton (blanks filled with defaults).</summary>
|
||||||
|
public sealed record ChurchAiConfig(
|
||||||
|
string Provider,
|
||||||
|
string ClaudeModel, string? ClaudeApiKey,
|
||||||
|
string GeminiModel, string? GeminiApiKey);
|
||||||
|
|
||||||
|
/// <summary>Reads the church's AI settings from the database for the current request.</summary>
|
||||||
|
public interface IChurchAiConfigProvider
|
||||||
|
{
|
||||||
|
Task<ChurchAiConfig> GetAsync(CancellationToken ct = default);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using ROLAC.API.Data;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Loads AI settings from the singleton <c>ChurchProfile</c> row, substituting default model names
|
||||||
|
/// for any blank field so a freshly migrated install still names a valid model. The API keys are
|
||||||
|
/// passed through as-is (null when unset → the calling service treats AI as disabled).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ChurchAiConfigProvider : IChurchAiConfigProvider
|
||||||
|
{
|
||||||
|
private const string DefaultClaudeModel = "claude-haiku-4-5-20251001";
|
||||||
|
private const string DefaultGeminiModel = "gemini-2.5-flash-lite";
|
||||||
|
|
||||||
|
private readonly AppDbContext _db;
|
||||||
|
public ChurchAiConfigProvider(AppDbContext db) => _db = db;
|
||||||
|
|
||||||
|
public async Task<ChurchAiConfig> GetAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var p = await _db.ChurchProfiles.AsNoTracking().OrderBy(x => x.Id).FirstOrDefaultAsync(ct);
|
||||||
|
|
||||||
|
var provider = string.IsNullOrWhiteSpace(p?.AiProvider) ? "Claude" : p.AiProvider;
|
||||||
|
var claudeModel = string.IsNullOrWhiteSpace(p?.ClaudeModel) ? DefaultClaudeModel : p!.ClaudeModel!;
|
||||||
|
var geminiModel = string.IsNullOrWhiteSpace(p?.GeminiModel) ? DefaultGeminiModel : p!.GeminiModel!;
|
||||||
|
|
||||||
|
return new ChurchAiConfig(provider, claudeModel, p?.ClaudeApiKey, geminiModel, p?.GeminiApiKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using ROLAC.API.Data;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Translates and classifies an expense via the Anthropic Claude Messages API. It forces a single
|
||||||
|
/// tool call (<c>tool_choice</c> → <c>classify_expense</c>) whose <c>input_schema</c> matches our
|
||||||
|
/// answer shape, so the model returns structured JSON in a <c>tool_use</c> block. The catalog,
|
||||||
|
/// prompt, and id validation come from <see cref="ExpenseAiServiceBase"/>; this class only owns the
|
||||||
|
/// Claude HTTP call + parse. Forced tool use works on every Claude model, so the configured
|
||||||
|
/// model can be swapped (e.g. to a cheaper model) without code changes.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ClaudeExpenseAiService : ExpenseAiServiceBase
|
||||||
|
{
|
||||||
|
private const string BaseUrl = "https://api.anthropic.com/v1";
|
||||||
|
private const string AnthropicVersion = "2023-06-01";
|
||||||
|
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
private readonly IChurchAiConfigProvider _config;
|
||||||
|
private readonly ILogger<ClaudeExpenseAiService> _logger;
|
||||||
|
|
||||||
|
public ClaudeExpenseAiService(
|
||||||
|
HttpClient http,
|
||||||
|
IChurchAiConfigProvider config,
|
||||||
|
AppDbContext db,
|
||||||
|
ILogger<ClaudeExpenseAiService> logger)
|
||||||
|
: base(db)
|
||||||
|
{
|
||||||
|
_http = http;
|
||||||
|
_config = config;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task<ModelAnswer?> CallModelAsync(string prompt, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var cfg = await _config.GetAsync(ct);
|
||||||
|
if (string.IsNullOrWhiteSpace(cfg.ClaudeApiKey))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Claude API key is not configured; expense AI assist is disabled.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var payload = new
|
||||||
|
{
|
||||||
|
model = cfg.ClaudeModel,
|
||||||
|
max_tokens = 1024,
|
||||||
|
tools = new[]
|
||||||
|
{
|
||||||
|
new
|
||||||
|
{
|
||||||
|
name = "classify_expense",
|
||||||
|
description = "Record the English translation and the chosen expense category ids for the expense.",
|
||||||
|
input_schema = new
|
||||||
|
{
|
||||||
|
type = "object",
|
||||||
|
properties = new
|
||||||
|
{
|
||||||
|
chineseDescription = new { type = "string" },
|
||||||
|
englishDescription = new { type = "string" },
|
||||||
|
groupId = new { type = "integer" },
|
||||||
|
subCategoryId = new { type = "integer" },
|
||||||
|
confidence = new { type = "number" },
|
||||||
|
},
|
||||||
|
required = new[] { "chineseDescription", "englishDescription", "groupId", "subCategoryId", "confidence" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
tool_choice = new { type = "tool", name = "classify_expense" },
|
||||||
|
messages = new[]
|
||||||
|
{
|
||||||
|
new { role = "user", content = prompt },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
var url = $"{BaseUrl}/messages";
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, url)
|
||||||
|
{
|
||||||
|
Content = JsonContent.Create(payload),
|
||||||
|
};
|
||||||
|
request.Headers.Add("x-api-key", cfg.ClaudeApiKey);
|
||||||
|
request.Headers.Add("anthropic-version", AnthropicVersion);
|
||||||
|
|
||||||
|
using var response = await _http.SendAsync(request, ct);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var body = await response.Content.ReadAsStringAsync(ct);
|
||||||
|
_logger.LogWarning("Claude returned {Status}: {Body}", (int)response.StatusCode, body);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The forced tool call lands in content[] as a tool_use block; its `input` is our object.
|
||||||
|
using var doc = JsonDocument.Parse(await response.Content.ReadAsStreamAsync(ct));
|
||||||
|
foreach (var block in doc.RootElement.GetProperty("content").EnumerateArray())
|
||||||
|
{
|
||||||
|
if (block.GetProperty("type").GetString() != "tool_use") continue;
|
||||||
|
|
||||||
|
var parsed = block.GetProperty("input").Deserialize<ClaudeAnswer>(
|
||||||
|
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||||
|
if (parsed is null) return null;
|
||||||
|
|
||||||
|
return new ModelAnswer(parsed.EnglishDescription, parsed.ChineseDescription, parsed.GroupId, parsed.SubCategoryId, parsed.Confidence);
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogWarning("Claude response contained no tool_use block.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Claude expense AI assist failed.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shape of the classify_expense tool input the model fills in.</summary>
|
||||||
|
private sealed class ClaudeAnswer
|
||||||
|
{
|
||||||
|
public string? EnglishDescription { get; set; }
|
||||||
|
public string? ChineseDescription { get; set; }
|
||||||
|
public int GroupId { get; set; }
|
||||||
|
public int SubCategoryId { get; set; }
|
||||||
|
public double Confidence { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using ROLAC.API.Data;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Refines, translates, and maps an expense category to a Form 990 line via the Anthropic Claude
|
||||||
|
/// Messages API. It forces a single tool call (<c>tool_choice</c> → <c>map_category</c>) whose
|
||||||
|
/// <c>input_schema</c> matches our answer shape, so the model returns structured JSON in a
|
||||||
|
/// <c>tool_use</c> block. The catalog, prompt, and id validation come from
|
||||||
|
/// <see cref="ExpenseCategoryAiServiceBase"/>; this class only owns the Claude HTTP call + parse.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ClaudeExpenseCategoryAiService : ExpenseCategoryAiServiceBase
|
||||||
|
{
|
||||||
|
private const string BaseUrl = "https://api.anthropic.com/v1";
|
||||||
|
private const string AnthropicVersion = "2023-06-01";
|
||||||
|
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
private readonly IChurchAiConfigProvider _config;
|
||||||
|
private readonly ILogger<ClaudeExpenseCategoryAiService> _logger;
|
||||||
|
|
||||||
|
public ClaudeExpenseCategoryAiService(
|
||||||
|
HttpClient http,
|
||||||
|
IChurchAiConfigProvider config,
|
||||||
|
AppDbContext db,
|
||||||
|
ILogger<ClaudeExpenseCategoryAiService> logger)
|
||||||
|
: base(db)
|
||||||
|
{
|
||||||
|
_http = http;
|
||||||
|
_config = config;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task<ModelAnswer?> CallModelAsync(string prompt, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var cfg = await _config.GetAsync(ct);
|
||||||
|
if (string.IsNullOrWhiteSpace(cfg.ClaudeApiKey))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Claude API key is not configured; category AI assist is disabled.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var payload = new
|
||||||
|
{
|
||||||
|
model = cfg.ClaudeModel,
|
||||||
|
max_tokens = 1024,
|
||||||
|
tools = new[]
|
||||||
|
{
|
||||||
|
new
|
||||||
|
{
|
||||||
|
name = "map_category",
|
||||||
|
description = "Record the refined Chinese name, English translation, and chosen Form 990 line id for the expense category.",
|
||||||
|
input_schema = new
|
||||||
|
{
|
||||||
|
type = "object",
|
||||||
|
properties = new
|
||||||
|
{
|
||||||
|
chineseName = new { type = "string" },
|
||||||
|
englishName = new { type = "string" },
|
||||||
|
form990LineId = new { type = "integer" },
|
||||||
|
confidence = new { type = "number" },
|
||||||
|
},
|
||||||
|
required = new[] { "chineseName", "englishName", "form990LineId", "confidence" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
tool_choice = new { type = "tool", name = "map_category" },
|
||||||
|
messages = new[]
|
||||||
|
{
|
||||||
|
new { role = "user", content = prompt },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
var url = $"{BaseUrl}/messages";
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, url)
|
||||||
|
{
|
||||||
|
Content = JsonContent.Create(payload),
|
||||||
|
};
|
||||||
|
request.Headers.Add("x-api-key", cfg.ClaudeApiKey);
|
||||||
|
request.Headers.Add("anthropic-version", AnthropicVersion);
|
||||||
|
|
||||||
|
using var response = await _http.SendAsync(request, ct);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var body = await response.Content.ReadAsStringAsync(ct);
|
||||||
|
_logger.LogWarning("Claude returned {Status}: {Body}", (int)response.StatusCode, body);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The forced tool call lands in content[] as a tool_use block; its `input` is our object.
|
||||||
|
using var doc = JsonDocument.Parse(await response.Content.ReadAsStreamAsync(ct));
|
||||||
|
foreach (var block in doc.RootElement.GetProperty("content").EnumerateArray())
|
||||||
|
{
|
||||||
|
if (block.GetProperty("type").GetString() != "tool_use") continue;
|
||||||
|
|
||||||
|
var parsed = block.GetProperty("input").Deserialize<ClaudeAnswer>(
|
||||||
|
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||||
|
if (parsed is null) return null;
|
||||||
|
|
||||||
|
return new ModelAnswer(parsed.ChineseName, parsed.EnglishName, parsed.Form990LineId, parsed.Confidence);
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogWarning("Claude response contained no tool_use block.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Claude category AI assist failed.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shape of the map_category tool input the model fills in.</summary>
|
||||||
|
private sealed class ClaudeAnswer
|
||||||
|
{
|
||||||
|
public string? ChineseName { get; set; }
|
||||||
|
public string? EnglishName { get; set; }
|
||||||
|
public int? Form990LineId { get; set; }
|
||||||
|
public double Confidence { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using ROLAC.API.Data;
|
||||||
|
using ROLAC.API.DTOs.Expense;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Provider-independent expense-AI logic: loads the active category catalog, builds the
|
||||||
|
/// classification prompt, and validates the model's chosen ids against that catalog. Concrete
|
||||||
|
/// providers (Gemini, Claude) only implement <see cref="CallModelAsync"/> — the HTTP call plus
|
||||||
|
/// response parsing — so the catalog/prompt/validation code lives in exactly one place.
|
||||||
|
/// </summary>
|
||||||
|
public abstract class ExpenseAiServiceBase : IExpenseAiService
|
||||||
|
{
|
||||||
|
private readonly AppDbContext _db;
|
||||||
|
|
||||||
|
protected ExpenseAiServiceBase(AppDbContext db) => _db = db;
|
||||||
|
|
||||||
|
/// <summary>One sub-category in the catalog passed to the model.</summary>
|
||||||
|
protected sealed record CatalogSub(int Id, string NameEn, string? NameZh);
|
||||||
|
|
||||||
|
/// <summary>One major category (with its sub-categories) in the catalog passed to the model.</summary>
|
||||||
|
protected sealed record CatalogGroup(int Id, string NameEn, string? NameZh, IReadOnlyList<CatalogSub> Subs);
|
||||||
|
|
||||||
|
/// <summary>The model's raw answer, before its ids are validated against the catalog.</summary>
|
||||||
|
protected sealed record ModelAnswer(
|
||||||
|
string? EnglishDescription, string? ChineseDescription, int GroupId, int SubCategoryId, double Confidence);
|
||||||
|
|
||||||
|
public async Task<ExpenseAiSuggestion> SuggestAsync(string chineseText, decimal amount, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var catalog = await LoadCatalogAsync(ct);
|
||||||
|
var prompt = BuildPrompt(chineseText, amount, catalog);
|
||||||
|
|
||||||
|
var answer = await CallModelAsync(prompt, ct);
|
||||||
|
if (answer is null) return new ExpenseAiSuggestion();
|
||||||
|
|
||||||
|
return BuildSuggestion(answer, catalog);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Call the provider's API with <paramref name="prompt"/> and return its parsed answer, or null
|
||||||
|
/// on any failure (missing key, HTTP error, unparseable response). Implementations must not throw.
|
||||||
|
/// </summary>
|
||||||
|
protected abstract Task<ModelAnswer?> CallModelAsync(string prompt, CancellationToken ct);
|
||||||
|
|
||||||
|
private async Task<List<CatalogGroup>> LoadCatalogAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
return await _db.ExpenseCategoryGroups
|
||||||
|
.AsNoTracking()
|
||||||
|
.Where(group => group.IsActive)
|
||||||
|
.OrderBy(group => group.SortOrder)
|
||||||
|
.Select(group => new CatalogGroup(
|
||||||
|
group.Id,
|
||||||
|
group.Name_en,
|
||||||
|
group.Name_zh,
|
||||||
|
group.SubCategories
|
||||||
|
.Where(sub => sub.IsActive)
|
||||||
|
.OrderBy(sub => sub.SortOrder)
|
||||||
|
.Select(sub => new CatalogSub(sub.Id, sub.Name_en, sub.Name_zh))
|
||||||
|
.ToList()))
|
||||||
|
.ToListAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildPrompt(string chineseText, decimal amount, List<CatalogGroup> catalog)
|
||||||
|
{
|
||||||
|
var catalogJson = JsonSerializer.Serialize(catalog);
|
||||||
|
return
|
||||||
|
"You are a bookkeeping assistant for a church. Given an expense description (often in " +
|
||||||
|
"Traditional Chinese) and its amount, do three things:\n" +
|
||||||
|
"1. Correct any typos in the description and refine it into natural Traditional Chinese — " +
|
||||||
|
"return it as chineseDescription.\n" +
|
||||||
|
"2. Translate that into concise, natural accounting English (a short noun phrase, not a " +
|
||||||
|
"full sentence) — return it as englishDescription.\n" +
|
||||||
|
"3. Choose the single best matching major category (group) and sub-category from the catalog " +
|
||||||
|
"below. You MUST pick a groupId and subCategoryId that appear in the catalog, and the " +
|
||||||
|
"subCategoryId must belong to that groupId. If nothing fits well, choose the closest " +
|
||||||
|
"\"Other / 其他\" option and lower your confidence.\n\n" +
|
||||||
|
$"Expense description: {chineseText}\n" +
|
||||||
|
$"Amount: {amount}\n\n" +
|
||||||
|
$"Category catalog (JSON; each group has an Id, English/Chinese names, and its Subs):\n{catalogJson}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ExpenseAiSuggestion BuildSuggestion(ModelAnswer answer, List<CatalogGroup> catalog)
|
||||||
|
{
|
||||||
|
var suggestion = new ExpenseAiSuggestion
|
||||||
|
{
|
||||||
|
EnglishDescription = string.IsNullOrWhiteSpace(answer.EnglishDescription)
|
||||||
|
? null
|
||||||
|
: answer.EnglishDescription.Trim(),
|
||||||
|
ChineseDescription = string.IsNullOrWhiteSpace(answer.ChineseDescription)
|
||||||
|
? null
|
||||||
|
: answer.ChineseDescription.Trim(),
|
||||||
|
Confidence = answer.Confidence,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Re-validate the returned ids against the catalog; drop anything that doesn't line up
|
||||||
|
// (defends against a hallucinated id, or a sub-category that doesn't belong to the group).
|
||||||
|
var group = catalog.FirstOrDefault(candidate => candidate.Id == answer.GroupId);
|
||||||
|
if (group is not null)
|
||||||
|
{
|
||||||
|
suggestion.GroupId = group.Id;
|
||||||
|
suggestion.GroupLabel = Label(group.NameEn, group.NameZh);
|
||||||
|
|
||||||
|
var sub = group.Subs.FirstOrDefault(candidate => candidate.Id == answer.SubCategoryId);
|
||||||
|
if (sub is not null)
|
||||||
|
{
|
||||||
|
suggestion.SubCategoryId = sub.Id;
|
||||||
|
suggestion.SubLabel = Label(sub.NameEn, sub.NameZh);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return suggestion;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Mirror the frontend's bilingual() convention: "English / 中文" (or just English).</summary>
|
||||||
|
private static string Label(string nameEn, string? nameZh)
|
||||||
|
=> string.IsNullOrWhiteSpace(nameZh) ? nameEn : $"{nameEn} / {nameZh}";
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>Selects the active expense-AI provider per request from <c>ChurchProfile.AiProvider</c>.</summary>
|
||||||
|
public interface IExpenseAiServiceFactory
|
||||||
|
{
|
||||||
|
Task<IExpenseAiService> ResolveAsync(CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ExpenseAiServiceFactory : IExpenseAiServiceFactory
|
||||||
|
{
|
||||||
|
private readonly IChurchAiConfigProvider _config;
|
||||||
|
private readonly ClaudeExpenseAiService _claude;
|
||||||
|
private readonly GeminiExpenseAiService _gemini;
|
||||||
|
|
||||||
|
public ExpenseAiServiceFactory(
|
||||||
|
IChurchAiConfigProvider config,
|
||||||
|
ClaudeExpenseAiService claude,
|
||||||
|
GeminiExpenseAiService gemini)
|
||||||
|
{
|
||||||
|
_config = config;
|
||||||
|
_claude = claude;
|
||||||
|
_gemini = gemini;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IExpenseAiService> ResolveAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var cfg = await _config.GetAsync(ct);
|
||||||
|
return cfg.Provider.Equals("Gemini", StringComparison.OrdinalIgnoreCase) ? _gemini : _claude;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using ROLAC.API.Data;
|
||||||
|
using ROLAC.API.DTOs.Expense;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Provider-independent category-AI logic: loads the active Form 990 line catalog, builds the
|
||||||
|
/// mapping prompt, and validates the model's chosen line id against that catalog. Concrete providers
|
||||||
|
/// (Gemini, Claude) only implement <see cref="CallModelAsync"/> — the HTTP call plus response parsing —
|
||||||
|
/// so the catalog/prompt/validation code lives in exactly one place. Mirrors
|
||||||
|
/// <see cref="ExpenseAiServiceBase"/>, which does the same for the expense-entry classification task.
|
||||||
|
/// </summary>
|
||||||
|
public abstract class ExpenseCategoryAiServiceBase : IExpenseCategoryAiService
|
||||||
|
{
|
||||||
|
private readonly AppDbContext _db;
|
||||||
|
|
||||||
|
protected ExpenseCategoryAiServiceBase(AppDbContext db) => _db = db;
|
||||||
|
|
||||||
|
/// <summary>One Form 990 line in the catalog passed to the model.</summary>
|
||||||
|
protected sealed record CatalogLine(int Id, string LineCode, string NameEn, string? NameZh);
|
||||||
|
|
||||||
|
/// <summary>The model's raw answer, before its line id is validated against the catalog.</summary>
|
||||||
|
protected sealed record ModelAnswer(string? ChineseName, string? EnglishName, int? Form990LineId, double Confidence);
|
||||||
|
|
||||||
|
public async Task<CategoryAiSuggestion> SuggestAsync(ExpenseCategoryAiRequest request, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var catalog = await LoadCatalogAsync(ct);
|
||||||
|
var prompt = BuildPrompt(request, catalog);
|
||||||
|
|
||||||
|
var answer = await CallModelAsync(prompt, ct);
|
||||||
|
if (answer is null) return new CategoryAiSuggestion();
|
||||||
|
|
||||||
|
return BuildSuggestion(answer, catalog);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Call the provider's API with <paramref name="prompt"/> and return its parsed answer, or null
|
||||||
|
/// on any failure (missing key, HTTP error, unparseable response). Implementations must not throw.
|
||||||
|
/// </summary>
|
||||||
|
protected abstract Task<ModelAnswer?> CallModelAsync(string prompt, CancellationToken ct);
|
||||||
|
|
||||||
|
private async Task<List<CatalogLine>> LoadCatalogAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
return await _db.Form990ExpenseLines
|
||||||
|
.AsNoTracking()
|
||||||
|
.Where(line => line.IsActive)
|
||||||
|
.OrderBy(line => line.SortOrder)
|
||||||
|
.Select(line => new CatalogLine(line.Id, line.LineCode, line.Name_en, line.Name_zh))
|
||||||
|
.ToListAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildPrompt(ExpenseCategoryAiRequest request, List<CatalogLine> catalog)
|
||||||
|
{
|
||||||
|
var catalogJson = JsonSerializer.Serialize(catalog);
|
||||||
|
var levelLabel = request.Level.Equals("sub", StringComparison.OrdinalIgnoreCase)
|
||||||
|
? "sub-category (小項)"
|
||||||
|
: "major category (大項)";
|
||||||
|
|
||||||
|
var context = new StringBuilder();
|
||||||
|
context.Append($"This is an expense {levelLabel} in a church's bookkeeping chart of accounts.\n");
|
||||||
|
if (!string.IsNullOrWhiteSpace(request.Name_zh))
|
||||||
|
context.Append($"Chinese name entered: {request.Name_zh}\n");
|
||||||
|
if (!string.IsNullOrWhiteSpace(request.Name_en))
|
||||||
|
context.Append($"English name entered: {request.Name_en}\n");
|
||||||
|
if (!string.IsNullOrWhiteSpace(request.ParentGroupName))
|
||||||
|
context.Append($"It belongs under the parent major category: {request.ParentGroupName}\n");
|
||||||
|
if (request.ParentForm990LineId is int parentLineId)
|
||||||
|
context.Append(
|
||||||
|
$"The parent major category is mapped to Form 990 line id {parentLineId}; prefer a consistent " +
|
||||||
|
"choice unless a more specific line clearly fits this sub-category.\n");
|
||||||
|
|
||||||
|
return
|
||||||
|
"You are a bookkeeping assistant for a church mapping its expense categories to the IRS Form 990 " +
|
||||||
|
"Part IX (Statement of Functional Expenses) lines. Given an expense category name (often in " +
|
||||||
|
"Traditional Chinese), do three things:\n" +
|
||||||
|
"1. Correct any typos in the name and refine it into natural Traditional Chinese — return it as " +
|
||||||
|
"chineseName.\n" +
|
||||||
|
"2. Translate that into a concise, natural accounting English noun phrase (not a full sentence) — " +
|
||||||
|
"return it as englishName.\n" +
|
||||||
|
"3. Choose the single best matching Form 990 line from the catalog below. You MUST pick a " +
|
||||||
|
"form990LineId that appears in the catalog. If nothing fits well, choose the closest general line " +
|
||||||
|
"(e.g. an \"Other expenses\" line) and lower your confidence.\n\n" +
|
||||||
|
context +
|
||||||
|
"\n" +
|
||||||
|
$"Form 990 line catalog (JSON; each line has an Id, LineCode, and English/Chinese names):\n{catalogJson}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CategoryAiSuggestion BuildSuggestion(ModelAnswer answer, List<CatalogLine> catalog)
|
||||||
|
{
|
||||||
|
var suggestion = new CategoryAiSuggestion
|
||||||
|
{
|
||||||
|
ChineseName = string.IsNullOrWhiteSpace(answer.ChineseName) ? null : answer.ChineseName.Trim(),
|
||||||
|
EnglishName = string.IsNullOrWhiteSpace(answer.EnglishName) ? null : answer.EnglishName.Trim(),
|
||||||
|
Confidence = answer.Confidence,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Re-validate the returned id against the catalog; drop a hallucinated id rather than returning it.
|
||||||
|
var line = catalog.FirstOrDefault(candidate => candidate.Id == answer.Form990LineId);
|
||||||
|
if (line is not null)
|
||||||
|
{
|
||||||
|
suggestion.Form990LineId = line.Id;
|
||||||
|
suggestion.Form990LineLabel = Label(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
return suggestion;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Mirror the frontend dropdown label: "code — English / 中文" (or just "code — English").</summary>
|
||||||
|
private static string Label(CatalogLine line)
|
||||||
|
=> string.IsNullOrWhiteSpace(line.NameZh)
|
||||||
|
? $"{line.LineCode} — {line.NameEn}"
|
||||||
|
: $"{line.LineCode} — {line.NameEn} / {line.NameZh}";
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>Selects the active category-AI provider per request from <c>ChurchProfile.AiProvider</c>.</summary>
|
||||||
|
public interface IExpenseCategoryAiServiceFactory
|
||||||
|
{
|
||||||
|
Task<IExpenseCategoryAiService> ResolveAsync(CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class ExpenseCategoryAiServiceFactory : IExpenseCategoryAiServiceFactory
|
||||||
|
{
|
||||||
|
private readonly IChurchAiConfigProvider _config;
|
||||||
|
private readonly ClaudeExpenseCategoryAiService _claude;
|
||||||
|
private readonly GeminiExpenseCategoryAiService _gemini;
|
||||||
|
|
||||||
|
public ExpenseCategoryAiServiceFactory(
|
||||||
|
IChurchAiConfigProvider config,
|
||||||
|
ClaudeExpenseCategoryAiService claude,
|
||||||
|
GeminiExpenseCategoryAiService gemini)
|
||||||
|
{
|
||||||
|
_config = config;
|
||||||
|
_claude = claude;
|
||||||
|
_gemini = gemini;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IExpenseCategoryAiService> ResolveAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var cfg = await _config.GetAsync(ct);
|
||||||
|
return cfg.Provider.Equals("Gemini", StringComparison.OrdinalIgnoreCase) ? _gemini : _claude;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using ROLAC.API.Data;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Translates and classifies an expense via the Google Gemini <c>generateContent</c> API, using
|
||||||
|
/// Gemini's structured-output mode (<c>responseSchema</c>). The catalog, prompt, and id validation
|
||||||
|
/// come from <see cref="ExpenseAiServiceBase"/>; this class only owns the Gemini HTTP call + parse.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class GeminiExpenseAiService : ExpenseAiServiceBase
|
||||||
|
{
|
||||||
|
private const string BaseUrl = "https://generativelanguage.googleapis.com/v1beta";
|
||||||
|
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
private readonly IChurchAiConfigProvider _config;
|
||||||
|
private readonly ILogger<GeminiExpenseAiService> _logger;
|
||||||
|
|
||||||
|
public GeminiExpenseAiService(
|
||||||
|
HttpClient http,
|
||||||
|
IChurchAiConfigProvider config,
|
||||||
|
AppDbContext db,
|
||||||
|
ILogger<GeminiExpenseAiService> logger)
|
||||||
|
: base(db)
|
||||||
|
{
|
||||||
|
_http = http;
|
||||||
|
_config = config;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task<ModelAnswer?> CallModelAsync(string prompt, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var cfg = await _config.GetAsync(ct);
|
||||||
|
if (string.IsNullOrWhiteSpace(cfg.GeminiApiKey))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Gemini API key is not configured; expense AI assist is disabled.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var payload = new
|
||||||
|
{
|
||||||
|
contents = new[]
|
||||||
|
{
|
||||||
|
new { parts = new[] { new { text = prompt } } },
|
||||||
|
},
|
||||||
|
generationConfig = new
|
||||||
|
{
|
||||||
|
responseMimeType = "application/json",
|
||||||
|
responseSchema = new
|
||||||
|
{
|
||||||
|
type = "object",
|
||||||
|
properties = new
|
||||||
|
{
|
||||||
|
chineseDescription = new { type = "string" },
|
||||||
|
englishDescription = new { type = "string" },
|
||||||
|
groupId = new { type = "integer" },
|
||||||
|
subCategoryId = new { type = "integer" },
|
||||||
|
confidence = new { type = "number" },
|
||||||
|
},
|
||||||
|
required = new[] { "chineseDescription", "englishDescription", "groupId", "subCategoryId", "confidence" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
var url = $"{BaseUrl}/models/{cfg.GeminiModel}:generateContent";
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, url)
|
||||||
|
{
|
||||||
|
Content = JsonContent.Create(payload),
|
||||||
|
};
|
||||||
|
request.Headers.Add("X-goog-api-key", cfg.GeminiApiKey);
|
||||||
|
|
||||||
|
using var response = await _http.SendAsync(request, ct);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var body = await response.Content.ReadAsStringAsync(ct);
|
||||||
|
_logger.LogWarning("Gemini returned {Status}: {Body}", (int)response.StatusCode, body);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Navigate candidates[0].content.parts[0].text — the model's JSON answer as a string.
|
||||||
|
using var doc = JsonDocument.Parse(await response.Content.ReadAsStreamAsync(ct));
|
||||||
|
var text = doc.RootElement
|
||||||
|
.GetProperty("candidates")[0]
|
||||||
|
.GetProperty("content")
|
||||||
|
.GetProperty("parts")[0]
|
||||||
|
.GetProperty("text")
|
||||||
|
.GetString();
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(text))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Gemini response contained no text part.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed = JsonSerializer.Deserialize<GeminiAnswer>(
|
||||||
|
text, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||||
|
if (parsed is null) return null;
|
||||||
|
|
||||||
|
return new ModelAnswer(parsed.EnglishDescription, parsed.ChineseDescription, parsed.GroupId, parsed.SubCategoryId, parsed.Confidence);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Gemini expense AI assist failed.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shape of Gemini's JSON answer (constrained by responseSchema).</summary>
|
||||||
|
private sealed class GeminiAnswer
|
||||||
|
{
|
||||||
|
public string? EnglishDescription { get; set; }
|
||||||
|
public string? ChineseDescription { get; set; }
|
||||||
|
public int GroupId { get; set; }
|
||||||
|
public int SubCategoryId { get; set; }
|
||||||
|
public double Confidence { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using ROLAC.API.Data;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Refines, translates, and maps an expense category to a Form 990 line via the Google Gemini
|
||||||
|
/// <c>generateContent</c> API, using Gemini's structured-output mode (<c>responseSchema</c>). The
|
||||||
|
/// catalog, prompt, and id validation come from <see cref="ExpenseCategoryAiServiceBase"/>; this class
|
||||||
|
/// only owns the Gemini HTTP call + parse.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class GeminiExpenseCategoryAiService : ExpenseCategoryAiServiceBase
|
||||||
|
{
|
||||||
|
private const string BaseUrl = "https://generativelanguage.googleapis.com/v1beta";
|
||||||
|
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
private readonly IChurchAiConfigProvider _config;
|
||||||
|
private readonly ILogger<GeminiExpenseCategoryAiService> _logger;
|
||||||
|
|
||||||
|
public GeminiExpenseCategoryAiService(
|
||||||
|
HttpClient http,
|
||||||
|
IChurchAiConfigProvider config,
|
||||||
|
AppDbContext db,
|
||||||
|
ILogger<GeminiExpenseCategoryAiService> logger)
|
||||||
|
: base(db)
|
||||||
|
{
|
||||||
|
_http = http;
|
||||||
|
_config = config;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task<ModelAnswer?> CallModelAsync(string prompt, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var cfg = await _config.GetAsync(ct);
|
||||||
|
if (string.IsNullOrWhiteSpace(cfg.GeminiApiKey))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Gemini API key is not configured; category AI assist is disabled.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var payload = new
|
||||||
|
{
|
||||||
|
contents = new[]
|
||||||
|
{
|
||||||
|
new { parts = new[] { new { text = prompt } } },
|
||||||
|
},
|
||||||
|
generationConfig = new
|
||||||
|
{
|
||||||
|
responseMimeType = "application/json",
|
||||||
|
responseSchema = new
|
||||||
|
{
|
||||||
|
type = "object",
|
||||||
|
properties = new
|
||||||
|
{
|
||||||
|
chineseName = new { type = "string" },
|
||||||
|
englishName = new { type = "string" },
|
||||||
|
form990LineId = new { type = "integer" },
|
||||||
|
confidence = new { type = "number" },
|
||||||
|
},
|
||||||
|
required = new[] { "chineseName", "englishName", "form990LineId", "confidence" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
var url = $"{BaseUrl}/models/{cfg.GeminiModel}:generateContent";
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, url)
|
||||||
|
{
|
||||||
|
Content = JsonContent.Create(payload),
|
||||||
|
};
|
||||||
|
request.Headers.Add("X-goog-api-key", cfg.GeminiApiKey);
|
||||||
|
|
||||||
|
using var response = await _http.SendAsync(request, ct);
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
var body = await response.Content.ReadAsStringAsync(ct);
|
||||||
|
_logger.LogWarning("Gemini returned {Status}: {Body}", (int)response.StatusCode, body);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Navigate candidates[0].content.parts[0].text — the model's JSON answer as a string.
|
||||||
|
using var doc = JsonDocument.Parse(await response.Content.ReadAsStreamAsync(ct));
|
||||||
|
var text = doc.RootElement
|
||||||
|
.GetProperty("candidates")[0]
|
||||||
|
.GetProperty("content")
|
||||||
|
.GetProperty("parts")[0]
|
||||||
|
.GetProperty("text")
|
||||||
|
.GetString();
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(text))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Gemini response contained no text part.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed = JsonSerializer.Deserialize<GeminiAnswer>(
|
||||||
|
text, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
||||||
|
if (parsed is null) return null;
|
||||||
|
|
||||||
|
return new ModelAnswer(parsed.ChineseName, parsed.EnglishName, parsed.Form990LineId, parsed.Confidence);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Gemini category AI assist failed.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shape of Gemini's JSON answer (constrained by responseSchema).</summary>
|
||||||
|
private sealed class GeminiAnswer
|
||||||
|
{
|
||||||
|
public string? ChineseName { get; set; }
|
||||||
|
public string? EnglishName { get; set; }
|
||||||
|
public int? Form990LineId { get; set; }
|
||||||
|
public double Confidence { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using ROLAC.API.DTOs.Expense;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>AI assistance for expense entry: translate a description and suggest a category.</summary>
|
||||||
|
public interface IExpenseAiService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Translate <paramref name="chineseText"/> to concise accounting English and suggest the best
|
||||||
|
/// major/sub category from the live catalog, using <paramref name="amount"/> as a hint.
|
||||||
|
/// Never throws on an upstream/AI failure — returns a suggestion with null fields instead.
|
||||||
|
/// </summary>
|
||||||
|
Task<ExpenseAiSuggestion> SuggestAsync(string chineseText, decimal amount, CancellationToken ct = default);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using ROLAC.API.DTOs.Expense;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services.Ai;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AI assistance for defining an expense category (大項/小項): refine the Chinese name, translate it
|
||||||
|
/// to English, and suggest the matching IRS Form 990 Part IX line.
|
||||||
|
/// </summary>
|
||||||
|
public interface IExpenseCategoryAiService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Refine the entered name, translate it to concise accounting English, and choose the best Form 990
|
||||||
|
/// line from the live catalog (biased by the group/sub context in <paramref name="request"/>).
|
||||||
|
/// Never throws on an upstream/AI failure — returns a suggestion with null fields instead.
|
||||||
|
/// </summary>
|
||||||
|
Task<CategoryAiSuggestion> SuggestAsync(ExpenseCategoryAiRequest request, CancellationToken ct = default);
|
||||||
|
}
|
||||||
@@ -60,6 +60,22 @@ public class AuthService : IAuthService
|
|||||||
throw new UnauthorizedAccessException("Account is inactive.");
|
throw new UnauthorizedAccessException("Account is inactive.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_audit.Write(
|
||||||
|
AuditActions.Login, AuditCategories.Security, LogLevelEnum.Information,
|
||||||
|
entityName: nameof(AppUser), entityId: user.Id,
|
||||||
|
summary: $"Login succeeded: {user.Email}",
|
||||||
|
userId: user.Id, userEmail: user.Email, ipAddress: ipAddress);
|
||||||
|
|
||||||
|
return await IssueSessionAsync(user, ipAddress, deviceInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Issue session (shared by login and passwordless flows like invitations)
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public async Task<(LoginResponse Response, string RawRefreshToken)> IssueSessionAsync(
|
||||||
|
AppUser user, string? ipAddress = null, string? deviceInfo = null)
|
||||||
|
{
|
||||||
var roles = await _userManager.GetRolesAsync(user);
|
var roles = await _userManager.GetRolesAsync(user);
|
||||||
var accessToken = _tokenService.GenerateAccessToken(user, roles);
|
var accessToken = _tokenService.GenerateAccessToken(user, roles);
|
||||||
var rawRefresh = _tokenService.GenerateRefreshToken();
|
var rawRefresh = _tokenService.GenerateRefreshToken();
|
||||||
@@ -79,12 +95,6 @@ public class AuthService : IAuthService
|
|||||||
await _userManager.UpdateAsync(user);
|
await _userManager.UpdateAsync(user);
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
|
|
||||||
_audit.Write(
|
|
||||||
AuditActions.Login, AuditCategories.Security, LogLevelEnum.Information,
|
|
||||||
entityName: nameof(AppUser), entityId: user.Id,
|
|
||||||
summary: $"Login succeeded: {user.Email}",
|
|
||||||
userId: user.Id, userEmail: user.Email, ipAddress: ipAddress);
|
|
||||||
|
|
||||||
return (await BuildResponseAsync(accessToken, user, roles), rawRefresh);
|
return (await BuildResponseAsync(accessToken, user, roles), rawRefresh);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,5 +235,29 @@ public class AuthService : IAuthService
|
|||||||
Roles = roles,
|
Roles = roles,
|
||||||
LanguagePreference = user.LanguagePreference,
|
LanguagePreference = user.LanguagePreference,
|
||||||
Permissions = await _permissions.GetEffectivePermissionsAsync(roles),
|
Permissions = await _permissions.GetEffectivePermissionsAsync(roles),
|
||||||
|
MemberInfo = await BuildMemberInfoAsync(user),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Loads the linked member's display fields, or null when the account has no
|
||||||
|
/// MemberId or its member record was soft-deleted (excluded by query filter).
|
||||||
|
/// </summary>
|
||||||
|
private async Task<MemberInfo?> BuildMemberInfoAsync(AppUser user)
|
||||||
|
{
|
||||||
|
if (user.MemberId is not int memberId)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
return await _db.Members
|
||||||
|
.Where(member => member.Id == memberId)
|
||||||
|
.Select(member => new MemberInfo
|
||||||
|
{
|
||||||
|
Id = member.Id,
|
||||||
|
NickName = member.NickName,
|
||||||
|
FirstName_en = member.FirstName_en,
|
||||||
|
LastName_en = member.LastName_en,
|
||||||
|
FirstName_zh = member.FirstName_zh,
|
||||||
|
LastName_zh = member.LastName_zh,
|
||||||
|
})
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,18 +15,31 @@ public class ChurchProfileService : IChurchProfileService
|
|||||||
var p = await GetOrCreateAsync();
|
var p = await GetOrCreateAsync();
|
||||||
return new ChurchProfileDto
|
return new ChurchProfileDto
|
||||||
{
|
{
|
||||||
Id = p.Id, Name = p.Name, Address = p.Address, City = p.City, State = p.State,
|
Id = p.Id, Name = p.Name, NameZh = p.NameZh, Phone = p.Phone, Email = p.Email,
|
||||||
|
Website = p.Website, Address = p.Address, City = p.City, State = p.State,
|
||||||
ZipCode = p.ZipCode, BankName = p.BankName, BankAccountNumber = p.BankAccountNumber,
|
ZipCode = p.ZipCode, BankName = p.BankName, BankAccountNumber = p.BankAccountNumber,
|
||||||
BankRoutingNumber = p.BankRoutingNumber, NextCheckNumber = p.NextCheckNumber,
|
BankRoutingNumber = p.BankRoutingNumber, NextCheckNumber = p.NextCheckNumber,
|
||||||
|
AiProvider = p.AiProvider,
|
||||||
|
ClaudeModel = p.ClaudeModel,
|
||||||
|
ClaudeApiKeyMasked = Mask(p.ClaudeApiKey),
|
||||||
|
GeminiModel = p.GeminiModel,
|
||||||
|
GeminiApiKeyMasked = Mask(p.GeminiApiKey),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task UpdateAsync(UpdateChurchProfileRequest r)
|
public async Task UpdateAsync(UpdateChurchProfileRequest r)
|
||||||
{
|
{
|
||||||
var p = await GetOrCreateAsync();
|
var p = await GetOrCreateAsync();
|
||||||
p.Name = r.Name; p.Address = r.Address; p.City = r.City; p.State = r.State;
|
p.Name = r.Name; p.NameZh = r.NameZh; p.Phone = r.Phone; p.Email = r.Email;
|
||||||
|
p.Website = r.Website; p.Address = r.Address; p.City = r.City; p.State = r.State;
|
||||||
p.ZipCode = r.ZipCode; p.BankName = r.BankName; p.BankAccountNumber = r.BankAccountNumber;
|
p.ZipCode = r.ZipCode; p.BankName = r.BankName; p.BankAccountNumber = r.BankAccountNumber;
|
||||||
p.BankRoutingNumber = r.BankRoutingNumber; p.NextCheckNumber = r.NextCheckNumber;
|
p.BankRoutingNumber = r.BankRoutingNumber; p.NextCheckNumber = r.NextCheckNumber;
|
||||||
|
p.AiProvider = string.IsNullOrWhiteSpace(r.AiProvider) ? "Claude" : r.AiProvider;
|
||||||
|
p.ClaudeModel = r.ClaudeModel;
|
||||||
|
p.GeminiModel = r.GeminiModel;
|
||||||
|
// Leave-unchanged semantics: only overwrite a stored key when a new value is supplied.
|
||||||
|
if (!string.IsNullOrWhiteSpace(r.ClaudeApiKey)) p.ClaudeApiKey = r.ClaudeApiKey;
|
||||||
|
if (!string.IsNullOrWhiteSpace(r.GeminiApiKey)) p.GeminiApiKey = r.GeminiApiKey;
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,4 +54,12 @@ public class ChurchProfileService : IChurchProfileService
|
|||||||
}
|
}
|
||||||
return p;
|
return p;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Mask a stored secret for display: 6 bullets + last 4 chars; fully masked when ≤4 chars.</summary>
|
||||||
|
private static string Mask(string? key)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(key)) return "";
|
||||||
|
if (key.Length <= 4) return new string('•', key.Length);
|
||||||
|
return new string('•', 6) + key[^4..];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,19 @@ public class DisbursementService : IDisbursementService
|
|||||||
var memberIds = rows.Where(r => r.MemberId != null).Select(r => r.MemberId!.Value).ToHashSet();
|
var memberIds = rows.Where(r => r.MemberId != null).Select(r => r.MemberId!.Value).ToHashSet();
|
||||||
var members = await _db.Members.AsNoTracking().Where(m => memberIds.Contains(m.Id)).ToDictionaryAsync(m => m.Id);
|
var members = await _db.Members.AsNoTracking().Where(m => memberIds.Contains(m.Id)).ToDictionaryAsync(m => m.Id);
|
||||||
|
|
||||||
|
// Category label per expense: the single line's category, or "Multiple" when it spans several.
|
||||||
|
var expenseIds = rows.Select(r => r.Id).ToList();
|
||||||
|
var lineGroups = await _db.ExpenseLines.AsNoTracking()
|
||||||
|
.Where(l => expenseIds.Contains(l.ExpenseId))
|
||||||
|
.OrderBy(l => l.Id)
|
||||||
|
.Select(l => new { l.ExpenseId, l.CategoryGroupId })
|
||||||
|
.ToListAsync();
|
||||||
|
var categoryByExpense = lineGroups.GroupBy(l => l.ExpenseId).ToDictionary(
|
||||||
|
g => g.Key,
|
||||||
|
g => g.Select(l => l.CategoryGroupId).Distinct().Count() > 1
|
||||||
|
? "Multiple / 多類別"
|
||||||
|
: grpNames.GetValueOrDefault(g.First().CategoryGroupId, ""));
|
||||||
|
|
||||||
var groups = new Dictionary<string, PayeeGroupDto>();
|
var groups = new Dictionary<string, PayeeGroupDto>();
|
||||||
foreach (var e in rows)
|
foreach (var e in rows)
|
||||||
{
|
{
|
||||||
@@ -77,7 +90,7 @@ public class DisbursementService : IDisbursementService
|
|||||||
ExpenseId = e.Id, ExpenseDate = e.ExpenseDate.ToString("yyyy-MM-dd"),
|
ExpenseId = e.Id, ExpenseDate = e.ExpenseDate.ToString("yyyy-MM-dd"),
|
||||||
Description = e.Description, Amount = e.Amount,
|
Description = e.Description, Amount = e.Amount,
|
||||||
MinistryName = minNames.GetValueOrDefault(e.MinistryId, ""),
|
MinistryName = minNames.GetValueOrDefault(e.MinistryId, ""),
|
||||||
CategoryName = grpNames.GetValueOrDefault(e.CategoryGroupId, ""),
|
CategoryName = categoryByExpense.GetValueOrDefault(e.Id, ""),
|
||||||
});
|
});
|
||||||
g.TotalAmount += e.Amount;
|
g.TotalAmount += e.Amount;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,21 +22,28 @@ public class ExpenseCategoryService : IExpenseCategoryService
|
|||||||
.OrderBy(s => s.SortOrder).ThenBy(s => s.Name_en)
|
.OrderBy(s => s.SortOrder).ThenBy(s => s.Name_en)
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
|
var lineCodes = await _db.Form990ExpenseLines.AsNoTracking()
|
||||||
|
.ToDictionaryAsync(l => l.Id, l => l.LineCode);
|
||||||
|
|
||||||
return groups.Select(g => new ExpenseCategoryGroupDto
|
return groups.Select(g => new ExpenseCategoryGroupDto
|
||||||
{
|
{
|
||||||
Id = g.Id, Name_en = g.Name_en, Name_zh = g.Name_zh,
|
Id = g.Id, Name_en = g.Name_en, Name_zh = g.Name_zh,
|
||||||
SortOrder = g.SortOrder, IsActive = g.IsActive,
|
SortOrder = g.SortOrder, IsActive = g.IsActive,
|
||||||
|
Form990LineId = g.Form990LineId,
|
||||||
|
Form990LineCode = g.Form990LineId.HasValue ? lineCodes.GetValueOrDefault(g.Form990LineId.Value) : null,
|
||||||
SubCategories = subs.Where(s => s.GroupId == g.Id).Select(s => new ExpenseSubCategoryDto
|
SubCategories = subs.Where(s => s.GroupId == g.Id).Select(s => new ExpenseSubCategoryDto
|
||||||
{
|
{
|
||||||
Id = s.Id, GroupId = s.GroupId, Name_en = s.Name_en, Name_zh = s.Name_zh,
|
Id = s.Id, GroupId = s.GroupId, Name_en = s.Name_en, Name_zh = s.Name_zh,
|
||||||
SortOrder = s.SortOrder, IsActive = s.IsActive,
|
SortOrder = s.SortOrder, IsActive = s.IsActive,
|
||||||
|
Form990LineId = s.Form990LineId,
|
||||||
|
Form990LineCode = s.Form990LineId.HasValue ? lineCodes.GetValueOrDefault(s.Form990LineId.Value) : null,
|
||||||
}).ToList(),
|
}).ToList(),
|
||||||
}).ToList();
|
}).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<int> CreateGroupAsync(CreateExpenseGroupRequest r)
|
public async Task<int> CreateGroupAsync(CreateExpenseGroupRequest r)
|
||||||
{
|
{
|
||||||
var g = new ExpenseCategoryGroup { Name_en = r.Name_en, Name_zh = r.Name_zh, SortOrder = r.SortOrder, IsActive = true };
|
var g = new ExpenseCategoryGroup { Name_en = r.Name_en, Name_zh = r.Name_zh, SortOrder = r.SortOrder, IsActive = true, Form990LineId = r.Form990LineId };
|
||||||
_db.ExpenseCategoryGroups.Add(g);
|
_db.ExpenseCategoryGroups.Add(g);
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
return g.Id;
|
return g.Id;
|
||||||
@@ -46,7 +53,7 @@ public class ExpenseCategoryService : IExpenseCategoryService
|
|||||||
{
|
{
|
||||||
var g = await _db.ExpenseCategoryGroups.FindAsync(id)
|
var g = await _db.ExpenseCategoryGroups.FindAsync(id)
|
||||||
?? throw new KeyNotFoundException($"ExpenseCategoryGroup {id} not found.");
|
?? throw new KeyNotFoundException($"ExpenseCategoryGroup {id} not found.");
|
||||||
g.Name_en = r.Name_en; g.Name_zh = r.Name_zh; g.SortOrder = r.SortOrder; g.IsActive = r.IsActive;
|
g.Name_en = r.Name_en; g.Name_zh = r.Name_zh; g.SortOrder = r.SortOrder; g.IsActive = r.IsActive; g.Form990LineId = r.Form990LineId;
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,7 +69,7 @@ public class ExpenseCategoryService : IExpenseCategoryService
|
|||||||
{
|
{
|
||||||
var exists = await _db.ExpenseCategoryGroups.AnyAsync(g => g.Id == r.GroupId);
|
var exists = await _db.ExpenseCategoryGroups.AnyAsync(g => g.Id == r.GroupId);
|
||||||
if (!exists) throw new KeyNotFoundException($"ExpenseCategoryGroup {r.GroupId} not found.");
|
if (!exists) throw new KeyNotFoundException($"ExpenseCategoryGroup {r.GroupId} not found.");
|
||||||
var s = new ExpenseSubCategory { GroupId = r.GroupId, Name_en = r.Name_en, Name_zh = r.Name_zh, SortOrder = r.SortOrder, IsActive = true };
|
var s = new ExpenseSubCategory { GroupId = r.GroupId, Name_en = r.Name_en, Name_zh = r.Name_zh, SortOrder = r.SortOrder, IsActive = true, Form990LineId = r.Form990LineId };
|
||||||
_db.ExpenseSubCategories.Add(s);
|
_db.ExpenseSubCategories.Add(s);
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
return s.Id;
|
return s.Id;
|
||||||
@@ -72,7 +79,7 @@ public class ExpenseCategoryService : IExpenseCategoryService
|
|||||||
{
|
{
|
||||||
var s = await _db.ExpenseSubCategories.FindAsync(id)
|
var s = await _db.ExpenseSubCategories.FindAsync(id)
|
||||||
?? throw new KeyNotFoundException($"ExpenseSubCategory {id} not found.");
|
?? throw new KeyNotFoundException($"ExpenseSubCategory {id} not found.");
|
||||||
s.GroupId = r.GroupId; s.Name_en = r.Name_en; s.Name_zh = r.Name_zh; s.SortOrder = r.SortOrder; s.IsActive = r.IsActive;
|
s.GroupId = r.GroupId; s.Name_en = r.Name_en; s.Name_zh = r.Name_zh; s.SortOrder = r.SortOrder; s.IsActive = r.IsActive; s.Form990LineId = r.Form990LineId;
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,8 +35,9 @@ public class ExpenseService : IExpenseService
|
|||||||
{
|
{
|
||||||
var query = _db.Expenses.AsNoTracking().AsQueryable();
|
var query = _db.Expenses.AsNoTracking().AsQueryable();
|
||||||
if (ministryId.HasValue) query = query.Where(e => e.MinistryId == ministryId.Value);
|
if (ministryId.HasValue) query = query.Where(e => e.MinistryId == ministryId.Value);
|
||||||
if (categoryGroupId.HasValue) query = query.Where(e => e.CategoryGroupId == categoryGroupId.Value);
|
// Category filters now match against any line of the expense.
|
||||||
if (subCategoryId.HasValue) query = query.Where(e => e.SubCategoryId == subCategoryId.Value);
|
if (categoryGroupId.HasValue) query = query.Where(e => e.Lines.Any(l => l.CategoryGroupId == categoryGroupId.Value));
|
||||||
|
if (subCategoryId.HasValue) query = query.Where(e => e.Lines.Any(l => l.SubCategoryId == subCategoryId.Value));
|
||||||
// `statuses` (comma-separated) takes precedence over single `status`; lets the dashboard
|
// `statuses` (comma-separated) takes precedence over single `status`; lets the dashboard
|
||||||
// request the Paid+Approved set in one call.
|
// request the Paid+Approved set in one call.
|
||||||
if (!string.IsNullOrWhiteSpace(statuses))
|
if (!string.IsNullOrWhiteSpace(statuses))
|
||||||
@@ -81,57 +82,171 @@ public class ExpenseService : IExpenseService
|
|||||||
|
|
||||||
var minNames = await _db.Ministries.AsNoTracking().ToDictionaryAsync(m => m.Id, m => $"{m.Name_en} / {m.Name_zh}");
|
var minNames = await _db.Ministries.AsNoTracking().ToDictionaryAsync(m => m.Id, m => $"{m.Name_en} / {m.Name_zh}");
|
||||||
var grpNames = await _db.ExpenseCategoryGroups.AsNoTracking().ToDictionaryAsync(g => g.Id, g => $"{g.Name_en} / {g.Name_zh}");
|
var grpNames = await _db.ExpenseCategoryGroups.AsNoTracking().ToDictionaryAsync(g => g.Id, g => $"{g.Name_en} / {g.Name_zh}");
|
||||||
var subNames = await _db.ExpenseSubCategories.AsNoTracking().ToDictionaryAsync(s => s.Id, s => $"{s.Name_en} / {s.Name_zh}");
|
|
||||||
var memberIds = rows.Where(r => r.MemberId != null).Select(r => r.MemberId!.Value).ToHashSet();
|
var memberIds = rows.Where(r => r.MemberId != null).Select(r => r.MemberId!.Value).ToHashSet();
|
||||||
var memNames = await _db.Members.AsNoTracking().Where(m => memberIds.Contains(m.Id))
|
var memberNames = await _db.Members.AsNoTracking().Where(m => memberIds.Contains(m.Id))
|
||||||
.ToDictionaryAsync(m => m.Id, m => $"{m.FirstName_en} {m.LastName_en}");
|
.Select(m => new { m.Id, m.FirstName_en, m.LastName_en, m.NickName })
|
||||||
|
.ToDictionaryAsync(
|
||||||
|
m => m.Id,
|
||||||
|
m => new MemberPayeeName($"{m.FirstName_en} {m.LastName_en}",
|
||||||
|
BuildNickPayeeName(m.NickName, m.FirstName_en, m.LastName_en)));
|
||||||
|
var reviewerNames = await ResolveUserNamesAsync(rows.Select(r => r.ReviewedBy));
|
||||||
|
|
||||||
var items = rows.Select(e => new ExpenseListItemDto
|
// Line count + first line's category, per expense on this page.
|
||||||
|
var expenseIds = rows.Select(r => r.Id).ToList();
|
||||||
|
var lineRows = await _db.ExpenseLines.AsNoTracking()
|
||||||
|
.Where(l => expenseIds.Contains(l.ExpenseId))
|
||||||
|
.OrderBy(l => l.Id)
|
||||||
|
.Select(l => new { l.ExpenseId, l.CategoryGroupId })
|
||||||
|
.ToListAsync();
|
||||||
|
var linesByExpense = lineRows.GroupBy(l => l.ExpenseId)
|
||||||
|
.ToDictionary(g => g.Key, g => g.ToList());
|
||||||
|
|
||||||
|
var items = rows.Select(e =>
|
||||||
{
|
{
|
||||||
Id = e.Id, Type = e.Type, Status = e.Status, Amount = e.Amount, Description = e.Description,
|
linesByExpense.TryGetValue(e.Id, out var ls);
|
||||||
MinistryId = e.MinistryId, MinistryName = minNames.GetValueOrDefault(e.MinistryId, ""),
|
var firstGroupId = ls is { Count: > 0 } ? ls[0].CategoryGroupId : 0;
|
||||||
CategoryGroupId = e.CategoryGroupId, CategoryGroupName = grpNames.GetValueOrDefault(e.CategoryGroupId, ""),
|
return new ExpenseListItemDto
|
||||||
SubCategoryId = e.SubCategoryId, SubCategoryName = subNames.GetValueOrDefault(e.SubCategoryId, ""),
|
{
|
||||||
VendorName = e.VendorName, MemberId = e.MemberId,
|
Id = e.Id, Type = e.Type, Status = e.Status, Amount = e.Amount, Description = e.Description,
|
||||||
MemberName = e.MemberId != null ? memNames.GetValueOrDefault(e.MemberId.Value) : null,
|
MinistryId = e.MinistryId, MinistryName = minNames.GetValueOrDefault(e.MinistryId, ""),
|
||||||
ExpenseDate = e.ExpenseDate.ToString("yyyy-MM-dd"),
|
LineCount = ls?.Count ?? 0,
|
||||||
HasReceipt = e.ReceiptBlobPath != null,
|
PrimaryCategoryName = grpNames.GetValueOrDefault(firstGroupId, ""),
|
||||||
CheckNumber = e.CheckNumber,
|
VendorName = e.VendorName, MemberId = e.MemberId,
|
||||||
|
MemberName = e.MemberId != null ? memberNames.GetValueOrDefault(e.MemberId.Value)?.Legal : null,
|
||||||
|
MemberNickName = e.MemberId != null ? memberNames.GetValueOrDefault(e.MemberId.Value)?.Nick : null,
|
||||||
|
ExpenseDate = e.ExpenseDate.ToString("yyyy-MM-dd"),
|
||||||
|
HasReceipt = e.ReceiptBlobPath != null,
|
||||||
|
CheckNumber = e.CheckNumber,
|
||||||
|
ReviewedByName = e.ReviewedBy != null ? reviewerNames.GetValueOrDefault(e.ReviewedBy) : null,
|
||||||
|
ReviewedAt = e.ReviewedAt,
|
||||||
|
ReviewNotes = e.ReviewNotes,
|
||||||
|
};
|
||||||
}).ToList();
|
}).ToList();
|
||||||
|
|
||||||
return new PagedResult<ExpenseListItemDto> { Items = items, TotalCount = total, Page = page, PageSize = pageSize };
|
return new PagedResult<ExpenseListItemDto> { Items = items, TotalCount = total, Page = page, PageSize = pageSize };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Resolve actor user ids (AppUser.Id, stored in ReviewedBy/SubmittedBy/PaidBy) to a display name:
|
||||||
|
// the linked Member's full name when present, otherwise the account email.
|
||||||
|
private async Task<Dictionary<string, string>> ResolveUserNamesAsync(IEnumerable<string?> userIds)
|
||||||
|
{
|
||||||
|
var ids = userIds.Where(id => !string.IsNullOrEmpty(id)).Select(id => id!).Distinct().ToList();
|
||||||
|
if (ids.Count == 0) return new Dictionary<string, string>();
|
||||||
|
|
||||||
|
var users = await _db.Users.AsNoTracking()
|
||||||
|
.Where(u => ids.Contains(u.Id))
|
||||||
|
.Select(u => new { u.Id, u.Email, u.MemberId })
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
var memberIds = users.Where(u => u.MemberId != null).Select(u => u.MemberId!.Value).ToHashSet();
|
||||||
|
var memberNames = await _db.Members.AsNoTracking()
|
||||||
|
.Where(m => memberIds.Contains(m.Id))
|
||||||
|
.ToDictionaryAsync(m => m.Id, m => $"{m.FirstName_en} {m.LastName_en}".Trim());
|
||||||
|
|
||||||
|
return users.ToDictionary(
|
||||||
|
u => u.Id,
|
||||||
|
u => u.MemberId != null && memberNames.TryGetValue(u.MemberId.Value, out var name) && name.Length > 0
|
||||||
|
? name
|
||||||
|
: (u.Email ?? u.Id));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Member payee names carried to the frontend: the legal name (printed on the check) and an
|
||||||
|
// optional friendly "NickName LastName" line shown above it.
|
||||||
|
private sealed record MemberPayeeName(string Legal, string? Nick);
|
||||||
|
|
||||||
|
// Build the friendly "NickName LastName" payee line, or null when the member has no distinct
|
||||||
|
// nickname (mirrors the frontend memberDisplayName rule: a nickname equal to the first name is not shown).
|
||||||
|
private static string? BuildNickPayeeName(string? nickName, string firstNameEn, string lastNameEn)
|
||||||
|
{
|
||||||
|
bool hasDistinctNickName = !string.IsNullOrWhiteSpace(nickName) && nickName != firstNameEn;
|
||||||
|
if (!hasDistinctNickName)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return $"{nickName} {lastNameEn}";
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<ExpenseDto?> GetByIdAsync(int id)
|
public async Task<ExpenseDto?> GetByIdAsync(int id)
|
||||||
{
|
{
|
||||||
var e = await _db.Expenses.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
|
var e = await _db.Expenses.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
|
||||||
if (e is null) return null;
|
if (e is null) return null;
|
||||||
var minName = await _db.Ministries.Where(m => m.Id == e.MinistryId).Select(m => m.Name_en).FirstOrDefaultAsync() ?? "";
|
var minName = await _db.Ministries.Where(m => m.Id == e.MinistryId).Select(m => m.Name_en).FirstOrDefaultAsync() ?? "";
|
||||||
var grpName = await _db.ExpenseCategoryGroups.Where(g => g.Id == e.CategoryGroupId).Select(g => g.Name_en).FirstOrDefaultAsync() ?? "";
|
string? memberName = null;
|
||||||
var subName = await _db.ExpenseSubCategories.Where(s => s.Id == e.SubCategoryId).Select(s => s.Name_en).FirstOrDefaultAsync() ?? "";
|
string? memberNickName = null;
|
||||||
string? memName = e.MemberId != null
|
if (e.MemberId != null)
|
||||||
? await _db.Members.Where(m => m.Id == e.MemberId).Select(m => m.FirstName_en + " " + m.LastName_en).FirstOrDefaultAsync()
|
{
|
||||||
|
var member = await _db.Members.AsNoTracking()
|
||||||
|
.Where(m => m.Id == e.MemberId)
|
||||||
|
.Select(m => new { m.FirstName_en, m.LastName_en, m.NickName })
|
||||||
|
.FirstOrDefaultAsync();
|
||||||
|
if (member != null)
|
||||||
|
{
|
||||||
|
memberName = $"{member.FirstName_en} {member.LastName_en}";
|
||||||
|
memberNickName = BuildNickPayeeName(member.NickName, member.FirstName_en, member.LastName_en);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var reviewerName = e.ReviewedBy != null
|
||||||
|
? (await ResolveUserNamesAsync(new[] { e.ReviewedBy })).GetValueOrDefault(e.ReviewedBy)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
var lines = await _db.ExpenseLines.AsNoTracking().Where(l => l.ExpenseId == id).OrderBy(l => l.Id).ToListAsync();
|
||||||
|
var grpNames = await _db.ExpenseCategoryGroups.AsNoTracking().ToDictionaryAsync(g => g.Id, g => g.Name_en);
|
||||||
|
var subNames = await _db.ExpenseSubCategories.AsNoTracking().ToDictionaryAsync(s => s.Id, s => s.Name_en);
|
||||||
|
var lineDtos = lines.Select(l => new ExpenseLineItemDto
|
||||||
|
{
|
||||||
|
Id = l.Id, CategoryGroupId = l.CategoryGroupId, CategoryGroupName = grpNames.GetValueOrDefault(l.CategoryGroupId, ""),
|
||||||
|
SubCategoryId = l.SubCategoryId, SubCategoryName = subNames.GetValueOrDefault(l.SubCategoryId, ""),
|
||||||
|
FunctionalClass = l.FunctionalClass, Amount = l.Amount, Description = l.Description,
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
return new ExpenseDto
|
return new ExpenseDto
|
||||||
{
|
{
|
||||||
Id = e.Id, Type = e.Type, Status = e.Status, Amount = e.Amount, Description = e.Description,
|
Id = e.Id, Type = e.Type, Status = e.Status, Amount = e.Amount, Description = e.Description,
|
||||||
MinistryId = e.MinistryId, MinistryName = minName,
|
MinistryId = e.MinistryId, MinistryName = minName,
|
||||||
CategoryGroupId = e.CategoryGroupId, CategoryGroupName = grpName,
|
LineCount = lineDtos.Count,
|
||||||
SubCategoryId = e.SubCategoryId, SubCategoryName = subName,
|
PrimaryCategoryName = lineDtos.Count > 0 ? lineDtos[0].CategoryGroupName : "",
|
||||||
VendorName = e.VendorName, MemberId = e.MemberId, MemberName = memName,
|
VendorName = e.VendorName, MemberId = e.MemberId, MemberName = memberName, MemberNickName = memberNickName,
|
||||||
ExpenseDate = e.ExpenseDate.ToString("yyyy-MM-dd"), HasReceipt = e.ReceiptBlobPath != null,
|
ExpenseDate = e.ExpenseDate.ToString("yyyy-MM-dd"), HasReceipt = e.ReceiptBlobPath != null,
|
||||||
CheckNumber = e.CheckNumber, Notes = e.Notes, ReviewNotes = e.ReviewNotes,
|
CheckNumber = e.CheckNumber, Notes = e.Notes, ReviewNotes = e.ReviewNotes,
|
||||||
SubmittedBy = e.SubmittedBy, SubmittedAt = e.SubmittedAt, ReviewedAt = e.ReviewedAt, PaidAt = e.PaidAt,
|
ReviewedByName = reviewerName, ReviewedAt = e.ReviewedAt,
|
||||||
|
SubmittedBy = e.SubmittedBy, SubmittedAt = e.SubmittedAt, PaidAt = e.PaidAt,
|
||||||
|
Lines = lineDtos,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Lines are the source of truth: ≥1 line, each with a category/subcategory and a positive amount.
|
||||||
|
private static void ValidateLines(List<ExpenseLineInput> lines)
|
||||||
|
{
|
||||||
|
if (lines is null || lines.Count == 0)
|
||||||
|
throw new InvalidOperationException("An expense must have at least one line.");
|
||||||
|
foreach (var l in lines)
|
||||||
|
{
|
||||||
|
if (l.CategoryGroupId <= 0 || l.SubCategoryId <= 0)
|
||||||
|
throw new InvalidOperationException("Each expense line needs a category group and subcategory.");
|
||||||
|
if (l.Amount <= 0)
|
||||||
|
throw new InvalidOperationException("Each expense line amount must be greater than zero.");
|
||||||
|
if (l.FunctionalClass is not null && !FunctionalClasses.All.Contains(l.FunctionalClass))
|
||||||
|
throw new InvalidOperationException($"Invalid functional class '{l.FunctionalClass}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<ExpenseLine> BuildLines(List<ExpenseLineInput> inputs) =>
|
||||||
|
inputs.Select(l => new ExpenseLine
|
||||||
|
{
|
||||||
|
CategoryGroupId = l.CategoryGroupId, SubCategoryId = l.SubCategoryId,
|
||||||
|
FunctionalClass = l.FunctionalClass, Amount = l.Amount, Description = l.Description,
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
public async Task<int> CreateAsync(CreateExpenseRequest r, bool isFinance)
|
public async Task<int> CreateAsync(CreateExpenseRequest r, bool isFinance)
|
||||||
{
|
{
|
||||||
|
ValidateLines(r.Lines);
|
||||||
var e = new Expense
|
var e = new Expense
|
||||||
{
|
{
|
||||||
MinistryId = r.MinistryId, CategoryGroupId = r.CategoryGroupId, SubCategoryId = r.SubCategoryId,
|
MinistryId = r.MinistryId,
|
||||||
Type = r.Type, Amount = r.Amount, Description = r.Description, VendorName = r.VendorName,
|
Type = r.Type, Amount = r.Lines.Sum(l => l.Amount), Description = r.Description, VendorName = r.VendorName,
|
||||||
CheckNumber = r.CheckNumber, ExpenseDate = r.ExpenseDate, Notes = r.Notes,
|
CheckNumber = r.CheckNumber, ExpenseDate = r.ExpenseDate, Notes = r.Notes,
|
||||||
|
Lines = BuildLines(r.Lines),
|
||||||
};
|
};
|
||||||
|
|
||||||
if (r.Type == "VendorPayment")
|
if (r.Type == "VendorPayment")
|
||||||
@@ -171,16 +286,21 @@ public class ExpenseService : IExpenseService
|
|||||||
|
|
||||||
public async Task UpdateAsync(int id, UpdateExpenseRequest r, bool isFinance)
|
public async Task UpdateAsync(int id, UpdateExpenseRequest r, bool isFinance)
|
||||||
{
|
{
|
||||||
|
ValidateLines(r.Lines);
|
||||||
// FirstOrDefaultAsync (not FindAsync) so the soft-delete query filter applies.
|
// FirstOrDefaultAsync (not FindAsync) so the soft-delete query filter applies.
|
||||||
var e = await _db.Expenses.FirstOrDefaultAsync(x => x.Id == id)
|
var e = await _db.Expenses.Include(x => x.Lines).FirstOrDefaultAsync(x => x.Id == id)
|
||||||
?? throw new KeyNotFoundException($"Expense {id} not found.");
|
?? throw new KeyNotFoundException($"Expense {id} not found.");
|
||||||
if (!isFinance && !(e.SubmittedBy == CurrentUserId && (e.Status == "Draft" || e.Status == "PendingApproval")))
|
if (!isFinance && !(e.SubmittedBy == CurrentUserId && (e.Status == "Draft" || e.Status == "PendingApproval" || e.Status == "Rejected")))
|
||||||
throw new InvalidOperationException("You can only edit your own draft or pending reimbursements.");
|
throw new InvalidOperationException("You can only edit your own draft, pending, or rejected reimbursements.");
|
||||||
|
|
||||||
e.MinistryId = r.MinistryId; e.CategoryGroupId = r.CategoryGroupId; e.SubCategoryId = r.SubCategoryId;
|
e.MinistryId = r.MinistryId; e.Description = r.Description; e.CheckNumber = r.CheckNumber;
|
||||||
e.Amount = r.Amount; e.Description = r.Description; e.CheckNumber = r.CheckNumber;
|
|
||||||
e.ExpenseDate = r.ExpenseDate; e.Notes = r.Notes;
|
e.ExpenseDate = r.ExpenseDate; e.Notes = r.Notes;
|
||||||
if (e.Type == "VendorPayment") e.VendorName = r.VendorName;
|
if (e.Type == "VendorPayment") e.VendorName = r.VendorName;
|
||||||
|
|
||||||
|
// Replace the line set wholesale (lines are owned by the header), recompute the total.
|
||||||
|
_db.ExpenseLines.RemoveRange(e.Lines);
|
||||||
|
e.Lines = BuildLines(r.Lines);
|
||||||
|
e.Amount = r.Lines.Sum(l => l.Amount);
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,8 +323,11 @@ public class ExpenseService : IExpenseService
|
|||||||
{
|
{
|
||||||
var e = await RequireAsync(id);
|
var e = await RequireAsync(id);
|
||||||
if (e.SubmittedBy != CurrentUserId) throw new InvalidOperationException("Only the submitter can submit this reimbursement.");
|
if (e.SubmittedBy != CurrentUserId) throw new InvalidOperationException("Only the submitter can submit this reimbursement.");
|
||||||
if (e.Status != "Draft") throw new InvalidOperationException($"Cannot submit from status '{e.Status}'.");
|
// Draft (first submit) or Rejected (re-submit after fixing the flagged issue, e.g. a clearer receipt).
|
||||||
|
if (e.Status != "Draft" && e.Status != "Rejected") throw new InvalidOperationException($"Cannot submit from status '{e.Status}'.");
|
||||||
e.Status = "PendingApproval"; e.SubmittedAt = DateTimeOffset.UtcNow;
|
e.Status = "PendingApproval"; e.SubmittedAt = DateTimeOffset.UtcNow;
|
||||||
|
// Clear the prior review so the expense returns to a clean pending state.
|
||||||
|
e.ReviewedBy = null; e.ReviewedAt = null; e.ReviewNotes = null;
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,6 +350,11 @@ public class ExpenseService : IExpenseService
|
|||||||
if (e.Status != "PendingApproval") throw new InvalidOperationException($"Cannot reject from status '{e.Status}'.");
|
if (e.Status != "PendingApproval") throw new InvalidOperationException($"Cannot reject from status '{e.Status}'.");
|
||||||
e.Status = "Rejected"; e.ReviewedBy = CurrentUserId; e.ReviewedAt = DateTimeOffset.UtcNow; e.ReviewNotes = reviewNotes;
|
e.Status = "Rejected"; e.ReviewedBy = CurrentUserId; e.ReviewedAt = DateTimeOffset.UtcNow; e.ReviewNotes = reviewNotes;
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
|
|
||||||
|
_audit.Write(
|
||||||
|
AuditActions.ExpenseRejected, AuditCategories.Business, LogLevelEnum.Information,
|
||||||
|
entityName: nameof(Expense), entityId: e.Id.ToString(),
|
||||||
|
summary: $"Expense #{e.Id} rejected: {e.Description} — {reviewNotes}");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task PayAsync(int id, string? checkNumber, DateOnly? paidAt)
|
public async Task PayAsync(int id, string? checkNumber, DateOnly? paidAt)
|
||||||
@@ -245,8 +373,8 @@ public class ExpenseService : IExpenseService
|
|||||||
public async Task SaveReceiptAsync(int id, Stream content, string fileName, bool isFinance)
|
public async Task SaveReceiptAsync(int id, Stream content, string fileName, bool isFinance)
|
||||||
{
|
{
|
||||||
var e = await RequireAsync(id);
|
var e = await RequireAsync(id);
|
||||||
if (!isFinance && !(e.SubmittedBy == CurrentUserId && (e.Status == "Draft" || e.Status == "PendingApproval")))
|
if (!isFinance && !(e.SubmittedBy == CurrentUserId && (e.Status == "Draft" || e.Status == "PendingApproval" || e.Status == "Rejected")))
|
||||||
throw new InvalidOperationException("You can only attach receipts to your own draft or pending reimbursements.");
|
throw new InvalidOperationException("You can only attach receipts to your own draft, pending, or rejected reimbursements.");
|
||||||
|
|
||||||
var safe = Path.GetFileName(fileName).Replace(' ', '_');
|
var safe = Path.GetFileName(fileName).Replace(' ', '_');
|
||||||
var path = $"finance/receipts/{e.ExpenseDate.Year}/{e.ExpenseDate.Month}/{e.Id}-{safe}";
|
var path = $"finance/receipts/{e.ExpenseDate.Year}/{e.ExpenseDate.Month}/{e.Id}-{safe}";
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using ROLAC.API.Data;
|
||||||
|
using ROLAC.API.DTOs.Expense;
|
||||||
|
using ROLAC.API.Entities;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services;
|
||||||
|
|
||||||
|
public class ExpenseSnapshotService : IExpenseSnapshotService
|
||||||
|
{
|
||||||
|
private readonly AppDbContext _db;
|
||||||
|
private readonly IHttpContextAccessor _http;
|
||||||
|
public ExpenseSnapshotService(AppDbContext db, IHttpContextAccessor http)
|
||||||
|
{ _db = db; _http = http; }
|
||||||
|
|
||||||
|
// The JWT carries the user id in the "sub" claim (NameClaimType="sub", MapInboundClaims=false),
|
||||||
|
// so ClaimTypes.NameIdentifier is absent at runtime. Check NameIdentifier first (unit tests set it),
|
||||||
|
// then fall back to "sub" (real tokens). Required for the self-ownership guard to work in production.
|
||||||
|
private string CurrentUserId =>
|
||||||
|
_http.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier)
|
||||||
|
?? _http.HttpContext?.User.FindFirstValue("sub")
|
||||||
|
?? "system";
|
||||||
|
|
||||||
|
public async Task<List<ExpenseSnapshotDto>> GetAllAsync()
|
||||||
|
{
|
||||||
|
var snaps = await _db.ExpenseSnapshots.AsNoTracking()
|
||||||
|
.OrderByDescending(s => s.CreatedAt).ThenByDescending(s => s.Id)
|
||||||
|
.ToListAsync();
|
||||||
|
if (snaps.Count == 0) return new();
|
||||||
|
|
||||||
|
var ids = snaps.Select(s => s.Id).ToList();
|
||||||
|
var lines = await _db.ExpenseSnapshotLines.AsNoTracking()
|
||||||
|
.Where(l => ids.Contains(l.SnapshotId)).ToListAsync();
|
||||||
|
var linesBySnapshot = lines.GroupBy(l => l.SnapshotId).ToDictionary(g => g.Key, g => g.ToList());
|
||||||
|
|
||||||
|
var minNames = await _db.Ministries.AsNoTracking().ToDictionaryAsync(m => m.Id, m => $"{m.Name_en} / {m.Name_zh}");
|
||||||
|
var creatorNames = await ResolveUserNamesAsync(snaps.Select(s => s.CreatedBy));
|
||||||
|
|
||||||
|
return snaps.Select(s =>
|
||||||
|
{
|
||||||
|
linesBySnapshot.TryGetValue(s.Id, out var ls);
|
||||||
|
return new ExpenseSnapshotDto
|
||||||
|
{
|
||||||
|
Id = s.Id, Name = s.Name, MinistryId = s.MinistryId,
|
||||||
|
MinistryName = minNames.GetValueOrDefault(s.MinistryId, ""),
|
||||||
|
Description = s.Description, VendorName = s.VendorName,
|
||||||
|
CheckNumber = s.CheckNumber, Notes = s.Notes,
|
||||||
|
TotalAmount = ls?.Sum(l => l.Amount) ?? 0,
|
||||||
|
LineCount = ls?.Count ?? 0,
|
||||||
|
CreatedByName = creatorNames.GetValueOrDefault(s.CreatedBy),
|
||||||
|
CreatedAt = s.CreatedAt,
|
||||||
|
};
|
||||||
|
}).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ExpenseSnapshotDto?> GetByIdAsync(int id)
|
||||||
|
{
|
||||||
|
var s = await _db.ExpenseSnapshots.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
|
||||||
|
if (s is null) return null;
|
||||||
|
|
||||||
|
var lines = await _db.ExpenseSnapshotLines.AsNoTracking()
|
||||||
|
.Where(l => l.SnapshotId == id).OrderBy(l => l.Id).ToListAsync();
|
||||||
|
var minName = await _db.Ministries.Where(m => m.Id == s.MinistryId).Select(m => m.Name_en).FirstOrDefaultAsync() ?? "";
|
||||||
|
var grpNames = await _db.ExpenseCategoryGroups.AsNoTracking().ToDictionaryAsync(g => g.Id, g => g.Name_en);
|
||||||
|
var subNames = await _db.ExpenseSubCategories.AsNoTracking().ToDictionaryAsync(x => x.Id, x => x.Name_en);
|
||||||
|
var creatorName = (await ResolveUserNamesAsync(new[] { s.CreatedBy })).GetValueOrDefault(s.CreatedBy);
|
||||||
|
|
||||||
|
return new ExpenseSnapshotDto
|
||||||
|
{
|
||||||
|
Id = s.Id, Name = s.Name, MinistryId = s.MinistryId, MinistryName = minName,
|
||||||
|
Description = s.Description, VendorName = s.VendorName, CheckNumber = s.CheckNumber, Notes = s.Notes,
|
||||||
|
TotalAmount = lines.Sum(l => l.Amount), LineCount = lines.Count,
|
||||||
|
CreatedByName = creatorName, CreatedAt = s.CreatedAt,
|
||||||
|
Lines = lines.Select(l => new ExpenseSnapshotLineDto
|
||||||
|
{
|
||||||
|
CategoryGroupId = l.CategoryGroupId, CategoryGroupName = grpNames.GetValueOrDefault(l.CategoryGroupId, ""),
|
||||||
|
SubCategoryId = l.SubCategoryId, SubCategoryName = subNames.GetValueOrDefault(l.SubCategoryId, ""),
|
||||||
|
FunctionalClass = l.FunctionalClass, Amount = l.Amount, Description = l.Description,
|
||||||
|
}).ToList(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<int> CreateAsync(CreateExpenseSnapshotRequest r)
|
||||||
|
{
|
||||||
|
ValidateLines(r.Lines);
|
||||||
|
var s = new ExpenseSnapshot
|
||||||
|
{
|
||||||
|
Name = r.Name.Trim(), MinistryId = r.MinistryId, Description = r.Description,
|
||||||
|
VendorName = r.VendorName, CheckNumber = r.CheckNumber, Notes = r.Notes,
|
||||||
|
Lines = BuildLines(r.Lines),
|
||||||
|
};
|
||||||
|
_db.ExpenseSnapshots.Add(s);
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
return s.Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task UpdateAsync(int id, UpdateExpenseSnapshotRequest r)
|
||||||
|
{
|
||||||
|
ValidateLines(r.Lines);
|
||||||
|
var s = await _db.ExpenseSnapshots.Include(x => x.Lines).FirstOrDefaultAsync(x => x.Id == id)
|
||||||
|
?? throw new KeyNotFoundException($"Snapshot {id} not found.");
|
||||||
|
|
||||||
|
s.Name = r.Name.Trim(); s.MinistryId = r.MinistryId; s.Description = r.Description;
|
||||||
|
s.VendorName = r.VendorName; s.CheckNumber = r.CheckNumber; s.Notes = r.Notes;
|
||||||
|
|
||||||
|
_db.ExpenseSnapshotLines.RemoveRange(s.Lines);
|
||||||
|
s.Lines = BuildLines(r.Lines);
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DeleteAsync(int id)
|
||||||
|
{
|
||||||
|
var s = await _db.ExpenseSnapshots.FirstOrDefaultAsync(x => x.Id == id)
|
||||||
|
?? throw new KeyNotFoundException($"Snapshot {id} not found.");
|
||||||
|
s.IsDeleted = true; s.DeletedAt = DateTimeOffset.UtcNow; s.DeletedBy = CurrentUserId;
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ValidateLines(List<ExpenseLineInput> lines)
|
||||||
|
{
|
||||||
|
if (lines is null || lines.Count == 0)
|
||||||
|
throw new InvalidOperationException("A snapshot must have at least one line.");
|
||||||
|
foreach (var l in lines)
|
||||||
|
{
|
||||||
|
if (l.CategoryGroupId <= 0 || l.SubCategoryId <= 0)
|
||||||
|
throw new InvalidOperationException("Each snapshot line needs a category group and subcategory.");
|
||||||
|
if (l.Amount <= 0)
|
||||||
|
throw new InvalidOperationException("Each snapshot line amount must be greater than zero.");
|
||||||
|
if (l.FunctionalClass is not null && !FunctionalClasses.All.Contains(l.FunctionalClass))
|
||||||
|
throw new InvalidOperationException($"Invalid functional class '{l.FunctionalClass}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<ExpenseSnapshotLine> BuildLines(List<ExpenseLineInput> inputs) =>
|
||||||
|
inputs.Select(l => new ExpenseSnapshotLine
|
||||||
|
{
|
||||||
|
CategoryGroupId = l.CategoryGroupId, SubCategoryId = l.SubCategoryId,
|
||||||
|
FunctionalClass = l.FunctionalClass, Amount = l.Amount, Description = l.Description,
|
||||||
|
}).ToList();
|
||||||
|
|
||||||
|
// Resolve actor user ids (AppUser.Id, stored in CreatedBy) to a display name: the linked
|
||||||
|
// Member's full name when present, otherwise the account email. Mirrors ExpenseService.
|
||||||
|
private async Task<Dictionary<string, string>> ResolveUserNamesAsync(IEnumerable<string?> userIds)
|
||||||
|
{
|
||||||
|
var ids = userIds.Where(id => !string.IsNullOrEmpty(id)).Select(id => id!).Distinct().ToList();
|
||||||
|
if (ids.Count == 0) return new();
|
||||||
|
|
||||||
|
var users = await _db.Users.AsNoTracking()
|
||||||
|
.Where(u => ids.Contains(u.Id))
|
||||||
|
.Select(u => new { u.Id, u.Email, u.MemberId })
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
var memberIds = users.Where(u => u.MemberId != null).Select(u => u.MemberId!.Value).ToHashSet();
|
||||||
|
var memberNames = await _db.Members.AsNoTracking()
|
||||||
|
.Where(m => memberIds.Contains(m.Id))
|
||||||
|
.ToDictionaryAsync(m => m.Id, m => $"{m.FirstName_en} {m.LastName_en}".Trim());
|
||||||
|
|
||||||
|
return users.ToDictionary(
|
||||||
|
u => u.Id,
|
||||||
|
u => u.MemberId != null && memberNames.TryGetValue(u.MemberId.Value, out var name) && name.Length > 0
|
||||||
|
? name
|
||||||
|
: (u.Email ?? u.Id));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,17 +53,24 @@ public class FinanceDashboardService : IFinanceDashboardService
|
|||||||
DateOnly? from, DateOnly? to, int? ministryId, int? categoryGroupId)
|
DateOnly? from, DateOnly? to, int? ministryId, int? categoryGroupId)
|
||||||
{
|
{
|
||||||
var q = PaidApproved(from, to);
|
var q = PaidApproved(from, to);
|
||||||
if (ministryId.HasValue) q = q.Where(e => e.MinistryId == ministryId.Value);
|
if (ministryId.HasValue) q = q.Where(e => e.MinistryId == ministryId.Value);
|
||||||
if (categoryGroupId.HasValue) q = q.Where(e => e.CategoryGroupId == categoryGroupId.Value);
|
|
||||||
|
|
||||||
// Group by the deepest level whose parent id is supplied.
|
// Lines belonging to the scoped (Paid+Approved, optionally ministry-filtered) expenses.
|
||||||
|
var scopedLines = from l in _db.ExpenseLines
|
||||||
|
join e in q on l.ExpenseId equals e.Id
|
||||||
|
select l;
|
||||||
|
|
||||||
|
// Group by the deepest level whose parent id is supplied. Category levels aggregate
|
||||||
|
// over LINES (line amounts); the ministry level uses the header total to avoid
|
||||||
|
// double-counting a multi-line expense across its lines.
|
||||||
List<(int Id, decimal Amount)> grouped;
|
List<(int Id, decimal Amount)> grouped;
|
||||||
if (categoryGroupId.HasValue)
|
if (categoryGroupId.HasValue)
|
||||||
grouped = (await q.GroupBy(e => e.SubCategoryId)
|
grouped = (await scopedLines.Where(l => l.CategoryGroupId == categoryGroupId.Value)
|
||||||
|
.GroupBy(l => l.SubCategoryId)
|
||||||
.Select(g => new { Id = g.Key, Amount = g.Sum(x => x.Amount) }).ToListAsync())
|
.Select(g => new { Id = g.Key, Amount = g.Sum(x => x.Amount) }).ToListAsync())
|
||||||
.Select(x => (x.Id, x.Amount)).ToList();
|
.Select(x => (x.Id, x.Amount)).ToList();
|
||||||
else if (ministryId.HasValue)
|
else if (ministryId.HasValue)
|
||||||
grouped = (await q.GroupBy(e => e.CategoryGroupId)
|
grouped = (await scopedLines.GroupBy(l => l.CategoryGroupId)
|
||||||
.Select(g => new { Id = g.Key, Amount = g.Sum(x => x.Amount) }).ToListAsync())
|
.Select(g => new { Id = g.Key, Amount = g.Sum(x => x.Amount) }).ToListAsync())
|
||||||
.Select(x => (x.Id, x.Amount)).ToList();
|
.Select(x => (x.Id, x.Amount)).ToList();
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using ROLAC.API.Data;
|
||||||
|
using ROLAC.API.DTOs.Finance;
|
||||||
|
using ROLAC.API.Entities;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Read-only aggregation that produces the IRS Form 990 Part IX Statement of Functional
|
||||||
|
/// Expenses. Expense scope matches FinanceDashboardService: Paid + Approved only.
|
||||||
|
/// Each expense line is categorized independently, so one invoice can span multiple lines.
|
||||||
|
/// </summary>
|
||||||
|
public class Form990ReportService : IForm990ReportService
|
||||||
|
{
|
||||||
|
private readonly AppDbContext _db;
|
||||||
|
public Form990ReportService(AppDbContext db) => _db = db;
|
||||||
|
|
||||||
|
public async Task<List<Form990ExpenseLineDto>> GetLinesAsync() =>
|
||||||
|
await _db.Form990ExpenseLines.AsNoTracking().Where(l => l.IsActive)
|
||||||
|
.OrderBy(l => l.SortOrder)
|
||||||
|
.Select(l => new Form990ExpenseLineDto
|
||||||
|
{
|
||||||
|
Id = l.Id,
|
||||||
|
LineCode = l.LineCode,
|
||||||
|
Name_en = l.Name_en,
|
||||||
|
Name_zh = l.Name_zh,
|
||||||
|
SortOrder = l.SortOrder,
|
||||||
|
})
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
public async Task<FunctionalExpenseStatementDto> GetFunctionalExpenseStatementAsync(DateOnly? from, DateOnly? to)
|
||||||
|
{
|
||||||
|
var lines = await _db.Form990ExpenseLines.AsNoTracking()
|
||||||
|
.Where(l => l.IsActive).OrderBy(l => l.SortOrder).ToListAsync();
|
||||||
|
var fallbackId = lines.FirstOrDefault(l => l.LineCode == "24")?.Id;
|
||||||
|
|
||||||
|
var expenses = _db.Expenses.Where(e => e.Status == "Paid" || e.Status == "Approved");
|
||||||
|
if (from.HasValue) expenses = expenses.Where(e => e.ExpenseDate >= from.Value);
|
||||||
|
if (to.HasValue) expenses = expenses.Where(e => e.ExpenseDate <= to.Value);
|
||||||
|
|
||||||
|
var rows = await (
|
||||||
|
from e in expenses
|
||||||
|
join l in _db.ExpenseLines on e.Id equals l.ExpenseId
|
||||||
|
join m in _db.Ministries on e.MinistryId equals m.Id
|
||||||
|
join sub in _db.ExpenseSubCategories on l.SubCategoryId equals sub.Id
|
||||||
|
join grp in _db.ExpenseCategoryGroups on l.CategoryGroupId equals grp.Id
|
||||||
|
select new
|
||||||
|
{
|
||||||
|
l.Amount,
|
||||||
|
l.FunctionalClass,
|
||||||
|
MinistryDefault = m.DefaultFunctionalClass,
|
||||||
|
SubLineId = sub.Form990LineId,
|
||||||
|
GroupLineId = grp.Form990LineId,
|
||||||
|
}).ToListAsync();
|
||||||
|
|
||||||
|
var acc = new Dictionary<int, (decimal P, decimal M, decimal F)>();
|
||||||
|
var unmapped = 0;
|
||||||
|
|
||||||
|
foreach (var r in rows)
|
||||||
|
{
|
||||||
|
var function = FunctionalClasses.Normalize(r.FunctionalClass ?? r.MinistryDefault);
|
||||||
|
var lineId = r.SubLineId ?? r.GroupLineId ?? fallbackId;
|
||||||
|
if (lineId is null) continue;
|
||||||
|
|
||||||
|
if (r.SubLineId is null) unmapped++;
|
||||||
|
|
||||||
|
var cur = acc.GetValueOrDefault(lineId.Value);
|
||||||
|
acc[lineId.Value] = function switch
|
||||||
|
{
|
||||||
|
FunctionalClasses.ManagementGeneral => (cur.P, cur.M + r.Amount, cur.F),
|
||||||
|
FunctionalClasses.Fundraising => (cur.P, cur.M, cur.F + r.Amount),
|
||||||
|
_ => (cur.P + r.Amount, cur.M, cur.F),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var dto = new FunctionalExpenseStatementDto { UnmappedExpenseCount = unmapped };
|
||||||
|
foreach (var line in lines)
|
||||||
|
{
|
||||||
|
var v = acc.GetValueOrDefault(line.Id);
|
||||||
|
dto.Rows.Add(new FunctionalExpenseRowDto
|
||||||
|
{
|
||||||
|
LineCode = line.LineCode, Name_en = line.Name_en, Name_zh = line.Name_zh,
|
||||||
|
Program = v.P, ManagementGeneral = v.M, Fundraising = v.F, Total = v.P + v.M + v.F,
|
||||||
|
});
|
||||||
|
dto.ProgramTotal += v.P;
|
||||||
|
dto.ManagementGeneralTotal += v.M;
|
||||||
|
dto.FundraisingTotal += v.F;
|
||||||
|
}
|
||||||
|
dto.GrandTotal = dto.ProgramTotal + dto.ManagementGeneralTotal + dto.FundraisingTotal;
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,16 @@ public interface IAuthService
|
|||||||
string rawRefreshToken,
|
string rawRefreshToken,
|
||||||
string? ipAddress = null);
|
string? ipAddress = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Issues a fresh access token + refresh token for an already-verified user (no password
|
||||||
|
/// check). Stores the refresh token and returns the raw value for the caller to put in the
|
||||||
|
/// HttpOnly cookie. Used by passwordless flows such as accepting an invitation link.
|
||||||
|
/// </summary>
|
||||||
|
Task<(LoginResponse Response, string RawRefreshToken)> IssueSessionAsync(
|
||||||
|
AppUser user,
|
||||||
|
string? ipAddress = null,
|
||||||
|
string? deviceInfo = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Revokes the refresh token identified by its raw value.
|
/// Revokes the refresh token identified by its raw value.
|
||||||
/// Silently succeeds if the token is not found.
|
/// Silently succeeds if the token is not found.
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
using ROLAC.API.DTOs.Expense;
|
||||||
|
namespace ROLAC.API.Services;
|
||||||
|
|
||||||
|
public interface IExpenseSnapshotService
|
||||||
|
{
|
||||||
|
Task<List<ExpenseSnapshotDto>> GetAllAsync();
|
||||||
|
Task<ExpenseSnapshotDto?> GetByIdAsync(int id);
|
||||||
|
Task<int> CreateAsync(CreateExpenseSnapshotRequest r);
|
||||||
|
Task UpdateAsync(int id, UpdateExpenseSnapshotRequest r);
|
||||||
|
Task DeleteAsync(int id);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using ROLAC.API.DTOs.Finance;
|
||||||
|
namespace ROLAC.API.Services;
|
||||||
|
|
||||||
|
public interface IForm990ReportService
|
||||||
|
{
|
||||||
|
Task<FunctionalExpenseStatementDto> GetFunctionalExpenseStatementAsync(DateOnly? from, DateOnly? to);
|
||||||
|
Task<List<Form990ExpenseLineDto>> GetLinesAsync();
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using ROLAC.API.DTOs.Invitations;
|
||||||
|
using ROLAC.API.Entities;
|
||||||
|
|
||||||
|
namespace ROLAC.API.Services;
|
||||||
|
|
||||||
|
public interface IInvitationService
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Generates a single-use, 7-day invitation link for a member. Auto-creates the member's
|
||||||
|
/// login account (no password) when none exists, and revokes any prior unused invitation for
|
||||||
|
/// that account. Returns the raw token (shown once) and its expiry.
|
||||||
|
/// Throws <see cref="InvalidOperationException"/> when the member is missing or has no email.
|
||||||
|
/// </summary>
|
||||||
|
Task<CreateInvitationResult> CreateAsync(CreateInvitationRequest request);
|
||||||
|
|
||||||
|
/// <summary>Checks whether a raw token is still usable, without mutating it.</summary>
|
||||||
|
Task<ValidateInvitationResult> ValidateAsync(string rawToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Consumes an invitation: validates the token, sets the account password (enforcing the
|
||||||
|
/// Identity policy), and marks the invitation used. Returns the account on success, or an
|
||||||
|
/// error message describing why it failed (invalid/expired/used token or a policy violation).
|
||||||
|
/// </summary>
|
||||||
|
Task<(AppUser? User, string? Error)> AcceptAsync(string rawToken, string newPassword);
|
||||||
|
|
||||||
|
/// <summary>E-mails an already-generated invitation link to the member via IEmailService.</summary>
|
||||||
|
Task SendEmailAsync(int memberId, string link);
|
||||||
|
}
|
||||||
@@ -22,6 +22,13 @@ public interface IMealAttendanceService
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
Task<AttendanceCountsDto> SetAsync(DateOnly date, string category, int value);
|
Task<AttendanceCountsDto> SetAsync(DateOnly date, string category, int value);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Overwrites all three age-group columns for <paramref name="date"/> with absolute
|
||||||
|
/// values (each clamped at zero), creating the row if it does not exist, and returns
|
||||||
|
/// the resulting authoritative counts. Used by the back-office Sunday-attendance editor.
|
||||||
|
/// </summary>
|
||||||
|
Task<AttendanceCountsDto> SetCountsAsync(DateOnly date, int adult, int youth, int kid);
|
||||||
|
|
||||||
/// <summary>Returns the daily counts within the inclusive date range, ordered by date (for the dashboard).</summary>
|
/// <summary>Returns the daily counts within the inclusive date range, ordered by date (for the dashboard).</summary>
|
||||||
Task<IReadOnlyList<AttendanceCountsDto>> GetRangeAsync(DateOnly from, DateOnly to);
|
Task<IReadOnlyList<AttendanceCountsDto>> GetRangeAsync(DateOnly from, DateOnly to);
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user