Receipts: GN shipment number, created as paid with log, bind-name fix, lookups; communication cargo filter

- Receipts: رقم الارسالية (GN_PN, db/receipts-gn-permit.sql, tolerated when missing), company drop list, month/paid default filters, view only page, details dialog, amount caption
- New receipts are created PAID in one cash number series and write a CREATE log row
- Fix ORA-01745: reserved words used as bind names (:User, :From, :To, :Number, :By) in receipts and registrar repositories
- Lookups for receipt types / cargo come from the page's lookup request
- Communication: cargo filter lists CARGOTYPE of domain GN
- Jobs cards compact; report loading card

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-25 11:48:20 +03:00
parent 28e629ccac
commit ed18621821
15 changed files with 146 additions and 100 deletions

11
db/receipts-gn-permit.sql Normal file
View File

@ -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;
/

View File

@ -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 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) 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) 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) 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 **Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU

View File

@ -59,7 +59,7 @@ public sealed class ReceiptsController(IReceiptService receipts) : ControllerBas
receipts.GetLogAsync(id, new PageRequest(page, pageSize), ct); receipts.GetLogAsync(id, new PageRequest(page, pageSize), ct);
[HttpPost] [HttpPost]
public Task<ReceiptResult> Create([FromBody] CreateReceiptRequest request, CancellationToken ct) => receipts.CreateAsync(request, ct); public Task<ReceiptResult> Create([FromBody] CreateReceiptRequest request, CancellationToken ct) => receipts.CreateAsync(request, ct, Ip);
[HttpPut("{id:long}")] [HttpPut("{id:long}")]
public Task<ReceiptResult> Update(long id, [FromBody] UpdateReceiptRequest request, CancellationToken ct) => receipts.UpdateAsync(id, request, ct); public Task<ReceiptResult> Update(long id, [FromBody] UpdateReceiptRequest request, CancellationToken ct) => receipts.UpdateAsync(id, request, ct);

View File

@ -49,7 +49,7 @@ public interface IReceiptService
Task<ReceiptDetail> GetAsync(long id, CancellationToken ct); Task<ReceiptDetail> GetAsync(long id, CancellationToken ct);
Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct); Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct);
Task<ReceiptLookups> GetLookupsAsync(CancellationToken ct); Task<ReceiptLookups> GetLookupsAsync(CancellationToken ct);
Task<ReceiptResult> CreateAsync(CreateReceiptRequest request, CancellationToken ct); Task<ReceiptResult> CreateAsync(CreateReceiptRequest request, CancellationToken ct, string? ip = null);
Task<ReceiptResult> ConfirmAsync(long id, string? ip, CancellationToken ct); Task<ReceiptResult> ConfirmAsync(long id, string? ip, CancellationToken ct);
Task<ReceiptResult> UpdateAsync(long id, UpdateReceiptRequest request, CancellationToken ct); Task<ReceiptResult> UpdateAsync(long id, UpdateReceiptRequest request, CancellationToken ct);
Task<ReceiptResult> PaidAsync(long id, string? ip, CancellationToken ct); Task<ReceiptResult> PaidAsync(long id, string? ip, CancellationToken ct);

View File

@ -148,7 +148,7 @@ public static class ReceiptAudit
public static (List<AuditLine> Lines, List<AuditedReceipt> Audited, List<long> Identical) Compare( public static (List<AuditLine> Lines, List<AuditedReceipt> Audited, List<long> Identical) Compare(
IReadOnlyList<AuditFileRow> file, IReadOnlyList<ReceiptRow> receipts, AuditLookups lk, string? confirmationBy, Func<string?, string> statusName) IReadOnlyList<AuditFileRow> file, IReadOnlyList<ReceiptRow> receipts, AuditLookups lk, string? confirmationBy, Func<string?, string> statusName)
{ {
var lines = new List<AuditLine> { new("رقم التصريح", "حالة التصريح", "رقم الوصل", "الأجور", "حالة الوصل", "تاريخ الوصل", "النتيجة", "الملاحظات") }; var lines = new List<AuditLine> { new("رقم التصريح", "حالة التصريح", "رقم الوصل", "المبلغ", "حالة الوصل", "تاريخ الوصل", "النتيجة", "الملاحظات") };
var audited = new List<AuditedReceipt>(); var audited = new List<AuditedReceipt>();
var identical = new List<long>(); var identical = new List<long>();
var pns = new List<string>(); var pns = new List<string>();

View File

@ -6,6 +6,8 @@ public class ReceiptRow
public long Id { get; set; } public long Id { get; set; }
public long? ReceiptNo { get; set; } public long? ReceiptNo { get; set; }
public long? Pn { get; set; } public long? Pn { get; set; }
/// <summary>The grains (GN) permit number of the truck, "رقم الارسالية" (column GN_PN, db/receipts-gn-permit.sql).</summary>
public long? GnPn { get; set; }
public string? ShipmentMode { get; set; } public string? ShipmentMode { get; set; }
public string? FmShipmentMode { get; set; } public string? FmShipmentMode { get; set; }
/// <summary>The cargo type names, "first - second" for a double move (view column CARGO_TYPE).</summary> /// <summary>The cargo type names, "first - second" for a double move (view column CARGO_TYPE).</summary>
@ -61,6 +63,7 @@ public sealed class CreateReceiptRequest
public int Credit { get; set; } public int Credit { get; set; }
public long ReceiptType { get; set; } public long ReceiptType { get; set; }
public string? Pn { get; set; } public string? Pn { get; set; }
public string? GnPn { get; set; }
public string? FmShipmentMode { get; set; } public string? FmShipmentMode { get; set; }
public string? ShipmentMode { get; set; } public string? ShipmentMode { get; set; }
public string? Tn { get; set; } public string? Tn { get; set; }

View File

@ -45,8 +45,8 @@ public static class ReceiptRules
public static bool IsStatus(string? status, string expected) => string.Equals(status, expected, StringComparison.OrdinalIgnoreCase); public static bool IsStatus(string? status, string expected) => string.Equals(status, expected, StringComparison.OrdinalIgnoreCase);
/// <summary>Status of a new receipt: cash (credit 0) RECEIVED, a financial claim UNPAID.</summary> /// <summary>Status of a new receipt: PAID (owner decision; the legacy made cash RECEIVED and claims UNPAID).</summary>
public static string StatusForNew(int credit) => credit == 0 ? ReceiptStatus.Received : ReceiptStatus.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 CanUpdate(string? s) => IsStatus(s, ReceiptStatus.Received) || IsStatus(s, ReceiptStatus.Unpaid);
public static bool CanConfirm(string? s) => IsStatus(s, ReceiptStatus.NotReceived); public static bool CanConfirm(string? s) => IsStatus(s, ReceiptStatus.NotReceived);

View File

@ -47,7 +47,7 @@ public sealed class ReceiptService(
// ---------------------------------------------------------------- create / update // ---------------------------------------------------------------- create / update
public async Task<ReceiptResult> CreateAsync(CreateReceiptRequest request, CancellationToken ct) public async Task<ReceiptResult> CreateAsync(CreateReceiptRequest request, CancellationToken ct, string? ip = null)
{ {
await Require(PermissionKeys.ReceiptsCreate, ct); await Require(PermissionKeys.ReceiptsCreate, ct);
var failures = new List<ValidationFailure>(); var failures = new List<ValidationFailure>();
@ -57,8 +57,6 @@ public sealed class ReceiptService(
Need("trn", !string.IsNullOrWhiteSpace(request.Trn)); Need("trn", !string.IsNullOrWhiteSpace(request.Trn));
Need("nnpn", !string.IsNullOrWhiteSpace(request.Nnpn)); Need("nnpn", !string.IsNullOrWhiteSpace(request.Nnpn));
Need("drvr", !string.IsNullOrWhiteSpace(request.Drvr)); 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("shipmentMode", !string.IsNullOrWhiteSpace(request.ShipmentMode));
Need("receiptType", request.ReceiptType > 0); Need("receiptType", request.ReceiptType > 0);
Need("credit", request.Credit is 0 or 1); 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)) if (request.ReceiptType is 8 or 9 or 10 && !await repository.PermitMatchesTypeAsync(request.ReceiptType, pn, ct))
throw new BusinessException(ReceiptErrors.DataCheck, ReceiptMessages.DataCheck); 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); 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("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("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("createdBy", "إنشاء بواسطة", "Created by"), new("confirmationDate", "تاريخ التأكيد", "Confirmed"), new("confirmationBy", "تأكيد بواسطة", "Confirmed by"),
new("confirmationName", "اسم المؤكد", "Confirmed by (name)"), new("status", "الحالة", "Status"), new("source", "طريقة الدفع", "Payment"), new("confirmationName", "اسم المؤكد", "Confirmed by (name)"), new("status", "الحالة", "Status"), new("source", "طريقة الدفع", "Payment"),
}; };
@ -284,7 +290,7 @@ public sealed class ReceiptService(
var cols = new List<ReportColumn> var cols = new List<ReportColumn>
{ {
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"), new("receiptStatus", "حالة الوصل", "Receipt status"), new("date", "تاريخ الوصل", "Receipt date"), new("result", "النتيجة", "Result"), new("remark", "الملاحظات", "Remarks"),
}; };
var rows = lines.Skip(1).Select(l => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?> var rows = lines.Skip(1).Select(l => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>

View File

@ -15,7 +15,7 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepos
: OracleRepositoryBase(session, logger), IReceiptRepository : OracleRepositoryBase(session, logger), IReceiptRepository
{ {
private const string Select = """ private const string Select = """
SELECT p.ID AS Id, p.RECEIPT_NO AS ReceiptNo, p.PN AS Pn, p.SHIPMENTMODE AS ShipmentMode, p.FMSHIPMENTMODE AS FmShipmentMode, p.CARGO_TYPE AS CargoType, SELECT p.ID AS Id, p.RECEIPT_NO AS ReceiptNo, p.PN AS Pn, r.GN_PN AS GnPn, p.SHIPMENTMODE AS ShipmentMode, p.FMSHIPMENTMODE AS FmShipmentMode, p.CARGO_TYPE AS CargoType,
p.CRN AS Crn, p.CA_CODE AS CaCode, p.CA_NAME AS CaName, p.TN AS Tn, p.TRN AS Trn, p.DRVR AS Drvr, p.NNPN AS Nnpn, p.MOBILE AS Mobile, p.CRN AS Crn, p.CA_CODE AS CaCode, p.CA_NAME AS CaName, p.TN AS Tn, p.TRN AS Trn, p.DRVR AS Drvr, p.NNPN AS Nnpn, p.MOBILE AS Mobile,
p.STATUSCODE AS StatusCode, r.CREATION_DATE AS CreationDate, p.CREATED_BY AS CreatedBy, p.DLN AS Dln, p.DLED AS Dled, p.SCAC AS Scac, p.STATUSCODE AS StatusCode, r.CREATION_DATE AS CreationDate, p.CREATED_BY AS CreatedBy, p.DLN AS Dln, p.DLED AS Dled, p.SCAC AS Scac,
p.COMPANY_NAME AS CompanyName, p.INBOUNDTYPECODE AS InboundTypeCode, p.FMINBOUNDTYPECODE AS FmInboundTypeCode, p.COMPANY_NAME AS CompanyName, p.INBOUNDTYPECODE AS InboundTypeCode, p.FMINBOUNDTYPECODE AS FmInboundTypeCode,
@ -51,7 +51,7 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepos
for (var i = 0; i < statuses.Count; i++) p.Add("St" + i, statuses[i]); for (var i = 0; i < statuses.Count; i++) p.Add("St" + i, statuses[i]);
} }
var baseSql = Select + where; var baseSql = await SelectAsync(ct) + where;
var total = await ExecuteScalarAsync<long>(OracleSql.Count(baseSql), p, ct); var total = await ExecuteScalarAsync<long>(OracleSql.Count(baseSql), p, ct);
if (total == 0) return new PagedResult<ReceiptRow>([], page.SafePage, page.SafePageSize, 0); if (total == 0) return new PagedResult<ReceiptRow>([], page.SafePage, page.SafePageSize, 0);
p.Add("MinRow", page.MinRow); p.Add("MinRow", page.MinRow);
@ -61,7 +61,10 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepos
} }
public Task<ReceiptRow?> GetAsync(long id, CancellationToken ct = default) => public Task<ReceiptRow?> GetAsync(long id, CancellationToken ct = default) =>
QueryFirstAsync<ReceiptRow>(Select + " AND p.ID = :Id", new { Id = id }, ct); GetCoreAsync(id, ct);
private async Task<ReceiptRow?> GetCoreAsync(long id, CancellationToken ct) =>
await QueryFirstAsync<ReceiptRow>(await SelectAsync(ct) + " AND p.ID = :Id", new { Id = id }, ct);
public async Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct = default) public async Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct = default)
{ {
@ -113,17 +116,18 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepos
{ {
var id = await ExecuteScalarAsync<long>("SELECT SEQ_PERMITS_RECEIPTS.NEXTVAL FROM DUAL", null, ct); var id = await ExecuteScalarAsync<long>("SELECT SEQ_PERMITS_RECEIPTS.NEXTVAL FROM DUAL", null, ct);
var (fm, sm) = ReceiptRules.SplitModes(r.FmShipmentMode, r.ShipmentMode); 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 // CREATION_DATE: the legacy insert left it to the column default; CONFIRMATION_DATE stays empty, CONFIRMATION_BY is the creator
await ExecuteAsync($""" var gn = await HasGnPnAsync(ct);
INSERT INTO PERMITS_RECEIPTS (ID, RECEIPT_NO, PN, SHIPMENTMODE, FMSHIPMENTMODE, CRN, CA_CODE, TN, TRN, DRVR, NNPN, MOBILE, CREATION_DATE, CREATED_BY, STATUSCODE, 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) 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, VALUES (:Id, ({number}), :Pn, :GnPn, :Sm, :Fm, :Crn, :CaCode, :Tn, :Trn, :Drvr, :Nnpn, :Mobile, SYSDATE, :UserLogin, :Status,
:Dln, :Dled, :Scac, :Fees, :Type, :User, NULL, :Dest, :Origin, :Inbound, :Credit) :Dln, :Dled, :Scac, :Fees, :Type, :UserLogin, NULL, :Dest, :Origin, :Inbound, :Credit)
""", new """, 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), 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), User = Fit(userLogin, 300), Status = status, Dln = Clean(r.Dln), Dled = Clean(r.Dled), 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, r.Scac, Fees = fees, Type = r.ReceiptType, Dest = r.DestinationAddressId, Origin = r.OriginAddressId, Inbound = Clean(r.InboundTypeCode), r.Credit,
}, ct); }, ct);
return id; return id;
@ -141,22 +145,23 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepos
public async Task<long> InsertPaidCopyAsync(long sourceId, CancellationToken ct = default) public async Task<long> InsertPaidCopyAsync(long sourceId, CancellationToken ct = default)
{ {
var id = await ExecuteScalarAsync<long>("SELECT SEQ_PERMITS_RECEIPTS.NEXTVAL FROM DUAL", null, ct); var id = await ExecuteScalarAsync<long>("SELECT SEQ_PERMITS_RECEIPTS.NEXTVAL FROM DUAL", null, ct);
await ExecuteAsync($""" var gn = await HasGnPnAsync(ct);
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, 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, DLN, DLED, SCAC, FEES, RECEIPT_TYPE, PERMIT_STATUS, CONFIRMATION_BY, FMINBOUNDTYPECODE, DESTINATIONADDRESSID, ORIGINADDRESSID,
INBOUNDTYPECODE, CREDIT, REQUEST_ID) 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.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 s.INBOUNDTYPECODE, 0, s.REQUEST_ID
FROM PERMITS_RECEIPTS s WHERE s.ID = :Source FROM PERMITS_RECEIPTS s WHERE s.ID = :Source
""", new { Id = id, Source = sourceId }, ct); """, gn), new { Id = id, Source = sourceId }, ct);
return id; return id;
} }
public async Task<bool> ConfirmAsync(long id, string userLogin, CancellationToken ct = default) => public async Task<bool> ConfirmAsync(long id, string userLogin, CancellationToken ct = default) =>
await ExecuteAsync(""" await ExecuteAsync("""
UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'RECEIVED', CONFIRMATION_DATE = SYSDATE, CONFIRMATION_BY = :User WHERE ID = :Id AND STATUSCODE = 'NOT_RECEIVED' UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'RECEIVED', CONFIRMATION_DATE = SYSDATE, CONFIRMATION_BY = :UserLogin WHERE ID = :Id AND STATUSCODE = 'NOT_RECEIVED'
""", new { Id = id, User = Fit(userLogin, 300) }, ct) > 0; """, new { Id = id, UserLogin = Fit(userLogin, 300) }, ct) > 0;
public async Task<bool> UpdateAsync(long id, UpdateReceiptRequest r, string userLogin, CancellationToken ct = default) public async Task<bool> UpdateAsync(long id, UpdateReceiptRequest r, string userLogin, CancellationToken ct = default)
{ {
@ -164,11 +169,11 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepos
return await ExecuteAsync(""" return await ExecuteAsync("""
UPDATE PERMITS_RECEIPTS UPDATE PERMITS_RECEIPTS
SET PN = :Pn, TN = :Tn, TRN = :Trn, DRVR = :Drvr, NNPN = :Nnpn, MOBILE = :Mobile, SHIPMENTMODE = :Sm, FMSHIPMENTMODE = :Fm, SET PN = :Pn, TN = :Tn, TRN = :Trn, DRVR = :Drvr, NNPN = :Nnpn, MOBILE = :Mobile, SHIPMENTMODE = :Sm, FMSHIPMENTMODE = :Fm,
LASTUPDATEDATE = SYSDATE, LASTUPDATEBY = :User LASTUPDATEDATE = SYSDATE, LASTUPDATEBY = :UserLogin
WHERE ID = :Id AND STATUSCODE IN ('RECEIVED', 'UNPAID') WHERE ID = :Id AND STATUSCODE IN ('RECEIVED', 'UNPAID')
""", new """, new
{ {
Id = id, Pn = ToLong(r.Pn), Tn = Clean(r.Tn), Trn = Clean(r.Trn), Drvr = Clean(r.Drvr), Nnpn = Clean(r.Nnpn), Mobile = Clean(r.Mobile), Sm = sm, Fm = fm, User = Fit(userLogin, 500), Id = id, Pn = ToLong(r.Pn), Tn = Clean(r.Tn), Trn = Clean(r.Trn), Drvr = Clean(r.Drvr), Nnpn = Clean(r.Nnpn), Mobile = Clean(r.Mobile), Sm = sm, Fm = fm, UserLogin = Fit(userLogin, 500),
}, ct) > 0; }, ct) > 0;
} }
@ -183,10 +188,10 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepos
public async Task<bool> RevokeAsync(long id, string fromStatus, long? reason, string? note, string userLogin, CancellationToken ct = default) public async Task<bool> 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 = ""; var set = "";
if (reason is { } r) { set = ", REJECT_REASON = :Reason, REJECT_REASON_NOTE = :Note"; p.Add("Reason", r); p.Add("Note", note); } 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<bool> RejectRevokeAsync(long id, CancellationToken ct = default) => public async Task<bool> RejectRevokeAsync(long id, CancellationToken ct = default) =>
@ -245,16 +250,16 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepos
{ {
if (f.TimeFrom is { } tf && f.TimeTo is { } tt) if (f.TimeFrom is { } tf && f.TimeTo is { } tt)
{ {
sql.Append(" AND r.CONFIRMATION_DATE BETWEEN :From AND :To"); sql.Append(" AND r.CONFIRMATION_DATE BETWEEN :FromX AND :ToX");
p.Add("From", from.Date + tf); p.Add("To", to.Date + tt); p.Add("FromX", from.Date + tf); p.Add("ToX", to.Date + tt);
} }
else else
{ {
sql.Append(" AND r.CONFIRMATION_DATE >= :From AND r.CONFIRMATION_DATE < :To"); sql.Append(" AND r.CONFIRMATION_DATE >= :FromX AND r.CONFIRMATION_DATE < :ToX");
p.Add("From", from.Date); p.Add("To", to.Date.AddDays(1)); 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"); sql.Append(" ORDER BY p.RECEIPT_NO ASC");
return QueryAsync<ReceiptRow>(sql.ToString(), p, ct); return QueryAsync<ReceiptRow>(sql.ToString(), p, ct);
} }
@ -269,6 +274,25 @@ internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepos
} }
} }
// GN_PN (db/receipts-gn-permit.sql) may not exist yet: until the script has run the screens work without the shipment number
private static volatile bool gnPnKnown;
private static DateTime gnPnCheckedAt;
private async Task<bool> HasGnPnAsync(CancellationToken ct)
{
if (gnPnKnown) return true;
if (DateTime.UtcNow - gnPnCheckedAt < TimeSpan.FromMinutes(1)) return false;
gnPnCheckedAt = DateTime.UtcNow;
gnPnKnown = await ExecuteScalarAsync<long>("SELECT COUNT(*) FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'PERMITS_RECEIPTS' AND COLUMN_NAME = 'GN_PN'", null, ct) > 0;
return gnPnKnown;
}
private async Task<string> 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? 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 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; private static long? ToLong(string? s) => long.TryParse(s?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? n : null;

View File

@ -52,7 +52,7 @@ internal sealed class RegistrarRepository(IDbSession session, ILogger<RegistrarR
{ {
var where = new StringBuilder(" WHERE 1 = 1"); var where = new StringBuilder(" WHERE 1 = 1");
var p = new DynamicParameters(); var p = new DynamicParameters();
if (!string.IsNullOrWhiteSpace(query.Number)) { where.Append($" AND LOWER({NumberColumn(kind)}) = LOWER(:Number)"); p.Add("Number", query.Number.Trim()); } if (!string.IsNullOrWhiteSpace(query.Number)) { where.Append($" AND LOWER({NumberColumn(kind)}) = LOWER(:NumberValue)"); p.Add("NumberValue", query.Number.Trim()); }
if (!string.IsNullOrWhiteSpace(query.LicenseNo)) { where.Append(" AND LOWER(p.LICENSE_NO) = LOWER(:LicenseNo)"); p.Add("LicenseNo", query.LicenseNo.Trim()); } if (!string.IsNullOrWhiteSpace(query.LicenseNo)) { where.Append(" AND LOWER(p.LICENSE_NO) = LOWER(:LicenseNo)"); p.Add("LicenseNo", query.LicenseNo.Trim()); }
if (kind == RegistrarKind.Driver) if (kind == RegistrarKind.Driver)
{ {
@ -132,11 +132,11 @@ internal sealed class RegistrarRepository(IDbSession session, ILogger<RegistrarR
public async Task<bool> ChangeStatusAsync(RegistrarKind kind, long id, string fromStatus, string toStatus, string userId, string? revokeReason, CancellationToken ct = default) public async Task<bool> 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 = ""; var reason = "";
if (revokeReason is not null) { reason = ", REVOKE_REASON = :Reason"; p.Add("Reason", Fit(revokeReason, 100)); } if (revokeReason is not null) { reason = ", REVOKE_REASON = :Reason"; p.Add("Reason", Fit(revokeReason, 100)); }
var rows = await ExecuteAsync( 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; return rows > 0;
} }

View File

@ -37,8 +37,8 @@ public class ReceiptRulesTests
Assert.False(ReceiptRules.CanPrint("RVKD")); Assert.False(ReceiptRules.CanPrint("RVKD"));
Assert.True(ReceiptRules.CanRevokeAudited("AUDITED")); Assert.True(ReceiptRules.CanRevokeAudited("AUDITED"));
Assert.True(ReceiptRules.CanDecideRevoke("PENDING_RVKD")); Assert.True(ReceiptRules.CanDecideRevoke("PENDING_RVKD"));
Assert.Equal("RECEIVED", ReceiptRules.StatusForNew(0)); Assert.Equal("PAID", ReceiptRules.StatusForNew(0));
Assert.Equal("UNPAID", ReceiptRules.StatusForNew(1)); Assert.Equal("PAID", ReceiptRules.StatusForNew(1));
Assert.True(ReceiptRules.IsDoubleMove(1) && ReceiptRules.IsDoubleMove(2) && ReceiptRules.IsDoubleMove(10)); Assert.True(ReceiptRules.IsDoubleMove(1) && ReceiptRules.IsDoubleMove(2) && ReceiptRules.IsDoubleMove(10));
Assert.False(ReceiptRules.IsDoubleMove(3)); Assert.False(ReceiptRules.IsDoubleMove(3));
} }
@ -267,11 +267,11 @@ public class ReceiptServiceTests
var (svc, repo, _) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsCreate); var (svc, repo, _) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsCreate);
var r = await svc.CreateAsync(NewReceipt(), default); var r = await svc.CreateAsync(NewReceipt(), default);
Assert.Equal(77, r.Id); 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; var claim = NewReceipt(); claim.Credit = 1;
await svc.CreateAsync(claim, default); await svc.CreateAsync(claim, default);
Assert.Equal("insert:UNPAID:6:TS1", repo.Writes[1]); Assert.Equal("insert:PAID:6:TS1", repo.Writes[2]);
} }
[Fact] [Fact]

View File

@ -12,6 +12,7 @@ export interface ReceiptRow {
id: number; id: number;
receiptNo: number | null; receiptNo: number | null;
pn: number | null; pn: number | null;
gnPn: number | null;
shipmentMode: string | null; shipmentMode: string | null;
fmShipmentMode: string | null; fmShipmentMode: string | null;
cargoType: string | null; cargoType: string | null;
@ -91,27 +92,16 @@ export interface ReceiptResult { message: string; id: number | null }
export const useReceiptLookups = () => export const useReceiptLookups = () =>
useQuery({ queryKey: ['receipts.lookups'], queryFn: () => api.get<ReceiptLookups>(`${BASE}/lookups`), staleTime: 5 * 60_000 }); useQuery({ queryKey: ['receipts.lookups'], queryFn: () => api.get<ReceiptLookups>(`${BASE}/lookups`), staleTime: 5 * 60_000 });
let cache: { at: number; promise: Promise<ReceiptLookups> } | null = null; /** Options of the cargo types and (per company) the receipt types, built from the lookups the page already loaded (no extra request). */
function loadLookups(): Promise<ReceiptLookups> { export function lookupOptions(l: ReceiptLookups | undefined) {
if (!cache || Date.now() - cache.at > 60_000) { const cargo: OptionsLoader = { key: 'receipts.cargo.' + (l?.cargoTypes.length ?? 0), load: async () => (l?.cargoTypes ?? []).map((c): OptionItem => ({ value: c.code ?? '', label: c.name ?? '' })) };
const promise = api.get<ReceiptLookups>(`${BASE}/lookups`); const types: OptionsLoader = {
promise.catch(() => { cache = null; }); key: 'receipts.types.' + (l?.types.length ?? 0),
cache = { at: Date.now(), promise }; 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 cache.promise;
}
/** 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} دينار` })),
}; };
return { cargo, types };
}
// ---------------------------------------------------------------- reads / writes // ---------------------------------------------------------------- reads / writes

View File

@ -1,6 +1,17 @@
import type { FieldMeta, FormMeta, GridMeta, StatusMeta } from '@/components/meta/types'; import type { FieldMeta, FormMeta, GridMeta, StatusMeta } from '@/components/meta/types';
import strings from './strings'; 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; 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'] }]; 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. */ /** 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<ReceiptRow> { export function receiptsGrid(h: { onOpen: (r: ReceiptRow) => void; options: ReceiptOptions }): GridMeta<ReceiptRow> {
const month = currentMonth();
return { return {
key: GRID_RECEIPTS, key: GRID_RECEIPTS,
endpoint: BASE, endpoint: BASE,
@ -27,14 +39,14 @@ export function receiptsGrid(h: { onOpen: (r: ReceiptRow) => void }): GridMeta<R
onRowClick: h.onOpen, onRowClick: h.onOpen,
pageSize: 16, pageSize: 16,
emptyAsGrid: true, emptyAsGrid: true,
defaultFilters: { statusCode: 'RECEIVED' }, defaultFilters: { statusCode: 'PAID', createDateFrom: month.from, createDateTo: month.to },
status: { param: 'statusCode', options: receiptStatuses }, status: { param: 'statusCode', options: receiptStatuses },
filters: [ filters: [
{ name: 'receiptNo', type: 'text', label: s['rc.f.receiptNo'], ltr: true }, { name: 'receiptNo', type: 'text', label: s['rc.f.receiptNo'], ltr: true },
{ name: 'pn', type: 'text', label: s['rc.f.pn'], ltr: true }, { name: 'pn', type: 'text', label: s['rc.f.pn'], ltr: true },
{ name: 'tn', type: 'text', label: s['rc.f.tn'], ltr: true }, { name: 'tn', type: 'text', label: s['rc.f.tn'], ltr: true },
{ name: 'trn', type: 'text', label: s['rc.f.trn'], ltr: true }, { name: 'trn', type: 'text', label: s['rc.f.trn'], ltr: true },
{ name: 'shipmentMode', type: 'select', label: s['rc.f.cargoType'], options: cargoOptions }, { name: 'shipmentMode', type: 'select', label: s['rc.f.cargoType'], options: h.options.cargo },
{ name: 'credit', type: 'select', label: s['rc.f.credit'], options: yesNo }, { name: 'credit', type: 'select', label: s['rc.f.credit'], options: yesNo },
{ name: 'creationSource', type: 'select', label: s['rc.f.source'], options: sources }, { name: 'creationSource', type: 'select', label: s['rc.f.source'], options: sources },
{ name: 'createDateFrom', type: 'date', label: s['rc.f.createDateFrom'] }, { name: 'createDateFrom', type: 'date', label: s['rc.f.createDateFrom'] },
@ -58,18 +70,20 @@ const text = (name: string, label: FieldMeta['label'], extra: Partial<FieldMeta>
const digits = { regex: /^\d+$/, message: s['rc.digits'] }; 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). */ /** 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 { return {
key: 'receipts.create.form', key: 'receipts.create.form',
sections: [ sections: [
{ {
key: 'receipt', title: s['rc.sec.receipt'], columns: 2, key: 'receipt', title: s['rc.sec.receipt'], columns: 2,
fields: [ 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: '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 }), 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'] } }, text('gnPn', s['rc.f.gnPn'], { maxLength: 15, inputKind: 'code', pattern: digits }),
{ name: 'shipmentMode', type: 'select', label: s['rc.f.shipmentMode'], required: true, options: cargoOptions, helper: s['rc.f.shipmentModeHelp'] }, { 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('trn', s['rc.f.trn'], { required: true, maxLength: 45, inputKind: 'plate' }),
text('nnpn', s['rc.f.nnpn'], { required: true, maxLength: 20, inputKind: 'code' }), text('nnpn', s['rc.f.nnpn'], { required: true, maxLength: 20, inputKind: 'code' }),
text('drvr', s['rc.f.drvr'], { required: true, maxLength: 300 }), 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). */ /** 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; const ro = { readOnly: true } as const;
return { return {
key: 'receipts.detail.form', key: 'receipts.detail.form',
@ -102,8 +114,9 @@ export function detailForm(): FormMeta {
text('fees', s['rc.f.fees'], { ...ro, ltr: true }), text('fees', s['rc.f.fees'], { ...ro, ltr: true }),
text('companyName', s['rc.f.company'], ro), text('companyName', s['rc.f.company'], ro),
text('pn', s['rc.f.pn'], { maxLength: 15, inputKind: 'code', pattern: digits }), 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' } }, text('gnPn', s['rc.f.gnPn'], { ...ro, ltr: true }),
{ name: 'shipmentMode', type: 'select', label: s['rc.f.shipmentMode'], options: cargoOptions }, { 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('trn', s['rc.f.trn'], { maxLength: 45, inputKind: 'plate' }),
text('nnpn', s['rc.f.nnpn'], { maxLength: 20, inputKind: 'code' }), text('nnpn', s['rc.f.nnpn'], { maxLength: 20, inputKind: 'code' }),
text('drvr', s['rc.f.drvr'], { maxLength: 300 }), 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<string, unknown> { export function receiptToValues(r: ReceiptRow, rejectReasonName: string | null): Record<string, unknown> {
return { return {
receiptNo: r.receiptNo ?? '', creditText: r.credit === 0 ? s['rc.kind.0'].ar : s['rc.kind.1'].ar, receiptTypeCaption: r.receiptTypeCaption ?? '', fees: r.fees ?? '', 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 ?? '', 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 ?? '', dln: r.dln ?? '', dled: r.dled ?? '', creationSourceText: r.creationSource === 0 ? s['rc.source.0'].ar : s['rc.source.1'].ar, 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 : '', createdBy: r.createdBy ?? '', creationDate: stamp(r.creationDate), confirmationBy: r.confirmationBy && r.confirmationBy !== '0' ? r.confirmationBy : '',
confirmationDate: stamp(r.confirmationDate), rejectReasonName: rejectReasonName ?? '', rejectReasonNote: r.rejectReasonNote ?? '', confirmationDate: stamp(r.confirmationDate), rejectReasonName: rejectReasonName ?? '', rejectReasonNote: r.rejectReasonNote ?? '',
}; };

View File

@ -37,6 +37,7 @@ import {
type ReceiptAutoFill, type ReceiptPrint, type ReceiptAutoFill, type ReceiptPrint,
} from './api'; } from './api';
import { createForm, detailForm, receiptStatuses, receiptToValues, receiptsGrid } from './meta'; import { createForm, detailForm, receiptStatuses, receiptToValues, receiptsGrid } from './meta';
import { lookupOptions } from './api';
import strings from './strings'; import strings from './strings';
const ROOT = '/receipts'; const ROOT = '/receipts';
@ -64,7 +65,9 @@ export function ReceiptsPage() {
const { t } = useFeatureUi(strings); const { t } = useFeatureUi(strings);
const navigate = useNavigate(); const navigate = useNavigate();
const { can } = useAuth(); 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 ( return (
<> <>
<PageHeader <PageHeader
@ -91,7 +94,9 @@ export function ReceiptCreatePage() {
const [serverErrors, setServerErrors] = useState<Record<string, string>>({}); const [serverErrors, setServerErrors] = useState<Record<string, string>>({});
const mobile = useRef<string | null>(null); const mobile = useRef<string | null>(null);
const timer = useRef<number | undefined>(undefined); const timer = useRef<number | undefined>(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. */ /** 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<string, unknown>) => void) => { const onFieldChange = (name: string, value: unknown, patch: (v: Record<string, unknown>) => void) => {
@ -103,7 +108,7 @@ export function ReceiptCreatePage() {
void (async () => { void (async () => {
if (name === 'tn') { if (name === 'tn') {
const g: ReceiptAutoFill | undefined = await fetchTruckFill(text); 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; return;
} }
const d: ReceiptAutoFill | undefined = await fetchDriverFill(text); const d: ReceiptAutoFill | undefined = await fetchDriverFill(text);
@ -115,7 +120,7 @@ export function ReceiptCreatePage() {
const submit = (payload: Record<string, unknown>) => const submit = (payload: Record<string, unknown>) =>
new Promise<void>((resolve) => { new Promise<void>((resolve) => {
setServerErrors({}); 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, { create.mutate(body, {
onSuccess: (res) => { resolve(); navigate(res.id ? `${ROOT}/${res.id}` : gridReturnUrl(ROOT), { replace: true }); }, onSuccess: (res) => { resolve(); navigate(res.id ? `${ROOT}/${res.id}` : gridReturnUrl(ROOT), { replace: true }); },
onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); }, onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); },
@ -149,6 +154,7 @@ function Slip({ data, innerRef }: { data: ReceiptPrint; innerRef: React.Ref<HTML
const printDate = `${now.getFullYear()}-${p2(now.getMonth() + 1)}-${p2(now.getDate())} ${p2(now.getHours())}:${p2(now.getMinutes())}:${p2(now.getSeconds())}`; const printDate = `${now.getFullYear()}-${p2(now.getMonth() + 1)}-${p2(now.getDate())} ${p2(now.getHours())}:${p2(now.getMinutes())}:${p2(now.getSeconds())}`;
const rows: [string, string][] = [ const rows: [string, string][] = [
[t('rc.slip.pn'), String(r.pn ?? '')], [t('rc.slip.pn'), String(r.pn ?? '')],
...(r.scac === 327 && r.gnPn ? [[t('rc.f.gnPn'), String(r.gnPn)] as [string, string]] : []),
...(data.showCargo ? [[t('rc.slip.cargo'), r.cargoType ?? ''] as [string, string]] : []), ...(data.showCargo ? [[t('rc.slip.cargo'), r.cargoType ?? ''] as [string, string]] : []),
[t('rc.slip.tn'), r.tn ?? ''], [t('rc.slip.trn'), r.trn ?? ''], [t('rc.slip.driver'), r.drvr ?? ''], [t('rc.slip.nnpn'), r.nnpn ?? ''], [t('rc.slip.tn'), r.tn ?? ''], [t('rc.slip.trn'), r.trn ?? ''], [t('rc.slip.driver'), r.drvr ?? ''], [t('rc.slip.nnpn'), r.nnpn ?? ''],
[t('rc.slip.description'), data.description], [t('rc.slip.description'), data.description],
@ -297,7 +303,9 @@ export function ReceiptPage() {
const [revoking, setRevoking] = useState(false); const [revoking, setRevoking] = useState(false);
const [slip, setSlip] = useState<ReceiptPrint | null>(null); const [slip, setSlip] = useState<ReceiptPrint | null>(null);
const slipRef = useRef<HTMLDivElement>(null); const slipRef = useRef<HTMLDivElement>(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 d = q.data;
const initial = useMemo(() => (d ? receiptToValues(d.receipt, d.rejectReasonName) : {}), [d]); const initial = useMemo(() => (d ? receiptToValues(d.receipt, d.rejectReasonName) : {}), [d]);

View File

@ -28,6 +28,7 @@ export default defineStrings({
// fields // fields
'rc.f.receiptNo': { en: 'Number', ar: 'الرقم' }, 'rc.f.receiptNo': { en: 'Number', ar: 'الرقم' },
'rc.f.pn': { en: 'Permit number', ar: 'رقم التصريح' }, 'rc.f.pn': { en: 'Permit number', ar: 'رقم التصريح' },
'rc.f.gnPn': { en: 'Shipment number', ar: 'رقم الارسالية' },
'rc.f.company': { en: 'Company', ar: 'اسم الشركة' }, 'rc.f.company': { en: 'Company', ar: 'اسم الشركة' },
'rc.f.cargoType': { en: 'Cargo type', ar: 'النمط' }, 'rc.f.cargoType': { en: 'Cargo type', ar: 'النمط' },
'rc.f.shipmentMode': { 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.mobile': { en: 'Mobile', ar: 'الموبايل' },
'rc.f.dln': { en: 'Driving licence no.', ar: 'رقم رخصة السائق' }, 'rc.f.dln': { en: 'Driving licence no.', ar: 'رقم رخصة السائق' },
'rc.f.dled': { en: 'Driving licence expiry', 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.credit': { en: 'Kind', ar: 'النوع' },
'rc.f.onCredit': { en: 'On credit (financial claim)', 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.receiptType': { en: 'Receipt type', ar: 'نوع الوصل' },
'rc.f.creationDate': { en: 'Created', ar: 'تاريخ الانشاء' }, 'rc.f.creationDate': { en: 'Created', ar: 'تاريخ الانشاء' },
'rc.f.createdBy': { en: 'Created by', ar: 'إنشاء بواسطة' }, 'rc.f.createdBy': { en: 'Created by', ar: 'إنشاء بواسطة' },
@ -115,7 +119,7 @@ export default defineStrings({
'rc.method.AUDIT': { en: 'Audit', ar: 'تدقيق سندات القبض المالية' }, 'rc.method.AUDIT': { en: 'Audit', ar: 'تدقيق سندات القبض المالية' },
'rc.method.FIN_AUDIT': { en: 'Financial audit', ar: 'تدقيق مالي' }, 'rc.method.FIN_AUDIT': { en: 'Financial audit', ar: 'تدقيق مالي' },
'rc.prop.SCAC': { en: 'Company code', 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.FMSHIPMENTMODE': { en: 'First move cargo', ar: 'نمط الحركة الاولى' },
'rc.prop.SHIPMENTMODE': { en: 'Cargo type', ar: 'النمط' }, 'rc.prop.SHIPMENTMODE': { en: 'Cargo type', ar: 'النمط' },
'rc.prop.TN': { en: 'Truck', ar: 'رقم الشاحنة' }, 'rc.prop.TN': { en: 'Truck', ar: 'رقم الشاحنة' },