diff --git a/db/receipts-gn-permit.sql b/db/receipts-gn-permit.sql new file mode 100644 index 0000000..4d77bde --- /dev/null +++ b/db/receipts-gn-permit.sql @@ -0,0 +1,11 @@ +-- Permit receipts: the grains (GN) permit number of the receipt, "رقم الارسالية" (legacy form field GNPN, which the legacy never stored). +-- Run in the primary (NAFITHTCS) schema BEFORE deploying this version of the receipts screen. Safe to re-run; not run by the app. +DECLARE + n NUMBER; +BEGIN + SELECT COUNT(*) INTO n FROM user_tab_columns WHERE table_name = 'PERMITS_RECEIPTS' AND column_name = 'GN_PN'; + IF n = 0 THEN + EXECUTE IMMEDIATE 'ALTER TABLE PERMITS_RECEIPTS ADD (GN_PN NUMBER)'; + END IF; +END; +/ diff --git a/docs/ENVIRONMENTS.md b/docs/ENVIRONMENTS.md index 756cb2f..5cc52da 100644 --- a/docs/ENVIRONMENTS.md +++ b/docs/ENVIRONMENTS.md @@ -67,6 +67,7 @@ Apply these scripts once per database (not run by the application), in this orde 9. `db/refinery-op-permissions.sql` - role REFINERY_OP (موظف عطاء الصرف): the الارساليات screen, the شحن الديزل (Excel) report, print and the payment actions (13 keys); part 1 (role row, NTP schema) is only needed where the row is missing, part 2 (primary schema) writes the rows (safe to re-run). Everything else of the refinery module stays with REFINERY_MGR and SU 10. `db/registrar-permissions.sql` - registrar (التسجيل العام: رخص السائقين / الشاحنات / المقطورات): screens and edit / confirm / reject keys for role GOO only, reports SU only (10 rows); SU needs none (safe to re-run). Setting `Registrar__AttachmentsBaseUrl` (default: the legacy upload host, where the pictures stay) 11. `db/receipts-permissions.sql` - permit receipts (سندات القبض والمطالبات المالية): screen and action keys `receipts.*` from the legacy STATUS_ACTION_MATRIX (32 rows); SU needs none (safe to re-run) +11b. `db/receipts-gn-permit.sql` - adds PERMITS_RECEIPTS.GN_PN (رقم الارسالية of the receipt); run it in the primary schema BEFORE deploying the receipts screen of this version (safe to re-run) 12. `db/communication-permissions.sql` - voice communication screen (شاشة موظف الاتصالات): GTO gets the screen and the blacklist action, the Excel report is SU only (safe to re-run). Setting `Grains__Communication__AutoPostponeMinutes` (default 30, unverified) **Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU diff --git a/src/NTP.Api/Controllers/V1/Receipts/ReceiptsController.cs b/src/NTP.Api/Controllers/V1/Receipts/ReceiptsController.cs index fb10fc1..f8dcbc2 100644 --- a/src/NTP.Api/Controllers/V1/Receipts/ReceiptsController.cs +++ b/src/NTP.Api/Controllers/V1/Receipts/ReceiptsController.cs @@ -59,7 +59,7 @@ public sealed class ReceiptsController(IReceiptService receipts) : ControllerBas receipts.GetLogAsync(id, new PageRequest(page, pageSize), ct); [HttpPost] - public Task Create([FromBody] CreateReceiptRequest request, CancellationToken ct) => receipts.CreateAsync(request, ct); + public Task Create([FromBody] CreateReceiptRequest request, CancellationToken ct) => receipts.CreateAsync(request, ct, Ip); [HttpPut("{id:long}")] public Task Update(long id, [FromBody] UpdateReceiptRequest request, CancellationToken ct) => receipts.UpdateAsync(id, request, ct); diff --git a/src/NTP.Application/Receipts/IReceipts.cs b/src/NTP.Application/Receipts/IReceipts.cs index 86bbef2..d7bb099 100644 --- a/src/NTP.Application/Receipts/IReceipts.cs +++ b/src/NTP.Application/Receipts/IReceipts.cs @@ -49,7 +49,7 @@ public interface IReceiptService Task GetAsync(long id, CancellationToken ct); Task> GetLogAsync(long id, PageRequest page, CancellationToken ct); Task GetLookupsAsync(CancellationToken ct); - Task CreateAsync(CreateReceiptRequest request, CancellationToken ct); + Task CreateAsync(CreateReceiptRequest request, CancellationToken ct, string? ip = null); Task ConfirmAsync(long id, string? ip, CancellationToken ct); Task UpdateAsync(long id, UpdateReceiptRequest request, CancellationToken ct); Task PaidAsync(long id, string? ip, CancellationToken ct); diff --git a/src/NTP.Application/Receipts/ReceiptAudit.cs b/src/NTP.Application/Receipts/ReceiptAudit.cs index 40f00fa..17913ff 100644 --- a/src/NTP.Application/Receipts/ReceiptAudit.cs +++ b/src/NTP.Application/Receipts/ReceiptAudit.cs @@ -148,7 +148,7 @@ public static class ReceiptAudit public static (List Lines, List Audited, List Identical) Compare( IReadOnlyList file, IReadOnlyList receipts, AuditLookups lk, string? confirmationBy, Func statusName) { - var lines = new List { new("رقم التصريح", "حالة التصريح", "رقم الوصل", "الأجور", "حالة الوصل", "تاريخ الوصل", "النتيجة", "الملاحظات") }; + var lines = new List { new("رقم التصريح", "حالة التصريح", "رقم الوصل", "المبلغ", "حالة الوصل", "تاريخ الوصل", "النتيجة", "الملاحظات") }; var audited = new List(); var identical = new List(); var pns = new List(); diff --git a/src/NTP.Application/Receipts/ReceiptModels.cs b/src/NTP.Application/Receipts/ReceiptModels.cs index 84d21c1..0130c0c 100644 --- a/src/NTP.Application/Receipts/ReceiptModels.cs +++ b/src/NTP.Application/Receipts/ReceiptModels.cs @@ -6,6 +6,8 @@ public class ReceiptRow public long Id { get; set; } public long? ReceiptNo { get; set; } public long? Pn { get; set; } + /// The grains (GN) permit number of the truck, "رقم الارسالية" (column GN_PN, db/receipts-gn-permit.sql). + public long? GnPn { get; set; } public string? ShipmentMode { get; set; } public string? FmShipmentMode { get; set; } /// The cargo type names, "first - second" for a double move (view column CARGO_TYPE). @@ -61,6 +63,7 @@ public sealed class CreateReceiptRequest public int Credit { get; set; } public long ReceiptType { get; set; } public string? Pn { get; set; } + public string? GnPn { get; set; } public string? FmShipmentMode { get; set; } public string? ShipmentMode { get; set; } public string? Tn { get; set; } diff --git a/src/NTP.Application/Receipts/ReceiptRules.cs b/src/NTP.Application/Receipts/ReceiptRules.cs index c45709b..0805c05 100644 --- a/src/NTP.Application/Receipts/ReceiptRules.cs +++ b/src/NTP.Application/Receipts/ReceiptRules.cs @@ -45,8 +45,8 @@ public static class ReceiptRules public static bool IsStatus(string? status, string expected) => string.Equals(status, expected, StringComparison.OrdinalIgnoreCase); - /// Status of a new receipt: cash (credit 0) RECEIVED, a financial claim UNPAID. - public static string StatusForNew(int credit) => credit == 0 ? ReceiptStatus.Received : ReceiptStatus.Unpaid; + /// Status of a new receipt: PAID (owner decision; the legacy made cash RECEIVED and claims UNPAID). + public static string StatusForNew(int credit) => ReceiptStatus.Paid; public static bool CanUpdate(string? s) => IsStatus(s, ReceiptStatus.Received) || IsStatus(s, ReceiptStatus.Unpaid); public static bool CanConfirm(string? s) => IsStatus(s, ReceiptStatus.NotReceived); diff --git a/src/NTP.Application/Receipts/ReceiptService.cs b/src/NTP.Application/Receipts/ReceiptService.cs index a35e71e..58e580a 100644 --- a/src/NTP.Application/Receipts/ReceiptService.cs +++ b/src/NTP.Application/Receipts/ReceiptService.cs @@ -47,7 +47,7 @@ public sealed class ReceiptService( // ---------------------------------------------------------------- create / update - public async Task CreateAsync(CreateReceiptRequest request, CancellationToken ct) + public async Task CreateAsync(CreateReceiptRequest request, CancellationToken ct, string? ip = null) { await Require(PermissionKeys.ReceiptsCreate, ct); var failures = new List(); @@ -57,8 +57,6 @@ public sealed class ReceiptService( Need("trn", !string.IsNullOrWhiteSpace(request.Trn)); Need("nnpn", !string.IsNullOrWhiteSpace(request.Nnpn)); Need("drvr", !string.IsNullOrWhiteSpace(request.Drvr)); - Need("dln", !string.IsNullOrWhiteSpace(request.Dln)); - Need("dled", !string.IsNullOrWhiteSpace(request.Dled)); Need("shipmentMode", !string.IsNullOrWhiteSpace(request.ShipmentMode)); Need("receiptType", request.ReceiptType > 0); Need("credit", request.Credit is 0 or 1); @@ -71,7 +69,15 @@ public sealed class ReceiptService( if (request.ReceiptType is 8 or 9 or 10 && !await repository.PermitMatchesTypeAsync(request.ReceiptType, pn, ct)) throw new BusinessException(ReceiptErrors.DataCheck, ReceiptMessages.DataCheck); - var id = await repository.InsertAsync(request, type.Fees ?? 0, ReceiptRules.StatusForNew(request.Credit), user.UserId, ct); + // a receipt is created already paid (owner decision); the creation is logged like the legacy CREATE log + var status = ReceiptRules.StatusForNew(request.Credit); + var id = await unitOfWork.ExecuteInTransactionAsync(async c => + { + var newId = await repository.InsertAsync(request, type.Fees ?? 0, status, user.UserId, c); + var (old, @new) = ReceiptRules.CreateLog(status); + await repository.AddLogAsync(newId, "CREATE", old, @new, user.Id, ip, null, c); + return newId; + }, ct); return new ReceiptResult(ReceiptMessages.Done, id); } @@ -223,7 +229,7 @@ public sealed class ReceiptService( { new("counter", "متسلسل", "#"), new("receiptNo", "الرقم", "Receipt no."), new("pn", "رقم التصريح", "Permit"), new("company", "اسم الشركة", "Company"), new("cargo", "النمط", "Cargo type"), new("tn", "رقم الشاحنة", "Truck"), new("trn", "رقم المقطورة", "Trailer"), new("drvr", "اسم السائق", "Driver"), - new("nnpn", "الرقم الوطني", "National no."), new("fees", "الأجور", "Fees"), new("credit", "النوع", "Kind"), new("creationDate", "تاريخ الانشاء", "Created"), + new("nnpn", "الرقم الوطني", "National no."), new("fees", "المبلغ", "Amount"), new("credit", "النوع", "Kind"), new("creationDate", "تاريخ الانشاء", "Created"), new("createdBy", "إنشاء بواسطة", "Created by"), new("confirmationDate", "تاريخ التأكيد", "Confirmed"), new("confirmationBy", "تأكيد بواسطة", "Confirmed by"), new("confirmationName", "اسم المؤكد", "Confirmed by (name)"), new("status", "الحالة", "Status"), new("source", "طريقة الدفع", "Payment"), }; @@ -284,7 +290,7 @@ public sealed class ReceiptService( var cols = new List { - new("pn", "رقم التصريح", "Permit"), new("permitStatus", "حالة التصريح", "Permit status"), new("receiptNo", "رقم الوصل", "Receipt"), new("fees", "الأجور", "Fees"), + new("pn", "رقم التصريح", "Permit"), new("permitStatus", "حالة التصريح", "Permit status"), new("receiptNo", "رقم الوصل", "Receipt"), new("fees", "المبلغ", "Amount"), new("receiptStatus", "حالة الوصل", "Receipt status"), new("date", "تاريخ الوصل", "Receipt date"), new("result", "النتيجة", "Result"), new("remark", "الملاحظات", "Remarks"), }; var rows = lines.Skip(1).Select(l => (IReadOnlyDictionary)new Dictionary diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Receipts/ReceiptRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Receipts/ReceiptRepository.cs index 243f5d1..ef5fed4 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Receipts/ReceiptRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Receipts/ReceiptRepository.cs @@ -15,7 +15,7 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger(OracleSql.Count(baseSql), p, ct); if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); p.Add("MinRow", page.MinRow); @@ -61,7 +61,10 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger GetAsync(long id, CancellationToken ct = default) => - QueryFirstAsync(Select + " AND p.ID = :Id", new { Id = id }, ct); + GetCoreAsync(id, ct); + + private async Task GetCoreAsync(long id, CancellationToken ct) => + await QueryFirstAsync(await SelectAsync(ct) + " AND p.ID = :Id", new { Id = id }, ct); public async Task> GetLogAsync(long id, PageRequest page, CancellationToken ct = default) { @@ -113,17 +116,18 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger("SELECT SEQ_PERMITS_RECEIPTS.NEXTVAL FROM DUAL", null, ct); var (fm, sm) = ReceiptRules.SplitModes(r.FmShipmentMode, r.ShipmentMode); - var number = r.Credit == 0 ? CashNumberSql : ClaimNumberSql; + var number = CashNumberSql; // every new receipt is created paid and continues the one cash series (202620001, 202620002 ...); the claim series 2099xxxxx is no longer used // CREATION_DATE: the legacy insert left it to the column default; CONFIRMATION_DATE stays empty, CONFIRMATION_BY is the creator - await ExecuteAsync($""" - INSERT INTO PERMITS_RECEIPTS (ID, RECEIPT_NO, PN, SHIPMENTMODE, FMSHIPMENTMODE, CRN, CA_CODE, TN, TRN, DRVR, NNPN, MOBILE, CREATION_DATE, CREATED_BY, STATUSCODE, + var gn = await HasGnPnAsync(ct); + await ExecuteAsync(Gn($""" + INSERT INTO PERMITS_RECEIPTS (ID, RECEIPT_NO, PN, GN_PN, SHIPMENTMODE, FMSHIPMENTMODE, CRN, CA_CODE, TN, TRN, DRVR, NNPN, MOBILE, CREATION_DATE, CREATED_BY, STATUSCODE, DLN, DLED, SCAC, FEES, RECEIPT_TYPE, CONFIRMATION_BY, FMINBOUNDTYPECODE, DESTINATIONADDRESSID, ORIGINADDRESSID, INBOUNDTYPECODE, CREDIT) - VALUES (:Id, ({number}), :Pn, :Sm, :Fm, :Crn, :CaCode, :Tn, :Trn, :Drvr, :Nnpn, :Mobile, SYSDATE, :User, :Status, - :Dln, :Dled, :Scac, :Fees, :Type, :User, NULL, :Dest, :Origin, :Inbound, :Credit) - """, new + VALUES (:Id, ({number}), :Pn, :GnPn, :Sm, :Fm, :Crn, :CaCode, :Tn, :Trn, :Drvr, :Nnpn, :Mobile, SYSDATE, :UserLogin, :Status, + :Dln, :Dled, :Scac, :Fees, :Type, :UserLogin, NULL, :Dest, :Origin, :Inbound, :Credit) + """, gn), new { - Id = id, Pn = long.Parse(r.Pn!.Trim(), CultureInfo.InvariantCulture), Sm = sm, Fm = fm, Crn = ToLong(r.Crn), CaCode = r.CaCode, Tn = Clean(r.Tn), Trn = Clean(r.Trn), - Drvr = Clean(r.Drvr), Nnpn = Clean(r.Nnpn), Mobile = Clean(r.Mobile), User = Fit(userLogin, 300), Status = status, Dln = Clean(r.Dln), Dled = Clean(r.Dled), + Id = id, Pn = long.Parse(r.Pn!.Trim(), CultureInfo.InvariantCulture), GnPn = ToLong(r.GnPn), Sm = sm, Fm = fm, Crn = ToLong(r.Crn), CaCode = r.CaCode, Tn = Clean(r.Tn), Trn = Clean(r.Trn), + Drvr = Clean(r.Drvr), Nnpn = Clean(r.Nnpn), Mobile = Clean(r.Mobile), UserLogin = Fit(userLogin, 300), Status = status, Dln = Clean(r.Dln), Dled = Clean(r.Dled), r.Scac, Fees = fees, Type = r.ReceiptType, Dest = r.DestinationAddressId, Origin = r.OriginAddressId, Inbound = Clean(r.InboundTypeCode), r.Credit, }, ct); return id; @@ -141,22 +145,23 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger InsertPaidCopyAsync(long sourceId, CancellationToken ct = default) { var id = await ExecuteScalarAsync("SELECT SEQ_PERMITS_RECEIPTS.NEXTVAL FROM DUAL", null, ct); - await ExecuteAsync($""" - INSERT INTO PERMITS_RECEIPTS (ID, RECEIPT_NO, PERMIT_ID, PN, SHIPMENTMODE, FMSHIPMENTMODE, CRN, CA_CODE, TN, TRN, DRVR, NNPN, MOBILE, CREATION_DATE, CREATED_BY, STATUSCODE, + var gn = await HasGnPnAsync(ct); + await ExecuteAsync(Gn($""" + INSERT INTO PERMITS_RECEIPTS (ID, RECEIPT_NO, PERMIT_ID, PN, GN_PN, SHIPMENTMODE, FMSHIPMENTMODE, CRN, CA_CODE, TN, TRN, DRVR, NNPN, MOBILE, CREATION_DATE, CREATED_BY, STATUSCODE, DLN, DLED, SCAC, FEES, RECEIPT_TYPE, PERMIT_STATUS, CONFIRMATION_BY, FMINBOUNDTYPECODE, DESTINATIONADDRESSID, ORIGINADDRESSID, INBOUNDTYPECODE, CREDIT, REQUEST_ID) - SELECT :Id, ({CashNumberSql}), s.PERMIT_ID, s.PN, s.SHIPMENTMODE, s.FMSHIPMENTMODE, s.CRN, s.CA_CODE, s.TN, s.TRN, s.DRVR, s.NNPN, s.MOBILE, SYSDATE, s.CREATED_BY, 'RECEIVED', + SELECT :Id, ({CashNumberSql}), s.PERMIT_ID, s.PN, s.GN_PN, s.SHIPMENTMODE, s.FMSHIPMENTMODE, s.CRN, s.CA_CODE, s.TN, s.TRN, s.DRVR, s.NNPN, s.MOBILE, SYSDATE, s.CREATED_BY, 'RECEIVED', s.DLN, s.DLED, s.SCAC, s.FEES, s.RECEIPT_TYPE, s.PERMIT_STATUS, s.CONFIRMATION_BY, s.FMINBOUNDTYPECODE, s.DESTINATIONADDRESSID, s.ORIGINADDRESSID, s.INBOUNDTYPECODE, 0, s.REQUEST_ID FROM PERMITS_RECEIPTS s WHERE s.ID = :Source - """, new { Id = id, Source = sourceId }, ct); + """, gn), new { Id = id, Source = sourceId }, ct); return id; } public async Task ConfirmAsync(long id, string userLogin, CancellationToken ct = default) => await ExecuteAsync(""" - UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'RECEIVED', CONFIRMATION_DATE = SYSDATE, CONFIRMATION_BY = :User WHERE ID = :Id AND STATUSCODE = 'NOT_RECEIVED' - """, new { Id = id, User = Fit(userLogin, 300) }, ct) > 0; + UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'RECEIVED', CONFIRMATION_DATE = SYSDATE, CONFIRMATION_BY = :UserLogin WHERE ID = :Id AND STATUSCODE = 'NOT_RECEIVED' + """, new { Id = id, UserLogin = Fit(userLogin, 300) }, ct) > 0; public async Task UpdateAsync(long id, UpdateReceiptRequest r, string userLogin, CancellationToken ct = default) { @@ -164,11 +169,11 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger 0; } @@ -183,10 +188,10 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger RevokeAsync(long id, string fromStatus, long? reason, string? note, string userLogin, CancellationToken ct = default) { - var p = new DynamicParameters(new { Id = id, From = fromStatus, User = Fit(userLogin, 300) }); + var p = new DynamicParameters(new { Id = id, FromX = fromStatus, UserLogin = Fit(userLogin, 300) }); var set = ""; if (reason is { } r) { set = ", REJECT_REASON = :Reason, REJECT_REASON_NOTE = :Note"; p.Add("Reason", r); p.Add("Note", note); } - return await ExecuteAsync($"UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'RVKD', REVOKE_DATE = SYSDATE, REVOKE_BY = :User, FEES = 0{set} WHERE ID = :Id AND STATUSCODE = :From", p, ct) > 0; + return await ExecuteAsync($"UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'RVKD', REVOKE_DATE = SYSDATE, REVOKE_BY = :UserLogin, FEES = 0{set} WHERE ID = :Id AND STATUSCODE = :FromX", p, ct) > 0; } public async Task RejectRevokeAsync(long id, CancellationToken ct = default) => @@ -245,16 +250,16 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger= :From AND r.CONFIRMATION_DATE < :To"); - p.Add("From", from.Date); p.Add("To", to.Date.AddDays(1)); + sql.Append(" AND r.CONFIRMATION_DATE >= :FromX AND r.CONFIRMATION_DATE < :ToX"); + p.Add("FromX", from.Date); p.Add("ToX", to.Date.AddDays(1)); } } - if (!string.IsNullOrWhiteSpace(f.ConfirmationBy)) { sql.Append(" AND LOWER(p.CONFIRMATION_BY) = LOWER(:By)"); p.Add("By", f.ConfirmationBy.Trim()); } + if (!string.IsNullOrWhiteSpace(f.ConfirmationBy)) { sql.Append(" AND LOWER(p.CONFIRMATION_BY) = LOWER(:ByUser)"); p.Add("ByUser", f.ConfirmationBy.Trim()); } sql.Append(" ORDER BY p.RECEIPT_NO ASC"); return QueryAsync(sql.ToString(), p, ct); } @@ -269,6 +274,25 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger HasGnPnAsync(CancellationToken ct) + { + if (gnPnKnown) return true; + if (DateTime.UtcNow - gnPnCheckedAt < TimeSpan.FromMinutes(1)) return false; + gnPnCheckedAt = DateTime.UtcNow; + gnPnKnown = await ExecuteScalarAsync("SELECT COUNT(*) FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'PERMITS_RECEIPTS' AND COLUMN_NAME = 'GN_PN'", null, ct) > 0; + return gnPnKnown; + } + + private async Task SelectAsync(CancellationToken ct) => + await HasGnPnAsync(ct) ? Select : Select.Replace("r.GN_PN AS GnPn", "CAST(NULL AS NUMBER) AS GnPn"); + + private static string Gn(string sql, bool has) => + has ? sql : sql.Replace("GN_PN, ", "").Replace(":GnPn, ", "").Replace("s.GN_PN, ", ""); + private static string? Clean(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); private static string Fit(string v, int max) => v.Length <= max ? v : v[..max]; private static long? ToLong(string? s) => long.TryParse(s?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? n : null; diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Registrar/RegistrarRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Registrar/RegistrarRepository.cs index cba7152..3691da2 100644 --- a/src/NTP.Infrastructure/Persistence/Repositories/Registrar/RegistrarRepository.cs +++ b/src/NTP.Infrastructure/Persistence/Repositories/Registrar/RegistrarRepository.cs @@ -52,7 +52,7 @@ internal sealed class RegistrarRepository(IDbSession session, ILogger ChangeStatusAsync(RegistrarKind kind, long id, string fromStatus, string toStatus, string userId, string? revokeReason, CancellationToken ct = default) { - var p = new DynamicParameters(new { Id = id, From = fromStatus, To = toStatus, UserId = Fit(userId, 50) }); + var p = new DynamicParameters(new { Id = id, FromX = fromStatus, ToX = toStatus, UserId = Fit(userId, 50) }); var reason = ""; if (revokeReason is not null) { reason = ", REVOKE_REASON = :Reason"; p.Add("Reason", Fit(revokeReason, 100)); } var rows = await ExecuteAsync( - $"UPDATE {Table(kind)} SET STATUS_CODE = :To, UPDATED_BY = :UserId, LAST_UPDATE_DATE = SYSDATE{reason} WHERE ID = :Id AND STATUS_CODE = :From", p, ct); + $"UPDATE {Table(kind)} SET STATUS_CODE = :ToX, UPDATED_BY = :UserId, LAST_UPDATE_DATE = SYSDATE{reason} WHERE ID = :Id AND STATUS_CODE = :FromX", p, ct); return rows > 0; } diff --git a/tests/NTP.Tests/Receipts/ReceiptTests.cs b/tests/NTP.Tests/Receipts/ReceiptTests.cs index 530aee8..e4d5576 100644 --- a/tests/NTP.Tests/Receipts/ReceiptTests.cs +++ b/tests/NTP.Tests/Receipts/ReceiptTests.cs @@ -37,8 +37,8 @@ public class ReceiptRulesTests Assert.False(ReceiptRules.CanPrint("RVKD")); Assert.True(ReceiptRules.CanRevokeAudited("AUDITED")); Assert.True(ReceiptRules.CanDecideRevoke("PENDING_RVKD")); - Assert.Equal("RECEIVED", ReceiptRules.StatusForNew(0)); - Assert.Equal("UNPAID", ReceiptRules.StatusForNew(1)); + Assert.Equal("PAID", ReceiptRules.StatusForNew(0)); + Assert.Equal("PAID", ReceiptRules.StatusForNew(1)); Assert.True(ReceiptRules.IsDoubleMove(1) && ReceiptRules.IsDoubleMove(2) && ReceiptRules.IsDoubleMove(10)); Assert.False(ReceiptRules.IsDoubleMove(3)); } @@ -267,11 +267,11 @@ public class ReceiptServiceTests var (svc, repo, _) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsCreate); var r = await svc.CreateAsync(NewReceipt(), default); Assert.Equal(77, r.Id); - Assert.Equal(["insert:RECEIVED:6:TS1"], repo.Writes); + Assert.Equal(["insert:PAID:6:TS1", "log:77:CREATE:{\"STATUSCODE\":\"مسدد\",\"NOTES\":\"\"}"], repo.Writes); var claim = NewReceipt(); claim.Credit = 1; await svc.CreateAsync(claim, default); - Assert.Equal("insert:UNPAID:6:TS1", repo.Writes[1]); + Assert.Equal("insert:PAID:6:TS1", repo.Writes[2]); } [Fact] diff --git a/web/src/features/receipts/api.ts b/web/src/features/receipts/api.ts index f59576c..3c10e23 100644 --- a/web/src/features/receipts/api.ts +++ b/web/src/features/receipts/api.ts @@ -12,6 +12,7 @@ export interface ReceiptRow { id: number; receiptNo: number | null; pn: number | null; + gnPn: number | null; shipmentMode: string | null; fmShipmentMode: string | null; cargoType: string | null; @@ -91,28 +92,17 @@ export interface ReceiptResult { message: string; id: number | null } export const useReceiptLookups = () => useQuery({ queryKey: ['receipts.lookups'], queryFn: () => api.get(`${BASE}/lookups`), staleTime: 5 * 60_000 }); -let cache: { at: number; promise: Promise } | null = null; -function loadLookups(): Promise { - if (!cache || Date.now() - cache.at > 60_000) { - const promise = api.get(`${BASE}/lookups`); - promise.catch(() => { cache = null; }); - cache = { at: Date.now(), promise }; - } - return cache.promise; +/** Options of the cargo types and (per company) the receipt types, built from the lookups the page already loaded (no extra request). */ +export function lookupOptions(l: ReceiptLookups | undefined) { + const cargo: OptionsLoader = { key: 'receipts.cargo.' + (l?.cargoTypes.length ?? 0), load: async () => (l?.cargoTypes ?? []).map((c): OptionItem => ({ value: c.code ?? '', label: c.name ?? '' })) }; + const types: OptionsLoader = { + key: 'receipts.types.' + (l?.types.length ?? 0), + load: async ({ parent }) => (l?.types ?? []).filter((t) => t.scac === Number(parent) && t.id !== 7) // type 7 (zero fee) was never offered + .map((t): OptionItem => ({ value: t.id, label: `${(t.caption ?? String(t.id)).trim()} - ${t.fees ?? 0} دينار` })), + }; + return { cargo, types }; } -/** Cargo types (CARGOTYPE) for the selects. */ -export const cargoOptions: OptionsLoader = { - key: 'receipts.cargo', - load: async () => (await loadLookups()).cargoTypes.map((c): OptionItem => ({ value: c.code ?? '', label: c.name ?? '' })), -}; - -/** Receipt types of the supply tender company (327); type 7 is the zero-fee one the legacy never offered. */ -export const typeOptions: OptionsLoader = { - key: 'receipts.types', - load: async () => (await loadLookups()).types.filter((t) => t.scac === 327 && t.id !== 7).map((t): OptionItem => ({ value: t.id, label: `${(t.caption ?? String(t.id)).trim()} - ${t.fees ?? 0} دينار` })), -}; - // ---------------------------------------------------------------- reads / writes const keys = () => [gridKey(GRID_RECEIPTS), ['receipts.one'], ['receipts.log']]; diff --git a/web/src/features/receipts/meta.ts b/web/src/features/receipts/meta.ts index c5bee62..3a4b488 100644 --- a/web/src/features/receipts/meta.ts +++ b/web/src/features/receipts/meta.ts @@ -1,6 +1,17 @@ import type { FieldMeta, FormMeta, GridMeta, StatusMeta } from '@/components/meta/types'; import strings from './strings'; -import { GRID_RECEIPTS, BASE, cargoOptions, typeOptions, type ReceiptRow } from './api'; +import { GRID_RECEIPTS, BASE, type ReceiptRow } from './api'; +import type { OptionsLoader } from '@/components/meta/types'; + +/** The cargo / receipt-type options built from the loaded lookups (see lookupOptions in api.ts). */ +export interface ReceiptOptions { cargo: OptionsLoader; types: OptionsLoader } + +const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +/** First and last day of the current month (the list opens on this period). */ +function currentMonth() { + const n = new Date(); + return { from: iso(new Date(n.getFullYear(), n.getMonth(), 1)), to: iso(new Date(n.getFullYear(), n.getMonth() + 1, 0)) }; +} const s = strings; @@ -19,7 +30,8 @@ const yesNo = [{ value: '1', label: s['rc.kind.1'] }, { value: '0', label: s['rc const sources = [{ value: '0', label: s['rc.source.0'] }, { value: '1', label: s['rc.source.1'] }]; /** Legacy PERMITSRECEIPTSGRID: number, permit, company, cargo, truck, fees, kind, created, status; filters number, permit, truck, trailer, cargo, kind, payment way, dates. */ -export function receiptsGrid(h: { onOpen: (r: ReceiptRow) => void }): GridMeta { +export function receiptsGrid(h: { onOpen: (r: ReceiptRow) => void; options: ReceiptOptions }): GridMeta { + const month = currentMonth(); return { key: GRID_RECEIPTS, endpoint: BASE, @@ -27,14 +39,14 @@ export function receiptsGrid(h: { onOpen: (r: ReceiptRow) => void }): GridMeta const digits = { regex: /^\d+$/, message: s['rc.digits'] }; /** Create form of company 327 (legacy PERMITSRECEIPTSMain.html): kind, type, permit, truck, trailer, driver, licence, cargo type(s). */ -export function createForm(): FormMeta { +export function createForm(o: ReceiptOptions): FormMeta { return { key: 'receipts.create.form', sections: [ { key: 'receipt', title: s['rc.sec.receipt'], columns: 2, fields: [ + { name: 'scac', type: 'select', label: s['rc.f.scac'], required: true, defaultValue: '327', options: [{ value: '327', label: s['rc.scac.327'] }, { value: '326', label: s['rc.scac.326'] }] }, { name: 'credit', type: 'select', label: s['rc.f.onCredit'], required: true, options: [{ value: '0', label: s['rc.no'] }, { value: '1', label: s['rc.yes'] }], defaultValue: '0' }, - { name: 'receiptType', type: 'select', label: s['rc.f.receiptType'], required: true, options: typeOptions }, + { name: 'receiptType', type: 'select', label: s['rc.f.receiptType'], required: true, options: o.types, dependsOn: 'scac' }, text('pn', s['rc.f.pn'], { required: true, maxLength: 15, inputKind: 'code', pattern: digits }), - { name: 'fmShipmentMode', type: 'select', label: s['rc.f.fmShipmentMode'], options: cargoOptions, hiddenWhen: { field: 'receiptType', op: 'nin', value: ['1', '2'] }, required: false, requiredWhen: { field: 'receiptType', op: 'in', value: ['1', '2'] } }, - { name: 'shipmentMode', type: 'select', label: s['rc.f.shipmentMode'], required: true, options: cargoOptions, helper: s['rc.f.shipmentModeHelp'] }, + text('gnPn', s['rc.f.gnPn'], { maxLength: 15, inputKind: 'code', pattern: digits }), + { name: 'fmShipmentMode', type: 'select', label: s['rc.f.fmShipmentMode'], options: o.cargo, hiddenWhen: { field: 'receiptType', op: 'nin', value: ['1', '2'] }, required: false, requiredWhen: { field: 'receiptType', op: 'in', value: ['1', '2'] } }, + { name: 'shipmentMode', type: 'select', label: s['rc.f.shipmentMode'], required: true, options: o.cargo, helper: s['rc.f.shipmentModeHelp'] }, ], }, { @@ -79,8 +93,6 @@ export function createForm(): FormMeta { text('trn', s['rc.f.trn'], { required: true, maxLength: 45, inputKind: 'plate' }), text('nnpn', s['rc.f.nnpn'], { required: true, maxLength: 20, inputKind: 'code' }), text('drvr', s['rc.f.drvr'], { required: true, maxLength: 300 }), - text('dln', s['rc.f.dln'], { required: true, maxLength: 50, inputKind: 'code' }), - { name: 'dled', type: 'date', label: s['rc.f.dled'], required: true }, ], }, ], @@ -88,7 +100,7 @@ export function createForm(): FormMeta { } /** Receipt page: read-only data of the receipt and, while it may be edited, the legacy edit fields (permit, cargo types, truck, trailer, driver). */ -export function detailForm(): FormMeta { +export function detailForm(o: ReceiptOptions): FormMeta { const ro = { readOnly: true } as const; return { key: 'receipts.detail.form', @@ -102,8 +114,9 @@ export function detailForm(): FormMeta { text('fees', s['rc.f.fees'], { ...ro, ltr: true }), text('companyName', s['rc.f.company'], ro), text('pn', s['rc.f.pn'], { maxLength: 15, inputKind: 'code', pattern: digits }), - { name: 'fmShipmentMode', type: 'select', label: s['rc.f.fmShipmentMode'], options: cargoOptions, hiddenWhen: { field: 'fmShipmentMode', op: 'empty' } }, - { name: 'shipmentMode', type: 'select', label: s['rc.f.shipmentMode'], options: cargoOptions }, + text('gnPn', s['rc.f.gnPn'], { ...ro, ltr: true }), + { name: 'fmShipmentMode', type: 'select', label: s['rc.f.fmShipmentMode'], options: o.cargo, hiddenWhen: { field: 'fmShipmentMode', op: 'empty' } }, + { name: 'shipmentMode', type: 'select', label: s['rc.f.shipmentMode'], options: o.cargo }, ], }, { @@ -113,20 +126,6 @@ export function detailForm(): FormMeta { text('trn', s['rc.f.trn'], { maxLength: 45, inputKind: 'plate' }), text('nnpn', s['rc.f.nnpn'], { maxLength: 20, inputKind: 'code' }), text('drvr', s['rc.f.drvr'], { maxLength: 300 }), - text('dln', s['rc.f.dln'], { ...ro, ltr: true }), - text('dled', s['rc.f.dled'], { ...ro, ltr: true }), - ], - }, - { - key: 'record', title: s['rc.sec.record'], columns: 2, - fields: [ - text('creationSourceText', s['rc.f.source'], ro), - text('createdBy', s['rc.f.createdBy'], { ...ro, ltr: true }), - text('creationDate', s['rc.f.creationDate'], { ...ro, ltr: true }), - text('confirmationBy', s['rc.f.confirmationBy'], { ...ro, ltr: true, hiddenWhen: { field: 'confirmationBy', op: 'empty' } }), - text('confirmationDate', s['rc.f.confirmationDate'], { ...ro, ltr: true, hiddenWhen: { field: 'confirmationDate', op: 'empty' } }), - text('rejectReasonName', s['rc.f.rejectReason'], { ...ro, span: 'full', hiddenWhen: { field: 'rejectReasonName', op: 'empty' } }), - text('rejectReasonNote', s['rc.f.rejectNote'], { ...ro, span: 'full', hiddenWhen: { field: 'rejectReasonNote', op: 'empty' } }), ], }, ], @@ -143,8 +142,8 @@ const stamp = (v: string | null) => { export function receiptToValues(r: ReceiptRow, rejectReasonName: string | null): Record { return { receiptNo: r.receiptNo ?? '', creditText: r.credit === 0 ? s['rc.kind.0'].ar : s['rc.kind.1'].ar, receiptTypeCaption: r.receiptTypeCaption ?? '', fees: r.fees ?? '', - companyName: r.companyName ?? '', pn: r.pn ?? '', fmShipmentMode: r.fmShipmentMode ?? '', shipmentMode: r.shipmentMode ?? '', tn: r.tn ?? '', trn: r.trn ?? '', - nnpn: r.nnpn ?? '', drvr: r.drvr ?? '', dln: r.dln ?? '', dled: r.dled ?? '', creationSourceText: r.creationSource === 0 ? s['rc.source.0'].ar : s['rc.source.1'].ar, + companyName: r.companyName ?? '', pn: r.pn ?? '', gnPn: r.gnPn ?? '', fmShipmentMode: r.fmShipmentMode ?? '', shipmentMode: r.shipmentMode ?? '', tn: r.tn ?? '', trn: r.trn ?? '', + nnpn: r.nnpn ?? '', drvr: r.drvr ?? '', creationSourceText: r.creationSource === 0 ? s['rc.source.0'].ar : s['rc.source.1'].ar, createdBy: r.createdBy ?? '', creationDate: stamp(r.creationDate), confirmationBy: r.confirmationBy && r.confirmationBy !== '0' ? r.confirmationBy : '', confirmationDate: stamp(r.confirmationDate), rejectReasonName: rejectReasonName ?? '', rejectReasonNote: r.rejectReasonNote ?? '', }; diff --git a/web/src/features/receipts/pages.tsx b/web/src/features/receipts/pages.tsx index 3e8f202..7866ef3 100644 --- a/web/src/features/receipts/pages.tsx +++ b/web/src/features/receipts/pages.tsx @@ -37,6 +37,7 @@ import { type ReceiptAutoFill, type ReceiptPrint, } from './api'; import { createForm, detailForm, receiptStatuses, receiptToValues, receiptsGrid } from './meta'; +import { lookupOptions } from './api'; import strings from './strings'; const ROOT = '/receipts'; @@ -64,7 +65,9 @@ export function ReceiptsPage() { const { t } = useFeatureUi(strings); const navigate = useNavigate(); const { can } = useAuth(); - const meta = useMemo(() => receiptsGrid({ onOpen: (r) => navigate(`${ROOT}/${r.id}`) }), [navigate]); + const lookups = useReceiptLookups(); + const options = useMemo(() => lookupOptions(lookups.data), [lookups.data]); + const meta = useMemo(() => receiptsGrid({ onOpen: (r) => navigate(`${ROOT}/${r.id}`), options }), [navigate, options]); return ( <> >({}); const mobile = useRef(null); const timer = useRef(undefined); - const meta = useMemo(() => createForm(), []); + const lookups = useReceiptLookups(); + const options = useMemo(() => lookupOptions(lookups.data), [lookups.data]); + const meta = useMemo(() => createForm(options), [options]); /** Legacy: entering the truck number filled trailer, driver number and name from the truck's grains permit; the driver number filled name and mobile. */ const onFieldChange = (name: string, value: unknown, patch: (v: Record) => void) => { @@ -103,7 +108,7 @@ export function ReceiptCreatePage() { void (async () => { if (name === 'tn') { const g: ReceiptAutoFill | undefined = await fetchTruckFill(text); - if (g) patch({ trn: g.trn ?? '', nnpn: g.nnpn ?? '', drvr: g.drvr ?? '' }); + if (g) patch({ trn: g.trn ?? '', nnpn: g.nnpn ?? '', drvr: g.drvr ?? '', gnPn: g.pn ?? '' }); return; } const d: ReceiptAutoFill | undefined = await fetchDriverFill(text); @@ -115,7 +120,7 @@ export function ReceiptCreatePage() { const submit = (payload: Record) => new Promise((resolve) => { setServerErrors({}); - const body = { ...payload, scac: 327, credit: Number(payload.credit), receiptType: Number(payload.receiptType), mobile: mobile.current }; + const body = { ...payload, scac: Number(payload.scac), credit: Number(payload.credit), receiptType: Number(payload.receiptType), mobile: mobile.current }; create.mutate(body, { onSuccess: (res) => { resolve(); navigate(res.id ? `${ROOT}/${res.id}` : gridReturnUrl(ROOT), { replace: true }); }, onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); }, @@ -149,6 +154,7 @@ function Slip({ data, innerRef }: { data: ReceiptPrint; innerRef: React.Ref(null); const slipRef = useRef(null); - const meta = useMemo(() => detailForm(), []); + const lookups = useReceiptLookups(); + const options = useMemo(() => lookupOptions(lookups.data), [lookups.data]); + const meta = useMemo(() => detailForm(options), [options]); const d = q.data; const initial = useMemo(() => (d ? receiptToValues(d.receipt, d.rejectReasonName) : {}), [d]); diff --git a/web/src/features/receipts/strings.ts b/web/src/features/receipts/strings.ts index 56829e4..43764d4 100644 --- a/web/src/features/receipts/strings.ts +++ b/web/src/features/receipts/strings.ts @@ -28,6 +28,7 @@ export default defineStrings({ // fields 'rc.f.receiptNo': { en: 'Number', ar: 'الرقم' }, 'rc.f.pn': { en: 'Permit number', ar: 'رقم التصريح' }, + 'rc.f.gnPn': { en: 'Shipment number', ar: 'رقم الارسالية' }, 'rc.f.company': { en: 'Company', ar: 'اسم الشركة' }, 'rc.f.cargoType': { en: 'Cargo type', ar: 'النمط' }, 'rc.f.shipmentMode': { en: 'Cargo type', ar: 'النمط' }, @@ -41,9 +42,12 @@ export default defineStrings({ 'rc.f.mobile': { en: 'Mobile', ar: 'الموبايل' }, 'rc.f.dln': { en: 'Driving licence no.', ar: 'رقم رخصة السائق' }, 'rc.f.dled': { en: 'Driving licence expiry', ar: 'تاريخ انتهاء رخصة السائق' }, - 'rc.f.fees': { en: 'Fees', ar: 'الأجور' }, + 'rc.f.fees': { en: 'Amount', ar: 'المبلغ' }, 'rc.f.credit': { en: 'Kind', ar: 'النوع' }, 'rc.f.onCredit': { en: 'On credit (financial claim)', ar: 'على الذمة (مطالبة مالية)' }, + 'rc.f.scac': { en: 'Transport company', ar: 'شركة النقل' }, + 'rc.scac.327': { en: 'Supply tender administration / Aswar Al Quds - 327', ar: 'ادارة عطاء التموين/شركة أسوار القدس - 327' }, + 'rc.scac.326': { en: 'Aswar Al Quds - 326', ar: 'شركة أسوار القدس - 326' }, 'rc.f.receiptType': { en: 'Receipt type', ar: 'نوع الوصل' }, 'rc.f.creationDate': { en: 'Created', ar: 'تاريخ الانشاء' }, 'rc.f.createdBy': { en: 'Created by', ar: 'إنشاء بواسطة' }, @@ -115,7 +119,7 @@ export default defineStrings({ 'rc.method.AUDIT': { en: 'Audit', ar: 'تدقيق سندات القبض المالية' }, 'rc.method.FIN_AUDIT': { en: 'Financial audit', ar: 'تدقيق مالي' }, 'rc.prop.SCAC': { en: 'Company code', ar: 'رقم الشركة' }, - 'rc.prop.FEES': { en: 'Fees', ar: 'الأجور' }, + 'rc.prop.FEES': { en: 'Amount', ar: 'المبلغ' }, 'rc.prop.FMSHIPMENTMODE': { en: 'First move cargo', ar: 'نمط الحركة الاولى' }, 'rc.prop.SHIPMENTMODE': { en: 'Cargo type', ar: 'النمط' }, 'rc.prop.TN': { en: 'Truck', ar: 'رقم الشاحنة' },