NTP_V2/src/NTP.Application/Receipts/ReceiptService.cs

339 lines
22 KiB
C#

using System.Globalization;
using FluentValidation;
using FluentValidation.Results;
using NTP.Application.Abstractions;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Grains.Orders;
using NTP.Application.Grains.Reports;
namespace NTP.Application.Receipts;
/// <summary>
/// Port of the AqabaTCS entity permitsreceipts (factory, factoryweb, dao): cash receipts and financial claims of the permits (سندات القبض والمطالبات
/// المالية). The screen and every action are permission keys (db/receipts-permissions.sql, from the legacy STATUS_ACTION_MATRIX); the status each action
/// needs is checked here. Every status change writes LOG_PERMITS_RECEIPTS like the legacy saveLog.
/// </summary>
public sealed class ReceiptService(
IReceiptRepository repository,
IUnitOfWork unitOfWork,
IPermissionService permissions,
IReportExcelService excel,
ICurrentUser user) : IReceiptService
{
private const int ExportLimit = 50_000;
public async Task<PagedResult<ReceiptRow>> SearchAsync(ReceiptQuery query, PageRequest page, CancellationToken ct)
{
if (query.DateFrom is { } from && query.DateTo is { } to && from.Date > to.Date) throw new BusinessException("ERROR.CREATEDATEFROM_NOT_GT_CREATEDATETO", ReceiptMessages.DateRange);
return await repository.SearchAsync(query, page, ct);
}
public async Task<ReceiptDetail> GetAsync(long id, CancellationToken ct)
{
var r = await Load(id, ct);
var reasons = r.RejectReason is { } rr ? (await repository.GetRejectReasonsAsync(ct)).FirstOrDefault(x => x.Code == rr.ToString(CultureInfo.InvariantCulture))?.Name : null;
return new ReceiptDetail(r, await ActionsAsync(r, ct), reasons);
}
public async Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct)
{
_ = await Load(id, ct);
return await repository.GetLogAsync(id, page, ct);
}
public async Task<ReceiptLookups> GetLookupsAsync(CancellationToken ct) =>
new(await repository.GetTypesAsync(null, null, ct), await repository.GetRejectReasonsAsync(ct), await repository.GetCargoTypesAsync(ct));
// ---------------------------------------------------------------- create / update
public async Task<ReceiptResult> CreateAsync(CreateReceiptRequest request, CancellationToken ct, string? ip = null)
{
await Require(PermissionKeys.ReceiptsCreate, ct);
var failures = new List<ValidationFailure>();
void Need(string field, bool ok) { if (!ok) failures.Add(new ValidationFailure(field, ReceiptMessages.Required)); }
Need("pn", long.TryParse(request.Pn?.Trim(), out _));
Need("tn", !string.IsNullOrWhiteSpace(request.Tn));
Need("trn", !string.IsNullOrWhiteSpace(request.Trn));
Need("nnpn", !string.IsNullOrWhiteSpace(request.Nnpn));
Need("drvr", !string.IsNullOrWhiteSpace(request.Drvr));
Need("shipmentMode", !string.IsNullOrWhiteSpace(request.ShipmentMode));
Need("receiptType", request.ReceiptType > 0);
Need("credit", request.Credit is 0 or 1);
if (ReceiptRules.IsDoubleMove(request.ReceiptType)) Need("fmShipmentMode", !string.IsNullOrWhiteSpace(request.FmShipmentMode));
if (failures.Count > 0) throw new ValidationException(failures);
var type = await repository.GetTypeAsync(request.ReceiptType, ct) ?? throw new BusinessException("ERROR.CREATING_RECEIPT", ReceiptMessages.UnknownType);
var pn = long.Parse(request.Pn!.Trim(), CultureInfo.InvariantCulture);
// create: the permit has to fit the type (types 8, 9, 10; legacy checkPermitType*)
if (request.ReceiptType is 8 or 9 or 10 && !await repository.PermitMatchesTypeAsync(request.ReceiptType, pn, ct))
throw new BusinessException(ReceiptErrors.DataCheck, ReceiptMessages.DataCheck);
// 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);
}
public async Task<ReceiptResult> UpdateAsync(long id, UpdateReceiptRequest request, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanUpdate(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsUpdate, ct)) throw NoAuthority();
if (!await repository.UpdateAsync(id, request, user.UserId, ct)) throw NoAuthority();
return new ReceiptResult(ReceiptMessages.Done, id);
}
// ---------------------------------------------------------------- status changes
public async Task<ReceiptResult> ConfirmAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanConfirm(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsConfirm, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, ReceiptStatus.Received);
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "CONFIRM", old, @new, user.Id, ip, null, c);
if (!await repository.ConfirmAsync(id, user.UserId, c)) throw NoAuthority();
return true;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, id);
}
/// <summary>factory.PAID: the claim becomes PAID and a cash receipt (credit 0, RECEIVED, new number) is created from it; both are logged.</summary>
public async Task<ReceiptResult> PaidAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanPay(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsPaid, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, ReceiptStatus.Paid);
var copyId = await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "PAID", old, @new, user.Id, ip, null, c);
if (!await repository.PayAsync(id, c)) throw NoAuthority();
var copy = await repository.InsertPaidCopyAsync(id, c);
var (o2, n2) = ReceiptRules.CreateLog(ReceiptStatus.Received);
await repository.AddLogAsync(copy, "CREATE", o2, n2, user.Id, ip, null, c);
return copy;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, copyId);
}
/// <summary>
/// factory.revokeReceipt: QUEUE_OP and SU ask for the cancellation (RECEIVED / UNPAID to PENDING_RVKD); the others cancel at once (RECEIVED / UNPAID, or AUDITED
/// for the roles that may). A reason from RECEIPT_REVOKE_REJECT_REASON is mandatory; a cancelled receipt has no fees.
/// </summary>
public async Task<ReceiptResult> RevokeAsync(long id, RevokeReceiptRequest request, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
var asksOnly = user.IsInAnyRole("SU", "QUEUE_OP");
string next;
if (ReceiptRules.CanRevokeOpen(r.StatusCode))
{
if (!await permissions.IsAllowedAsync(asksOnly ? PermissionKeys.ReceiptsRevokeRequest : PermissionKeys.ReceiptsRevoke, ct)) throw NoAuthority();
next = asksOnly ? ReceiptStatus.PendingRvkd : ReceiptStatus.Rvkd;
}
else if (ReceiptRules.CanRevokeAudited(r.StatusCode) && !asksOnly)
{
if (!await permissions.IsAllowedAsync(PermissionKeys.ReceiptsRevokeAudited, ct)) throw NoAuthority();
next = ReceiptStatus.Rvkd;
}
else throw NoAuthority();
var reasons = await repository.GetRejectReasonsAsync(ct);
if (request.Reason is not { } reason || reasons.All(x => x.Code != reason.ToString(CultureInfo.InvariantCulture)))
throw new ValidationException([new ValidationFailure("reason", ReceiptMessages.RejectReasonMandatory)]);
var note = RegistrarClean(request.Note);
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, next);
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "REVOKE", old, @new, user.Id, ip, null, c);
var ok = next == ReceiptStatus.PendingRvkd
? await repository.RequestRevokeAsync(id, reason, note, c)
: await repository.RevokeAsync(id, r.StatusCode!, reason, note, user.UserId, c);
if (!ok) throw NoAuthority();
return true;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, id);
}
public async Task<ReceiptResult> AcceptRevokeAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanDecideRevoke(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsAcceptRevoke, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, ReceiptStatus.Rvkd);
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "ACCEPT_REVOKE", old, @new, user.Id, ip, null, c);
if (!await repository.RevokeAsync(id, ReceiptStatus.PendingRvkd, null, null, user.UserId, c)) throw NoAuthority();
return true;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, id);
}
public async Task<ReceiptResult> RejectRevokeAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanDecideRevoke(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsRejectRevoke, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, ReceiptStatus.Received);
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "REJECT_REVOKE", old, @new, user.Id, ip, null, c);
if (!await repository.RejectRevokeAsync(id, c)) throw NoAuthority();
return true;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, id);
}
/// <summary>printPermitsReceipts: a zero-fee receipt cannot be printed; the print is logged. The page draws the slip.</summary>
public async Task<ReceiptPrint> PrintAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if ((r.Fees ?? 0) == 0) throw new BusinessException(ReceiptErrors.ZeroFees, ReceiptMessages.ZeroFees);
if (!ReceiptRules.CanPrint(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsPrint, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.PrintLog();
await repository.AddLogAsync(id, "PRINT", old, @new, user.Id, ip, null, ct);
var description = r.ReceiptType == 8 ? "بدل تصريح ملغي" : string.IsNullOrEmpty(r.FmShipmentMode) ? "تصريح واحد" : "تصريح مزدوج";
var showCargo = r.ReceiptType is not (1 or 5);
return new ReceiptPrint(r, r.Credit == 0 ? "سند قبض" : "مطالبة مالية", description, showCargo, ShowGnpn: false);
}
// ---------------------------------------------------------------- helpers for the create form
public async Task<ReceiptAutoFill?> GnPermitAsync(string tn, CancellationToken ct) =>
string.IsNullOrWhiteSpace(tn) ? null : await repository.GetGnPermitAsync(tn.Trim(), ct);
public async Task<ReceiptAutoFill?> DriverAsync(string nnpn, CancellationToken ct) =>
string.IsNullOrWhiteSpace(nnpn) ? null : await repository.GetDriverAsync(nnpn.Trim(), ct);
// ---------------------------------------------------------------- Excel
public async Task<ExportFile> ExportAsync(ReceiptQuery query, CancellationToken ct)
{
await Require(PermissionKeys.ReceiptsReport, ct);
var rows = new List<ReceiptRow>();
for (var p = 1; rows.Count < ExportLimit; p++)
{
var r = await SearchAsync(query, new PageRequest(p, PageRequest.MaxPageSize), ct);
rows.AddRange(r.Items);
if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break;
}
string D(DateTime? d) => d?.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture) ?? string.Empty;
var cols = new List<ReportColumn>
{
new("counter", "متسلسل", "#"), new("receiptNo", "الرقم", "Receipt no."), new("pn", "رقم التصريح", "Permit"), new("company", "اسم الشركة", "Company"),
new("cargo", "النمط", "Cargo type"), new("tn", "رقم الشاحنة", "Truck"), new("trn", "رقم المقطورة", "Trailer"), new("drvr", "اسم السائق", "Driver"),
new("nnpn", "الرقم الوطني", "National no."), new("fees", "المبلغ", "Amount"), new("credit", "النوع", "Kind"), new("creationDate", "تاريخ الانشاء", "Created"),
new("createdBy", "إنشاء بواسطة", "Created by"), new("confirmationDate", "تاريخ التأكيد", "Confirmed"), new("confirmationBy", "تأكيد بواسطة", "Confirmed by"),
new("confirmationName", "اسم المؤكد", "Confirmed by (name)"), new("status", "الحالة", "Status"), new("source", "طريقة الدفع", "Payment"),
};
var data = rows.Select((r, i) => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
{
["counter"] = i + 1, ["receiptNo"] = r.ReceiptNo, ["pn"] = r.Pn, ["company"] = r.CompanyName, ["cargo"] = r.CargoType, ["tn"] = r.Tn, ["trn"] = r.Trn, ["drvr"] = r.Drvr,
["nnpn"] = r.Nnpn, ["fees"] = r.Fees, ["credit"] = r.Credit == 0 ? "سند قبض" : "مطالبة مالية", ["creationDate"] = D(r.CreationDate), ["createdBy"] = r.CreatedBy,
["confirmationDate"] = D(r.ConfirmationDate), ["confirmationBy"] = r.ConfirmationBy == "0" ? "" : r.ConfirmationBy, ["confirmationName"] = r.ConfirmationName,
["status"] = ReceiptRules.StatusCaption(r.StatusCode), ["source"] = r.CreationSource == 0 ? "نقداً" : "دفع الالكتروني",
}).ToList();
var table = new ReportTable { Key = "PERMITSRECEIPTS", TitleAr = "تقرير الوصولات", TitleEn = "Receipts report", Columns = cols, Rows = data };
return new ExportFile(excel.Build(table, user.UserId, DateTime.Now, true), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "PERMITSRECEIPTS.xlsx");
}
// ---------------------------------------------------------------- audit
/// <summary>
/// permitsReceiptsAudit: compares the receipts confirmed by a user / in a period with the permits Excel file; the receipts that match move to AUDITED
/// (TENDER_SUP, SU, SAP) or COMPLETED (AM, the financial audit). Every compared receipt gets an audit log row; the result is an Excel file.
/// </summary>
public async Task<AuditResult> AuditAsync(Stream file, string originalName, AuditFilter filter, string? ip, CancellationToken ct)
{
await Require(PermissionKeys.ReceiptsAudit, ct);
string[] statuses; string next, action;
if (user.IsInAnyRole("TENDER_SUP", "SU", "QUEUE_OP", "SAP")) { statuses = [ReceiptStatus.NotReceived, "ALL", ReceiptStatus.Received, ReceiptStatus.Audited, ReceiptStatus.Unpaid]; next = ReceiptStatus.Audited; action = "AUDIT"; }
else if (user.IsInRole("AM")) { statuses = [ReceiptStatus.Audited, ReceiptStatus.Completed]; next = ReceiptStatus.Completed; action = "FIN_AUDIT"; }
else throw NoAuthority();
var hasUser = !string.IsNullOrWhiteSpace(filter.ConfirmationBy);
if (!hasUser && filter.DateFrom is null && filter.DateTo is null) throw new BusinessException(ReceiptErrors.AuditInput, ReceiptMessages.AuditFilter);
if ((filter.DateFrom is null) != (filter.DateTo is null)) throw new BusinessException(ReceiptErrors.AuditInput, ReceiptMessages.AuditBothDates);
if (filter.DateFrom is { } f && filter.DateTo is { } t && f > t) throw new BusinessException(ReceiptErrors.AuditInput, ReceiptMessages.ConfirmationRange);
if (hasUser && !await repository.UserExistsAsync(filter.ConfirmationBy!.Trim(), ct)) throw new BusinessException(ReceiptErrors.UserNotFound, ReceiptMessages.UserNotFound);
var sheet = excel.ReadFirstSheet(file);
if (sheet.Count <= 3) throw new BusinessException(ReceiptErrors.AuditInput, ReceiptMessages.UploadFile);
string Cell(string[] r, int i) => i < r.Length ? (r[i] ?? string.Empty).Trim() : string.Empty;
// header on row 3 (legacy headerrow=3): SN, SCAC, COMPANY, NNPN, DRIVER, INBOUNDTYPECODE, SHIPMENTMODE, PERMIT_STATUS, PN, TN, TRN, ORIGINADDRESSID, DESTINATIONADDRESSID, ...
var permits = sheet.Skip(3).Select(r => new AuditFileRow
{
Scac = Cell(r, 1), Nnpn = Cell(r, 3), InboundTypeCode = Cell(r, 5), ShipmentMode = Cell(r, 6), PermitStatus = Cell(r, 7), Pn = Cell(r, 8), Tn = Cell(r, 9), Trn = Cell(r, 10),
OriginAddressId = Cell(r, 11), DestinationAddressId = Cell(r, 12), Crn = Cell(r, 14), CaCode = Cell(r, 15), IsEmployeeMistake = Cell(r, 18),
}).ToList();
var receipts = await repository.GetForAuditAsync(statuses, filter, ct);
if (receipts.Count == 0) throw new BusinessException(ReceiptErrors.NoReceipts, ReceiptMessages.NoReceiptsForUser);
var lookups = await repository.GetAuditLookupsAsync(ct);
var (lines, audited, identical) = ReceiptAudit.Compare(permits, receipts, lookups, filter.ConfirmationBy, ReceiptRules.StatusCaption);
if (audited.Count > 0)
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
foreach (var a in audited)
await repository.AddLogAsync(a.Id, action, "{}", ReceiptRules.AuditResultJson(a.Result, a.Remarks), user.Id, ip, originalName, c);
if (identical.Count > 0) await repository.SetStatusAsync(identical, next, c);
return true;
}, ct);
var cols = new List<ReportColumn>
{
new("pn", "رقم التصريح", "Permit"), new("permitStatus", "حالة التصريح", "Permit status"), new("receiptNo", "رقم الوصل", "Receipt"), new("fees", "المبلغ", "Amount"),
new("receiptStatus", "حالة الوصل", "Receipt status"), new("date", "تاريخ الوصل", "Receipt date"), new("result", "النتيجة", "Result"), new("remark", "الملاحظات", "Remarks"),
};
var rows = lines.Skip(1).Select(l => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
{
["pn"] = l.Pn, ["permitStatus"] = l.PermitStatus, ["receiptNo"] = l.ReceiptNo, ["fees"] = l.Fees, ["receiptStatus"] = l.ReceiptStatus, ["date"] = l.ConfirmationDate,
["result"] = l.Result, ["remark"] = l.Remark,
}).ToList();
var table = new ReportTable { Key = "PERMITSAUDIT", TitleAr = "نتيجة تدقيق الوصولات", TitleEn = "Receipts audit result", Columns = cols, Rows = rows };
var name = Path.GetFileNameWithoutExtension(originalName) + "_result.xlsx";
return new AuditResult(excel.Build(table, user.UserId, DateTime.Now, true), name, receipts.Count, identical.Count);
}
// ------------------------------------------------------------------------------------------------------------------------------------
private async Task<ReceiptRow> Load(long id, CancellationToken ct) =>
await repository.GetAsync(id, ct) ?? throw new NotFoundException("Receipt", id);
private async Task Require(string key, CancellationToken ct)
{
if (!await permissions.IsAllowedAsync(key, ct)) throw NoAuthority();
}
private async Task<ReceiptActions> ActionsAsync(ReceiptRow r, CancellationToken ct)
{
var asksOnly = user.IsInAnyRole("SU", "QUEUE_OP");
var revoke = false;
if (ReceiptRules.CanRevokeOpen(r.StatusCode))
revoke = await permissions.IsAllowedAsync(asksOnly ? PermissionKeys.ReceiptsRevokeRequest : PermissionKeys.ReceiptsRevoke, ct)
&& !(ReceiptRules.IsStatus(r.StatusCode, ReceiptStatus.Received) && r.RequestId is not null); // legacy hides cancel for a receipt made by a permit request
else if (ReceiptRules.CanRevokeAudited(r.StatusCode) && !asksOnly)
revoke = await permissions.IsAllowedAsync(PermissionKeys.ReceiptsRevokeAudited, ct);
return new ReceiptActions(
Update: ReceiptRules.CanUpdate(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsUpdate, ct),
Confirm: ReceiptRules.CanConfirm(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsConfirm, ct),
Paid: ReceiptRules.CanPay(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsPaid, ct),
Print: ReceiptRules.CanPrint(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsPrint, ct),
Revoke: revoke,
AcceptRevoke: ReceiptRules.CanDecideRevoke(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsAcceptRevoke, ct),
RejectRevoke: ReceiptRules.CanDecideRevoke(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsRejectRevoke, ct));
}
private static string? RegistrarClean(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim();
private static ForbiddenException NoAuthority() => new(ReceiptErrors.NoAuthority, ReceiptMessages.NoAuthority);
}