Billing: port new Invoice.cfc rules; invoice/document number mapping; grid tweaks
- addBillingInfo: price = GRAINS_WAGE rate and fine price = GRAINS_FINE rate of the claim's cargo type on the loading date; final cost = wage - shortage fine; invoice cargo-family check (38 / 74 / 39+41); archived-invoice and duplicate-permit checks; first billing creates the INVOICE row; unclosed permit is closed with a "Billing Close." event; company name from NTP_TENDERS_COMPANIES; raw permit weights no longer stored. - getBillingInfo: permits since 2020, tender company name, last invoice per user, already-billed check. - "رقم المطالبة" is stored in INVOICENUMBER and "رقم المستند" in SERIALNO (digits only). - Wages grid shows the wage with 4 decimals; invoices grid gets a company-number column; count / sent / received weight columns centred. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
cbdfe423c1
commit
e5159c7383
|
|
@ -19,66 +19,107 @@ public interface IBillingService
|
||||||
public sealed class BillingService(
|
public sealed class BillingService(
|
||||||
IBillingRepository repository,
|
IBillingRepository repository,
|
||||||
IUnitOfWork unitOfWork,
|
IUnitOfWork unitOfWork,
|
||||||
|
IEventLogger events,
|
||||||
ICurrentUser user,
|
ICurrentUser user,
|
||||||
IValidator<AddBillingRequest> validator) : IBillingService
|
IValidator<AddBillingRequest> validator) : IBillingService
|
||||||
{
|
{
|
||||||
private static string? Date(DateTime? d) => d?.ToString("yyyy-MM-dd");
|
private static string? Date(DateTime? d) => d?.ToString("yyyy-MM-dd");
|
||||||
|
|
||||||
|
/// <summary>Port of getBillingInfo (2023 version): empty PN, billing already entered, permit not found.</summary>
|
||||||
public async Task<BillingPermitDto> GetPermitAsync(long pn, long? scac, CancellationToken ct)
|
public async Task<BillingPermitDto> GetPermitAsync(long pn, long? scac, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var info = await repository.GetPermitBillingInfoAsync(pn, ct) ?? throw OrdersErrors.InvalidPn();
|
if (await repository.PnExistsAsync(pn, ct)) throw OrdersErrors.BillingExists();
|
||||||
|
var info = await repository.GetPermitBillingInfoAsync(pn, user.UserId, ct) ?? throw OrdersErrors.InvalidPn();
|
||||||
if (scac.HasValue && scac.Value != info.Scac) throw OrdersErrors.PnNotOfCompany();
|
if (scac.HasValue && scac.Value != info.Scac) throw OrdersErrors.PnNotOfCompany();
|
||||||
|
|
||||||
var lnw = BillingCalculator.NetWeight(info.Lgw, info.Ltw);
|
var lnw = BillingCalculator.NetWeight(info.Lgw, info.Ltw);
|
||||||
var dnw = BillingCalculator.NetWeight(info.Dgw, info.Dtw);
|
var dnw = BillingCalculator.NetWeight(info.Dgw, info.Dtw);
|
||||||
|
|
||||||
|
// Prices shown on the screen are the ones addBillingInfo will store: the destination's wage rate and the
|
||||||
|
// cargo type's fine rate, both valid on the loading date.
|
||||||
|
decimal? price = null, finePrice = null;
|
||||||
|
if (info.LoadDate.HasValue)
|
||||||
|
{
|
||||||
|
if (info.Destination.HasValue)
|
||||||
|
price = (await repository.GetWageRateAsync(info.Destination.Value, info.LoadDate.Value.Date, ct))?.Wage;
|
||||||
|
if (info.CargoType.HasValue)
|
||||||
|
finePrice = (await repository.GetFineRateAsync(info.CargoType.Value, info.LoadDate.Value.Date, ct))?.Fine;
|
||||||
|
}
|
||||||
return new BillingPermitDto(
|
return new BillingPermitDto(
|
||||||
info.Pn, info.Scac, info.CompanyName, info.CargoType, info.Tn, info.Destination,
|
info.Pn, info.Scac, info.CompanyName, info.CargoType, info.Tn, info.Destination,
|
||||||
Date(info.LoadDate), Date(info.DischargeDate), lnw,
|
Date(info.LoadDate), Date(info.DischargeDate), lnw,
|
||||||
dnw == 0 ? null : dnw, // the legacy page left the received-weight box empty when it was 0
|
dnw == 0 ? null : dnw, // the legacy page left the received-weight box empty when it was 0
|
||||||
info.LastInvoice,
|
info.LastInvoice, price, finePrice);
|
||||||
BillingPrices.Get(info.Destination), BillingPrices.Get(info.CargoType));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Port of addBillingInfo (Invoice.cfc, 2023) with the field mapping corrected on request: "رقم المطالبة" is the invoice
|
||||||
|
/// number (INVOICE / GRAINS_BILLING.INVOICENUMBER) and "رقم المستند" is stored in GRAINS_BILLING.SERIALNO.
|
||||||
|
/// (The legacy CFC had the two swapped.)
|
||||||
|
/// </summary>
|
||||||
public async Task<OrdersResult> AddAsync(AddBillingRequest request, CancellationToken ct)
|
public async Task<OrdersResult> AddAsync(AddBillingRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await validator.ValidateAndThrowAsync(request, ct);
|
await validator.ValidateAndThrowAsync(request, ct);
|
||||||
|
var invoiceNumber = request.InvoiceNumber;
|
||||||
|
var serialNo = long.Parse(request.SerialNo.Trim());
|
||||||
|
|
||||||
var info = await repository.GetPermitBillingInfoAsync(request.Pn, ct) ?? throw OrdersErrors.InvalidPn();
|
// 1. an invoice keeps one family of cargo types (38 / 74 / 39+41)
|
||||||
if (info.Scac != request.Scac) throw OrdersErrors.PnNotOfCompany();
|
var invoiceCargo = await repository.GetInvoiceCargoTypeAsync(request.Scac, invoiceNumber, ct);
|
||||||
|
if (invoiceCargo.HasValue && !BillingCalculator.IsCargoAllowedOnInvoice(invoiceCargo.Value, request.CargoType))
|
||||||
|
throw OrdersErrors.InvoiceCargoMismatch();
|
||||||
|
|
||||||
|
// 2. archived invoices take no new billing
|
||||||
|
var invoiceStatus = await repository.GetInvoiceStatusAsync(request.Scac.ToString(), invoiceNumber.ToString(), ct);
|
||||||
|
if (string.Equals(invoiceStatus, "ARCHIVED", StringComparison.OrdinalIgnoreCase)) throw OrdersErrors.InvoiceArchived();
|
||||||
|
|
||||||
|
// 3. one billing per permit
|
||||||
|
if (await repository.PnExistsAsync(request.Pn, ct)) throw OrdersErrors.BillingExists();
|
||||||
|
|
||||||
|
// page JS rules kept as server checks
|
||||||
if (!BillingCalculator.IsDischargeAfterLoad(request.LoadDate, request.DischargeDate)) throw OrdersErrors.DischargeBeforeLoad();
|
if (!BillingCalculator.IsDischargeAfterLoad(request.LoadDate, request.DischargeDate)) throw OrdersErrors.DischargeBeforeLoad();
|
||||||
|
|
||||||
// Sent / received weights are typed by the user (prefilled from the permit), like the legacy LNW / DNW inputs.
|
|
||||||
var lnw = request.Lnw;
|
var lnw = request.Lnw;
|
||||||
var dnw = request.Dnw;
|
var dnw = request.Dnw;
|
||||||
if (dnw <= 0) throw OrdersErrors.ReceivedWeightMissing();
|
if (dnw <= 0) throw OrdersErrors.ReceivedWeightMissing();
|
||||||
if (!BillingCalculator.IsSentWeightInRange(lnw)) throw OrdersErrors.SentWeightRange();
|
if (!BillingCalculator.IsSentWeightInRange(lnw)) throw OrdersErrors.SentWeightRange();
|
||||||
|
|
||||||
// PRICE / FINEPRICE come from the static price table (legacy: readonly inputs filled from the same table).
|
// 4. PRICE = wage rate of the destination on the loading date, FINEPRICE = fine rate of the cargo type on that
|
||||||
var price = BillingPrices.Get(request.Destination);
|
// date; if either is missing the billing cannot be added.
|
||||||
var finePrice = BillingPrices.Get(request.CargoType);
|
var wage = await repository.GetWageRateAsync(request.Destination, request.LoadDate.Date, ct);
|
||||||
if (price is null || finePrice is null) throw OrdersErrors.PriceNotDefined();
|
var fine = await repository.GetFineRateAsync(request.CargoType, request.LoadDate.Date, ct);
|
||||||
|
if (wage is null || fine is null) throw OrdersErrors.PriceNotDefined();
|
||||||
|
|
||||||
|
var wageAmount = BillingCalculator.Wage(wage.Wage, lnw);
|
||||||
|
var loseFine = BillingCalculator.ShortageFine(lnw, dnw, fine.Allowance, fine.Fine);
|
||||||
|
var finalCost = wageAmount - loseFine;
|
||||||
|
|
||||||
|
var companyName = await repository.GetTenderCompanyNameAsync(request.Scac, ct);
|
||||||
|
var permit = await repository.GetPermitRefAsync(request.Pn, ct) ?? throw OrdersErrors.InvalidPn();
|
||||||
|
|
||||||
return await unitOfWork.ExecuteInTransactionAsync(async token =>
|
return await unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||||
{
|
{
|
||||||
var wage = await repository.GetWageRateAsync(request.Destination, request.LoadDate.Date, token);
|
// first billing of the invoice creates it
|
||||||
var fine = await repository.GetFineRateAsync(request.LoadDate.Date, token);
|
if (invoiceStatus is null) await repository.InsertInvoiceAsync(invoiceNumber, request.Scac, token);
|
||||||
if (wage is null || fine is null) throw OrdersErrors.RatesNotFound();
|
|
||||||
|
|
||||||
var finalCost = BillingCalculator.Wage(wage.Wage, lnw);
|
// a permit that is not CLOSE yet is closed by the system when it is billed
|
||||||
var loseFine = BillingCalculator.ShortageFine(lnw, dnw, fine.Allowance, fine.Fine);
|
if (!string.Equals(permit.ShipmentStatusCode, "CLOSE", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
await repository.ClosePermitAsync(permit.Id, token);
|
||||||
|
await events.AddAsync(new EventEntry(
|
||||||
|
"PERMITID", permit.Id, permit.ShipmentStatusCode, "CLOSE", "SYSTEM", "OVRD", "GN", null, "NTP", null,
|
||||||
|
new Dictionary<string, object?> { ["REMARKS"] = "Billing Close." }), token);
|
||||||
|
}
|
||||||
|
|
||||||
var id = await repository.InsertAsync(new NewGrainsBilling(
|
var id = await repository.InsertAsync(new NewGrainsBilling(
|
||||||
request.Pn, request.SerialNo.Trim(), request.Tn.Trim(), request.CargoType, request.Destination,
|
request.Pn, serialNo, request.Tn.Trim(), request.CargoType, request.Destination,
|
||||||
request.LoadDate.Date, request.DischargeDate.Date,
|
request.LoadDate.Date, request.DischargeDate.Date, dnw, lnw,
|
||||||
info.Dtw, info.Dgw, dnw, info.Ltw, info.Lgw, lnw,
|
request.Scac, companyName, invoiceNumber, GrainsOrderConstants.BillingOriginId,
|
||||||
request.Scac, request.InvoiceNumber, GrainsOrderConstants.BillingOriginId,
|
wage.Wage, fine.Fine, finalCost, loseFine, user.UserId, request.DemurrageFine, request.OtherFine), token);
|
||||||
price.Value, finePrice.Value, finalCost, loseFine, user.UserId, request.DemurrageFine, request.OtherFine), token);
|
|
||||||
|
|
||||||
return new OrdersResult(OrdersErrors.Success, id);
|
return new OrdersResult(OrdersErrors.Success, id);
|
||||||
}, ct);
|
}, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>Legacy returned an empty grid when no filter was supplied.</summary>
|
/// <summary>Legacy returned an empty grid when no filter was supplied.</summary>
|
||||||
public async Task<PagedResult<BillingDto>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct)
|
public async Task<PagedResult<BillingDto>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -97,6 +97,8 @@ public sealed class PermitBillingInfo
|
||||||
public decimal Dtw { get; set; }
|
public decimal Dtw { get; set; }
|
||||||
public decimal Dgw { get; set; }
|
public decimal Dgw { get; set; }
|
||||||
public long? LastInvoice { get; set; }
|
public long? LastInvoice { get; set; }
|
||||||
|
/// <summary>PERMITS.SHIPMENTSTATUSCODE (legacy BILLINGSTATUS).</summary>
|
||||||
|
public string? ShipmentStatusCode { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Billing screen prefill (page JS getAllInformation + price table).</summary>
|
/// <summary>Billing screen prefill (page JS getAllInformation + price table).</summary>
|
||||||
|
|
@ -120,7 +122,15 @@ public sealed record AddBillingRequest(
|
||||||
decimal DemurrageFine = 0,
|
decimal DemurrageFine = 0,
|
||||||
decimal OtherFine = 0);
|
decimal OtherFine = 0);
|
||||||
|
|
||||||
|
/// <summary>GRAINS_WAGE row valid on the loading date: <c>Wage</c> is the price per ton (legacy PRICE).</summary>
|
||||||
public sealed record WageRate(decimal Wage);
|
public sealed record WageRate(decimal Wage);
|
||||||
|
|
||||||
|
/// <summary>Permit identity needed to close it when a billing is entered.</summary>
|
||||||
|
public sealed class PermitRef
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public string? ShipmentStatusCode { get; set; }
|
||||||
|
}
|
||||||
public sealed record FineRate(decimal Allowance, decimal Fine);
|
public sealed record FineRate(decimal Allowance, decimal Fine);
|
||||||
|
|
||||||
public sealed record BillingQuery(string? Tn, long? Pn, long? Scac, string? InvoiceNumber = null)
|
public sealed record BillingQuery(string? Tn, long? Pn, long? Scac, string? InvoiceNumber = null)
|
||||||
|
|
|
||||||
|
|
@ -58,9 +58,19 @@ public interface IQuotaRepository
|
||||||
|
|
||||||
public interface IBillingRepository
|
public interface IBillingRepository
|
||||||
{
|
{
|
||||||
Task<PermitBillingInfo?> GetPermitBillingInfoAsync(long pn, CancellationToken ct = default);
|
/// <summary>getBillingInfo: <paramref name="userId"/> scopes the "last invoice" to the user's own billings.</summary>
|
||||||
|
Task<PermitBillingInfo?> GetPermitBillingInfoAsync(long pn, string userId, CancellationToken ct = default);
|
||||||
|
/// <summary>Any non-deleted billing already entered for the permit.</summary>
|
||||||
|
Task<bool> PnExistsAsync(long pn, CancellationToken ct = default);
|
||||||
|
/// <summary>CARGOTYPE of the first non-deleted billing of the invoice (null when the invoice has none).</summary>
|
||||||
|
Task<long?> GetInvoiceCargoTypeAsync(long scac, long invoiceNumber, CancellationToken ct = default);
|
||||||
|
Task InsertInvoiceAsync(long invoiceNumber, long scac, CancellationToken ct = default);
|
||||||
|
/// <summary>NTP_TENDERS_COMPANIES.NAME for the company in the last two tenders.</summary>
|
||||||
|
Task<string?> GetTenderCompanyNameAsync(long scac, CancellationToken ct = default);
|
||||||
|
Task<PermitRef?> GetPermitRefAsync(long pn, CancellationToken ct = default);
|
||||||
|
Task ClosePermitAsync(long permitId, CancellationToken ct = default);
|
||||||
Task<WageRate?> GetWageRateAsync(long destination, DateTime loadDate, CancellationToken ct = default);
|
Task<WageRate?> GetWageRateAsync(long destination, DateTime loadDate, CancellationToken ct = default);
|
||||||
Task<FineRate?> GetFineRateAsync(DateTime loadDate, CancellationToken ct = default);
|
Task<FineRate?> GetFineRateAsync(long cargoType, DateTime loadDate, CancellationToken ct = default);
|
||||||
Task<long> InsertAsync(NewGrainsBilling billing, CancellationToken ct = default);
|
Task<long> InsertAsync(NewGrainsBilling billing, CancellationToken ct = default);
|
||||||
Task<PagedResult<BillingRow>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct = default);
|
Task<PagedResult<BillingRow>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct = default);
|
||||||
Task<BillingDetailRow?> GetDetailAsync(long id, CancellationToken ct = default);
|
Task<BillingDetailRow?> GetDetailAsync(long id, CancellationToken ct = default);
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,16 @@ public static class OrdersErrors
|
||||||
new("BILLING_LNW_RANGE", "يجب أن يكون الوزن بين 0 - 50000");
|
new("BILLING_LNW_RANGE", "يجب أن يكون الوزن بين 0 - 50000");
|
||||||
|
|
||||||
public static BusinessException PriceNotDefined() =>
|
public static BusinessException PriceNotDefined() =>
|
||||||
new("BILLING_PRICE_NOT_DEFINED", "لا يوجد سعر محدد لهذه الوجهة أو نوع المادة");
|
new("BILLING_PRICE_NOT_DEFINED", "لا تسطيع الإضافة - السعر لهذه الوجهة غير معرف");
|
||||||
|
|
||||||
|
public static BusinessException InvoiceCargoMismatch() =>
|
||||||
|
new("BILLING_INVOICE_CARGO_MISMATCH", "لا يجوز ادخال نوع مادة مختلف على نفس الفاتورة");
|
||||||
|
|
||||||
|
public static BusinessException InvoiceArchived() =>
|
||||||
|
new("BILLING_INVOICE_ARCHIVED", "لا تسطيع أضافة مطالبة جديدة لفاتورة مؤرشفة");
|
||||||
|
|
||||||
|
public static BusinessException BillingExists() =>
|
||||||
|
new("BILLING_ALREADY_EXISTS", "المطالبة مدخلة مسبقا");
|
||||||
|
|
||||||
public static BusinessException RatesNotFound() =>
|
public static BusinessException RatesNotFound() =>
|
||||||
new("BILLING_RATES_NOT_FOUND", "لا توجد أجور أو غرامات محددة لهذه الوجهة في تاريخ التحميل");
|
new("BILLING_RATES_NOT_FOUND", "لا توجد أجور أو غرامات محددة لهذه الوجهة في تاريخ التحميل");
|
||||||
|
|
@ -139,6 +148,15 @@ public static class BillingCalculator
|
||||||
{
|
{
|
||||||
private static decimal Round3(decimal v) => Math.Round(v, 3, MidpointRounding.AwayFromZero);
|
private static decimal Round3(decimal v) => Math.Round(v, 3, MidpointRounding.AwayFromZero);
|
||||||
|
|
||||||
|
/// <summary>Cargo types that may share an invoice: 38 only with 38, 74 only with 74, 39 and 41 together; others are free.</summary>
|
||||||
|
public static bool IsCargoAllowedOnInvoice(long invoiceCargo, long cargo) => invoiceCargo switch
|
||||||
|
{
|
||||||
|
38 => cargo == 38,
|
||||||
|
74 => cargo == 74,
|
||||||
|
39 or 41 => cargo is 39 or 41,
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
|
||||||
/// <summary>Net weight: gross minus tare.</summary>
|
/// <summary>Net weight: gross minus tare.</summary>
|
||||||
public static decimal NetWeight(decimal gross, decimal tare) => gross - tare;
|
public static decimal NetWeight(decimal gross, decimal tare) => gross - tare;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,8 @@ public sealed class AddBillingValidator : AbstractValidator<AddBillingRequest>
|
||||||
RuleFor(x => x.Pn).GreaterThan(0).WithMessage("رقم الارسالية مطلوب");
|
RuleFor(x => x.Pn).GreaterThan(0).WithMessage("رقم الارسالية مطلوب");
|
||||||
RuleFor(x => x.Scac).GreaterThan(0).WithMessage("اسم الشركة مطلوب");
|
RuleFor(x => x.Scac).GreaterThan(0).WithMessage("اسم الشركة مطلوب");
|
||||||
RuleFor(x => x.InvoiceNumber).GreaterThan(0).WithMessage("رقم المطالبة مطلوب");
|
RuleFor(x => x.InvoiceNumber).GreaterThan(0).WithMessage("رقم المطالبة مطلوب");
|
||||||
RuleFor(x => x.SerialNo).NotEmpty().MaximumLength(30).WithMessage("رقم المستند مطلوب");
|
// GRAINS_BILLING.SERIALNO is numeric, so the document number must be digits
|
||||||
|
RuleFor(x => x.SerialNo).NotEmpty().Matches(@"^[0-9]{1,12}$").WithMessage("رقم المستند مطلوب");
|
||||||
RuleFor(x => x.LoadDate).NotEmpty().WithMessage("تاريخ التحميل مطلوب");
|
RuleFor(x => x.LoadDate).NotEmpty().WithMessage("تاريخ التحميل مطلوب");
|
||||||
RuleFor(x => x.DischargeDate).NotEmpty().WithMessage("تاريخ التفريغ مطلوب");
|
RuleFor(x => x.DischargeDate).NotEmpty().WithMessage("تاريخ التفريغ مطلوب");
|
||||||
RuleFor(x => x.Destination).GreaterThan(0).WithMessage("الى مطلوب");
|
RuleFor(x => x.Destination).GreaterThan(0).WithMessage("الى مطلوب");
|
||||||
|
|
|
||||||
|
|
@ -56,8 +56,10 @@ public sealed record NewTenderOrder(
|
||||||
int Quantity, string? Type, string Ct, string CreatedBy);
|
int Quantity, string? Type, string Ct, string CreatedBy);
|
||||||
|
|
||||||
/// <summary>New GRAINS_BILLING row (columns exactly as written by legacy addBillingInfo).</summary>
|
/// <summary>New GRAINS_BILLING row (columns exactly as written by legacy addBillingInfo).</summary>
|
||||||
|
/// <summary>Row inserted by Invoice.cfc addBillingInfo (the 2023 version no longer stores the permit's raw weights).
|
||||||
|
/// <c>SerialNo</c> = the screen's "رقم المستند", <c>InvoiceNumber</c> = the screen's "رقم المطالبة".</summary>
|
||||||
public sealed record NewGrainsBilling(
|
public sealed record NewGrainsBilling(
|
||||||
long Pn, string SerialNo, string Tn, long CargoType, long Destination, DateTime LoadDate, DateTime DischargeDate,
|
long Pn, long SerialNo, string Tn, long CargoType, long Destination, DateTime LoadDate, DateTime DischargeDate,
|
||||||
decimal Dtw, decimal Dgw, decimal Dnw, decimal Ltw, decimal Lgw, decimal Lnw, long Scac, long InvoiceNumber,
|
decimal Dnw, decimal Lnw, long Scac, string? CompanyName, long InvoiceNumber,
|
||||||
long Origin, decimal Price, decimal FinePrice, decimal FinalCost, decimal LoseFine, string CreateUserId = "",
|
long Origin, decimal Price, decimal FinePrice, decimal FinalCost, decimal LoseFine, string CreateUserId = "",
|
||||||
decimal DemurrageFine = 0, decimal OtherFine = 0);
|
decimal DemurrageFine = 0, decimal OtherFine = 0);
|
||||||
|
|
|
||||||
|
|
@ -12,11 +12,13 @@ namespace NTP.Infrastructure.Persistence.Repositories.Grains.Orders;
|
||||||
internal sealed class BillingRepository(IDbSession session, ILogger<BillingRepository> logger)
|
internal sealed class BillingRepository(IDbSession session, ILogger<BillingRepository> logger)
|
||||||
: OracleRepositoryBase(session, logger), IBillingRepository
|
: OracleRepositoryBase(session, logger), IBillingRepository
|
||||||
{
|
{
|
||||||
public Task<PermitBillingInfo?> GetPermitBillingInfoAsync(long pn, CancellationToken ct = default) =>
|
// Invoice.cfc getBillingInfo (2023 version): no CLOSE filter any more, permits created after 1/1/2020,
|
||||||
|
// company name from NTP_TENDERS_COMPANIES, "last invoice" limited to the signed-in user's non-deleted billings.
|
||||||
|
public Task<PermitBillingInfo?> GetPermitBillingInfoAsync(long pn, string userId, CancellationToken ct = default) =>
|
||||||
QueryFirstAsync<PermitBillingInfo>("""
|
QueryFirstAsync<PermitBillingInfo>("""
|
||||||
SELECT p.pn AS Pn,
|
SELECT p.pn AS Pn,
|
||||||
p.companycode AS Scac,
|
p.companycode AS Scac,
|
||||||
getcompanynamefromscac(p.companycode, 62) AS CompanyName,
|
NVL(c.name, getcompanynamefromscac(p.companycode, 62)) AS CompanyName,
|
||||||
p.shipmentmode AS CargoType,
|
p.shipmentmode AS CargoType,
|
||||||
p.tn AS Tn,
|
p.tn AS Tn,
|
||||||
p.originaddressid AS Origin,
|
p.originaddressid AS Origin,
|
||||||
|
|
@ -28,16 +30,61 @@ internal sealed class BillingRepository(IDbSession session, ILogger<BillingRepos
|
||||||
(SELECT MIN(e.eventdate) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'LTW') + 1) AS DischargeDate,
|
(SELECT MIN(e.eventdate) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'LTW') + 1) AS DischargeDate,
|
||||||
NVL((SELECT MIN(e.weight) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'DTW'), 0) AS Dtw,
|
NVL((SELECT MIN(e.weight) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'DTW'), 0) AS Dtw,
|
||||||
NVL((SELECT MIN(e.weight) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'DGW'), 0) AS Dgw,
|
NVL((SELECT MIN(e.weight) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'DGW'), 0) AS Dgw,
|
||||||
i.lastInvoice AS LastInvoice
|
i.lastInvoice AS LastInvoice,
|
||||||
|
p.shipmentstatuscode AS ShipmentStatusCode
|
||||||
FROM permits p,
|
FROM permits p,
|
||||||
|
ntp_tenders_companies c,
|
||||||
(SELECT DISTINCT FIRST_VALUE(t.invoicenumber) OVER (PARTITION BY t.scac ORDER BY t.id DESC) lastInvoice, scac
|
(SELECT DISTINCT FIRST_VALUE(t.invoicenumber) OVER (PARTITION BY t.scac ORDER BY t.id DESC) lastInvoice, scac
|
||||||
FROM GRAINS_BILLING t) i
|
FROM GRAINS_BILLING t
|
||||||
|
WHERE t.createuserid = :UserId
|
||||||
|
AND NVL(t.statuscode, 'ACTIVE') NOT IN ('DELETED')) i
|
||||||
WHERE p.domain = 'GN'
|
WHERE p.domain = 'GN'
|
||||||
AND p.shipmentstatuscode = 'CLOSE'
|
AND p.creationdate > TO_DATE('1/1/2020', 'dd/mm/yyyy')
|
||||||
AND i.scac(+) = p.companycode
|
AND i.scac(+) = p.companycode
|
||||||
|
AND c.scac(+) = p.companycode
|
||||||
AND p.pn = :Pn
|
AND p.pn = :Pn
|
||||||
""", new { Pn = pn.ToString() }, ct);
|
ORDER BY c.id DESC
|
||||||
|
""", new { Pn = pn.ToString(), UserId = userId }, ct);
|
||||||
|
|
||||||
|
public async Task<bool> PnExistsAsync(long pn, CancellationToken ct = default) =>
|
||||||
|
await ExecuteScalarAsync<long>(
|
||||||
|
"SELECT COUNT(*) FROM GRAINS_BILLING WHERE pn = :Pn AND NVL(statuscode, 'ACTIVE') NOT IN ('DELETED')", new { Pn = pn }, ct) > 0;
|
||||||
|
|
||||||
|
public async Task<long?> GetInvoiceCargoTypeAsync(long scac, long invoiceNumber, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var rows = await QueryAsync<long?>("""
|
||||||
|
SELECT t.cargotype FROM GRAINS_BILLING t
|
||||||
|
WHERE t.invoicenumber = :Inv AND t.scac = :Scac AND NVL(t.statuscode, 'ACTIVE') NOT IN ('DELETED')
|
||||||
|
ORDER BY t.id
|
||||||
|
""", new { Inv = invoiceNumber, Scac = scac }, ct);
|
||||||
|
return rows.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task InsertInvoiceAsync(long invoiceNumber, long scac, CancellationToken ct = default) =>
|
||||||
|
ExecuteAsync("""
|
||||||
|
INSERT INTO INVOICE (ID, INVOICENUMBER, SCAC, STATUSCODE, DOMAIN, INVOICEDATE)
|
||||||
|
VALUES (seq_INVOICE.NEXTVAL, :Inv, :Scac, 'ACTIVE', 'GN', SYSDATE)
|
||||||
|
""", new { Inv = invoiceNumber, Scac = scac }, ct);
|
||||||
|
|
||||||
|
public async Task<string?> GetTenderCompanyNameAsync(long scac, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var rows = await QueryAsync<string>("""
|
||||||
|
SELECT t.name FROM NTP_TENDERS_COMPANIES t
|
||||||
|
WHERE t.scac = :Scac
|
||||||
|
AND t.tenderid IN ((SELECT MAX(id) FROM NTP_TENDER), (SELECT MAX(id) - 1 FROM NTP_TENDER))
|
||||||
|
ORDER BY t.id DESC
|
||||||
|
""", new { Scac = scac }, ct);
|
||||||
|
return rows.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<PermitRef?> GetPermitRefAsync(long pn, CancellationToken ct = default) =>
|
||||||
|
QueryFirstAsync<PermitRef>("SELECT p.id AS Id, p.shipmentstatuscode AS ShipmentStatusCode FROM permits p WHERE p.domain = 'GN' AND p.pn = :Pn",
|
||||||
|
new { Pn = pn.ToString() }, ct);
|
||||||
|
|
||||||
|
public Task ClosePermitAsync(long permitId, CancellationToken ct = default) =>
|
||||||
|
ExecuteAsync("UPDATE PERMITS SET shipmentstatuscode = 'CLOSE' WHERE id = :Id", new { Id = permitId }, ct);
|
||||||
|
|
||||||
|
// Invoice.cfc addBillingInfo: PRICE = the destination's wage rate on the loading date (GRAINS_WAGE).
|
||||||
public Task<WageRate?> GetWageRateAsync(long destination, DateTime loadDate, CancellationToken ct = default) =>
|
public Task<WageRate?> GetWageRateAsync(long destination, DateTime loadDate, CancellationToken ct = default) =>
|
||||||
QueryFirstAsync<WageRate>("""
|
QueryFirstAsync<WageRate>("""
|
||||||
SELECT w.wage AS Wage
|
SELECT w.wage AS Wage
|
||||||
|
|
@ -47,53 +94,34 @@ internal sealed class BillingRepository(IDbSession session, ILogger<BillingRepos
|
||||||
ORDER BY w.startdate DESC
|
ORDER BY w.startdate DESC
|
||||||
""", new { Dest = destination, LoadDate = loadDate.Date }, ct);
|
""", new { Dest = destination, LoadDate = loadDate.Date }, ct);
|
||||||
|
|
||||||
public Task<FineRate?> GetFineRateAsync(DateTime loadDate, CancellationToken ct = default) =>
|
// FINEPRICE / allowance of the billing's own cargo type (the 2023 version no longer hard-codes cargo type 38).
|
||||||
|
public Task<FineRate?> GetFineRateAsync(long cargoType, DateTime loadDate, CancellationToken ct = default) =>
|
||||||
QueryFirstAsync<FineRate>("""
|
QueryFirstAsync<FineRate>("""
|
||||||
SELECT f.allowance AS Allowance, f.fine AS Fine
|
SELECT f.allowance AS Allowance, f.fine AS Fine
|
||||||
FROM grains_fine f
|
FROM grains_fine f
|
||||||
WHERE f.cargotype = :FineCargo
|
WHERE f.cargotype = :Cargo
|
||||||
AND :LoadDate BETWEEN f.startdate AND f.enddate
|
AND :LoadDate BETWEEN f.startdate AND f.enddate
|
||||||
ORDER BY f.startdate DESC
|
ORDER BY f.startdate DESC
|
||||||
""", new { FineCargo = GrainsOrderConstants.FineCargoTypeId, LoadDate = loadDate.Date }, ct);
|
""", new { Cargo = cargoType, LoadDate = loadDate.Date }, ct);
|
||||||
|
|
||||||
// Mirrors db.cfc addDBRecordNOORM: ID comes from seq_<table>.nextval.
|
|
||||||
public async Task<long> InsertAsync(NewGrainsBilling b, CancellationToken ct = default)
|
public async Task<long> InsertAsync(NewGrainsBilling b, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var p = new DynamicParameters(new
|
var p = new DynamicParameters(new
|
||||||
{
|
{
|
||||||
b.Pn,
|
b.Pn, b.SerialNo, b.Tn, b.CargoType, b.Destination,
|
||||||
b.SerialNo,
|
LoadDate = b.LoadDate.Date, DischargeDate = b.DischargeDate.Date,
|
||||||
b.Tn,
|
b.Dnw, b.Lnw, b.Scac, b.CompanyName, b.InvoiceNumber, b.Origin, b.Price, b.FinePrice,
|
||||||
b.CargoType,
|
b.FinalCost, b.LoseFine, b.CreateUserId, b.DemurrageFine, b.OtherFine,
|
||||||
b.Destination,
|
|
||||||
LoadDate = b.LoadDate.Date,
|
|
||||||
DischargeDate = b.DischargeDate.Date,
|
|
||||||
b.Dtw,
|
|
||||||
b.Dgw,
|
|
||||||
b.Dnw,
|
|
||||||
b.Ltw,
|
|
||||||
b.Lgw,
|
|
||||||
b.Lnw,
|
|
||||||
b.Scac,
|
|
||||||
b.InvoiceNumber,
|
|
||||||
b.Origin,
|
|
||||||
b.Price,
|
|
||||||
b.FinePrice,
|
|
||||||
b.FinalCost,
|
|
||||||
b.LoseFine,
|
|
||||||
b.CreateUserId,
|
|
||||||
b.DemurrageFine,
|
|
||||||
b.OtherFine
|
|
||||||
});
|
});
|
||||||
p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output);
|
p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output);
|
||||||
|
|
||||||
await ExecuteAsync("""
|
await ExecuteAsync("""
|
||||||
INSERT INTO GRAINS_BILLING
|
INSERT INTO GRAINS_BILLING
|
||||||
(ID, PN, SERIALNO, TN, CARGOTYPE, DESTINATION, LOADDATE, DISCHARGEDATE, DTW, DGW, DNW, LTW, LGW, LNW,
|
(ID, PN, SERIALNO, TN, CARGOTYPE, DESTINATION, LOADDATE, DISCHARGEDATE, DNW, LNW,
|
||||||
SCAC, INVOICENUMBER, ORIGIN, PRICE, FINEPRICE, FINALCOST, LOSEFINE, CREATEUSERID, DEMURRAGEFINE, OTHERFINE)
|
SCAC, COMPANYNAME, INVOICENUMBER, ORIGIN, PRICE, FINEPRICE, FINALCOST, LOSEFINE, CREATEUSERID, DEMURRAGEFINE, OTHERFINE)
|
||||||
VALUES
|
VALUES
|
||||||
(seq_GRAINS_BILLING.NEXTVAL, :Pn, :SerialNo, :Tn, :CargoType, :Destination, :LoadDate, :DischargeDate, :Dtw, :Dgw, :Dnw, :Ltw, :Lgw, :Lnw,
|
(seq_GRAINS_BILLING.NEXTVAL, :Pn, :SerialNo, :Tn, :CargoType, :Destination, :LoadDate, :DischargeDate, :Dnw, :Lnw,
|
||||||
:Scac, :InvoiceNumber, :Origin, :Price, :FinePrice, :FinalCost, :LoseFine, :CreateUserId, :DemurrageFine, :OtherFine)
|
:Scac, :CompanyName, :InvoiceNumber, :Origin, :Price, :FinePrice, :FinalCost, :LoseFine, :CreateUserId, :DemurrageFine, :OtherFine)
|
||||||
RETURNING ID INTO :NewId
|
RETURNING ID INTO :NewId
|
||||||
""", p, ct);
|
""", p, ct);
|
||||||
return OracleSql.ToInt64(p.Get<object>("NewId"));
|
return OracleSql.ToInt64(p.Get<object>("NewId"));
|
||||||
|
|
@ -104,7 +132,7 @@ internal sealed class BillingRepository(IDbSession session, ILogger<BillingRepos
|
||||||
var sql = new StringBuilder("""
|
var sql = new StringBuilder("""
|
||||||
SELECT t.id AS Id,
|
SELECT t.id AS Id,
|
||||||
ctp.name AS CargoType,
|
ctp.name AS CargoType,
|
||||||
getcompanynamefromscac(t.scac, 62) AS Scac,
|
NVL(t.companyname, getcompanynamefromscac(t.scac, 62)) AS Scac,
|
||||||
t.pn AS Pn,
|
t.pn AS Pn,
|
||||||
t.tn AS Tn,
|
t.tn AS Tn,
|
||||||
t.loaddate AS LoadDate,
|
t.loaddate AS LoadDate,
|
||||||
|
|
|
||||||
|
|
@ -140,11 +140,24 @@ public class BillingCalculatorTests
|
||||||
public void Add_billing_validator_requires_the_form_fields()
|
public void Add_billing_validator_requires_the_form_fields()
|
||||||
{
|
{
|
||||||
var v = new AddBillingValidator();
|
var v = new AddBillingValidator();
|
||||||
var ok = new AddBillingRequest(1, 2, 3, "S1", DateTime.Today, DateTime.Today, 215, 38, "T1");
|
var ok = new AddBillingRequest(1, 2, 3, "501", DateTime.Today, DateTime.Today, 215, 38, "T1");
|
||||||
Assert.True(v.Validate(ok).IsValid);
|
Assert.True(v.Validate(ok).IsValid);
|
||||||
Assert.False(v.Validate(ok with { SerialNo = "" }).IsValid);
|
Assert.False(v.Validate(ok with { SerialNo = "" }).IsValid);
|
||||||
|
Assert.False(v.Validate(ok with { SerialNo = "S1" }).IsValid); // invoice number: digits only (legacy Float check)
|
||||||
Assert.False(v.Validate(ok with { Tn = "" }).IsValid);
|
Assert.False(v.Validate(ok with { Tn = "" }).IsValid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(38, 38, true)]
|
||||||
|
[InlineData(38, 39, false)]
|
||||||
|
[InlineData(74, 74, true)]
|
||||||
|
[InlineData(74, 38, false)]
|
||||||
|
[InlineData(39, 41, true)]
|
||||||
|
[InlineData(41, 39, true)]
|
||||||
|
[InlineData(39, 40, false)]
|
||||||
|
[InlineData(40, 38, true)]
|
||||||
|
public void Invoice_keeps_one_cargo_family(long onInvoice, long entered, bool allowed)
|
||||||
|
=> Assert.Equal(allowed, BillingCalculator.IsCargoAllowedOnInvoice(onInvoice, entered));
|
||||||
}
|
}
|
||||||
|
|
||||||
public class GrainsWeightRulesTests
|
public class GrainsWeightRulesTests
|
||||||
|
|
|
||||||
|
|
@ -29,8 +29,8 @@ export const billingGrid = (h: { onDelete: (r: BillingRow) => void; onReroute: (
|
||||||
{ key: 'destination', header: { en: 'Destination', ar: 'الوجهة' } },
|
{ key: 'destination', header: { en: 'Destination', ar: 'الوجهة' } },
|
||||||
{ key: 'loadDate', header: { en: 'Load date', ar: 'تاريخ التحميل' }, format: 'date', ltr: true, hideBelow: 'md' },
|
{ key: 'loadDate', header: { en: 'Load date', ar: 'تاريخ التحميل' }, format: 'date', ltr: true, hideBelow: 'md' },
|
||||||
{ key: 'dischargeDate', header: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, format: 'date', ltr: true, hideBelow: 'md' },
|
{ key: 'dischargeDate', header: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, format: 'date', ltr: true, hideBelow: 'md' },
|
||||||
{ key: 'lnw', header: { en: 'Sent weight', ar: 'الوزن المرسل' }, format: 'number', align: 'end' },
|
{ key: 'lnw', header: { en: 'Sent weight', ar: 'الوزن المرسل' }, format: 'number', align: 'center' },
|
||||||
{ key: 'dnw', header: { en: 'Received weight', ar: 'الوزن المستلم' }, format: 'number', align: 'end' },
|
{ key: 'dnw', header: { en: 'Received weight', ar: 'الوزن المستلم' }, format: 'number', align: 'center' },
|
||||||
{ key: 'invoiceNumber', header: { en: 'Invoice', ar: 'الفاتورة' }, ltr: true },
|
{ key: 'invoiceNumber', header: { en: 'Invoice', ar: 'الفاتورة' }, ltr: true },
|
||||||
{ key: 'createUserId', header: { en: 'By', ar: 'بواسطة' }, ltr: true, hideBelow: 'lg' },
|
{ key: 'createUserId', header: { en: 'By', ar: 'بواسطة' }, ltr: true, hideBelow: 'lg' },
|
||||||
],
|
],
|
||||||
|
|
@ -50,7 +50,7 @@ export const billingForm: FormMeta = {
|
||||||
columns: 2,
|
columns: 2,
|
||||||
fields: [
|
fields: [
|
||||||
{ name: 'invoiceNumber', type: 'text', label: { en: 'Invoice number', ar: 'رقم المطالبة' }, required: true, inputKind: 'code', maxLength: 12, pattern: { regex: /^\d+$/, message: { en: 'Digits only', ar: 'أرقام فقط' } } },
|
{ name: 'invoiceNumber', type: 'text', label: { en: 'Invoice number', ar: 'رقم المطالبة' }, required: true, inputKind: 'code', maxLength: 12, pattern: { regex: /^\d+$/, message: { en: 'Digits only', ar: 'أرقام فقط' } } },
|
||||||
{ name: 'serialNo', type: 'text', label: { en: 'Document number', ar: 'رقم المستند' }, required: true, inputKind: 'code', maxLength: 30 },
|
{ name: 'serialNo', type: 'text', label: { en: 'Document number', ar: 'رقم المستند' }, required: true, inputKind: 'code', maxLength: 12, pattern: { regex: /^[0-9]+$/, message: { en: 'Digits only', ar: 'أرقام فقط' } } },
|
||||||
{ name: 'loadDate', type: 'date', label: { en: 'Load date', ar: 'تاريخ التحميل' }, required: true },
|
{ name: 'loadDate', type: 'date', label: { en: 'Load date', ar: 'تاريخ التحميل' }, required: true },
|
||||||
{ name: 'dischargeDate', type: 'date', label: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, required: true },
|
{ name: 'dischargeDate', type: 'date', label: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, required: true },
|
||||||
{ name: 'origin', type: 'text', label: { en: 'From', ar: 'من' }, readOnly: true },
|
{ name: 'origin', type: 'text', label: { en: 'From', ar: 'من' }, readOnly: true },
|
||||||
|
|
@ -88,9 +88,10 @@ export const invoiceGrid = (h: {
|
||||||
filters: [{ name: 'invoiceNumber', type: 'text', label: { en: 'Invoice number', ar: 'رقم الفاتورة' }, inputKind: 'code' }],
|
filters: [{ name: 'invoiceNumber', type: 'text', label: { en: 'Invoice number', ar: 'رقم الفاتورة' }, inputKind: 'code' }],
|
||||||
columns: [
|
columns: [
|
||||||
{ key: 'invoiceNumber', header: { en: 'Invoice number', ar: 'رقم الفاتورة' }, ltr: true },
|
{ key: 'invoiceNumber', header: { en: 'Invoice number', ar: 'رقم الفاتورة' }, ltr: true },
|
||||||
|
{ key: 'scac', header: { en: 'Company no.', ar: 'رقم الشركة' }, ltr: true },
|
||||||
{ key: 'companyName', header: { en: 'Company', ar: 'الشركة' } },
|
{ key: 'companyName', header: { en: 'Company', ar: 'الشركة' } },
|
||||||
{ key: 'invoiceDate', header: { en: 'Entry date', ar: 'تاريخ الإدخال' }, ltr: true, hideBelow: 'sm', render: (r) => slashDate(r.invoiceDate) },
|
{ key: 'invoiceDate', header: { en: 'Entry date', ar: 'تاريخ الإدخال' }, ltr: true, hideBelow: 'sm', render: (r) => slashDate(r.invoiceDate) },
|
||||||
{ key: 'count', header: { en: 'Count', ar: 'العدد' }, format: 'number', align: 'end' },
|
{ key: 'count', header: { en: 'Count', ar: 'العدد' }, format: 'number', align: 'center' },
|
||||||
{ key: 'statusCode', header: { en: 'Status', ar: 'الحالة' }, format: 'status', statuses: invoiceStatuses },
|
{ key: 'statusCode', header: { en: 'Status', ar: 'الحالة' }, format: 'status', statuses: invoiceStatuses },
|
||||||
],
|
],
|
||||||
rowActions: [
|
rowActions: [
|
||||||
|
|
@ -160,6 +161,6 @@ export const wagesGrid = (): GridMeta<WageRow> => ({
|
||||||
{ key: 'location', header: { en: 'Location', ar: 'الموقع' } },
|
{ key: 'location', header: { en: 'Location', ar: 'الموقع' } },
|
||||||
{ key: 'startDate', header: { en: 'Start date', ar: 'تاريخ البداية' }, format: 'date', ltr: true, align: 'center' },
|
{ key: 'startDate', header: { en: 'Start date', ar: 'تاريخ البداية' }, format: 'date', ltr: true, align: 'center' },
|
||||||
{ key: 'endDate', header: { en: 'End date', ar: 'تاريخ الإنتهاء' }, format: 'date', ltr: true, align: 'center' },
|
{ key: 'endDate', header: { en: 'End date', ar: 'تاريخ الإنتهاء' }, format: 'date', ltr: true, align: 'center' },
|
||||||
{ key: 'wage', header: { en: 'Wage', ar: 'الأجر' }, format: 'number', align: 'center' },
|
{ key: 'wage', header: { en: 'Wage', ar: 'الأجر' }, ltr: true, align: 'center', render: (r) => (r.wage === null || r.wage === undefined ? '' : Number(r.wage).toFixed(4)) },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue