NTP_V2/src/NTP.Application/Grains/Orders/OrderReportService.cs

185 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using NTP.Application.Abstractions;
using NTP.Application.Common;
using NTP.Domain.Grains.Orders;
namespace NTP.Application.Grains.Orders;
public interface IOrderReportService
{
Task<TenderOrderReportDto> GetTenderOrderReportAsync(DateTime orderDate, CancellationToken ct);
Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct);
Task<FinancialBillingPage> GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct);
/// <summary>The legacy FinancialBilling.cfm Excel (an HTML table opened by Excel), byte for byte the same layout.</summary>
Task<ExportFile> ExportFinancialBillingAsync(long scac, long invoiceNumber, CancellationToken ct);
Task<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct);
}
/// <summary>
/// Grains reports: tenderOrderReport_xls.cfm and FinancialBilling.cfm / FinancialRpts.cfm as JSON grids plus CSV/XLSX
/// exports (the legacy PDF variant FinancialBilling_pdf.cfm is not ported).
/// </summary>
public sealed class OrderReportService(IOrderReportRepository repository, ICurrentUser user) : IOrderReportService
{
private bool Ar => !string.Equals(user.Lang, "EN", StringComparison.OrdinalIgnoreCase);
private string L(string ar, string en) => Ar ? ar : en;
private static string Date(object? v) => v switch
{
null => string.Empty,
DateTime d => d.ToString("dd/MM/yyyy"),
_ => v.ToString() ?? string.Empty
};
// ------------------------------------------------------------------ tender order report
public async Task<TenderOrderReportDto> GetTenderOrderReportAsync(DateTime orderDate, CancellationToken ct)
{
// Access is decided by the permission grains.orders.reportOrders on the controller (the legacy hard-coded role block was removed).
var day = orderDate.Date;
var byType = await repository.GetTenderTypeTotalsAsync(day, ct);
var byDest = await repository.GetTenderDestinationTotalsAsync(day, ct);
var typeTotal = byType.Sum(x => x.Quantity);
var typeRows = byType.Select(x => new TenderTypeSummaryDto(
TenderOrderRules.NormalizeType(x.Type), x.Quantity, ReportMath.Percent2(x.Quantity, typeTotal))).ToList();
// PIVOT(sum(quant) FOR type IN ('COMP' AS company, 'AHALE' AS ahale)): other types are not part of this table.
var destRows = byDest
.Where(x => x.Type is TenderOrderType.Company or TenderOrderType.Individuals)
.GroupBy(x => x.Destination ?? string.Empty)
.OrderBy(g => g.Key, StringComparer.Ordinal)
.Select(g =>
{
var ahale = g.Where(x => x.Type == TenderOrderType.Individuals).Sum(x => x.Quantity);
var comp = g.Where(x => x.Type == TenderOrderType.Company).Sum(x => x.Quantity);
var all = ahale + comp;
return new TenderDestinationSummaryDto(
g.Key, ahale, ReportMath.Percent1(ahale, all), comp, ReportMath.Percent1(comp, all), all);
}).ToList();
return new TenderOrderReportDto(
day.ToString("yyyy-MM-dd"), typeRows, typeTotal, destRows,
destRows.Sum(x => x.Individuals), destRows.Sum(x => x.Companies));
}
public async Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct)
{
var r = await GetTenderOrderReportAsync(orderDate, ct);
string TypeLabel(string? t) => t switch
{
TenderOrderType.Individuals => L("افراد", "Individuals"),
TenderOrderType.Company => L("شركات", "Companies"),
_ => string.Empty
};
var title = new[] { L("شركة نافذ للخدمات اللوجستية", "Nafith Logistics Services"), L("نسب التوزيع في طلبيات السائب", "Distribution ratios of bulk orders"), $"{L("تاريخ الطلبية", "Order date")}: {r.OrderDate}" };
var t1 = new ExportTable(title,
[L("افراد \\ شركات", "Individuals / Companies"), L("العدد", "Count"), L("النسبة", "Ratio")],
r.ByType.Select(x => (IReadOnlyList<object?>)new object?[] { TypeLabel(x.Type), x.Quantity, x.Percent }).ToList(),
[L("المجموع", "Total"), r.TypeTotal, "100%"]);
var t2 = new ExportTable([],
[L("الوجهة", "Destination"), L("عدد الافراد", "Individuals"), L("نسبة الافراد", "Individuals %"),
L("عدد الشركات", "Companies"), L("نسبة الشركات", "Companies %"), L("المجموع", "Total")],
r.ByDestination.Select(x => (IReadOnlyList<object?>)new object?[]
{ x.Destination, x.Individuals, x.IndividualsPercent + "%", x.Companies, x.CompaniesPercent + "%", x.Total }).ToList(),
[L("المجموع", "Total"), r.TotalIndividuals, null, r.TotalCompanies, null, r.TotalIndividuals + r.TotalCompanies]);
return Build([t1, t2], format, $"ordersReport_{r.OrderDate}");
}
// ------------------------------------------------------------------ financial billing
private static FinancialBillingDto Map(FinancialBillingRow x) => new(
x.Id, x.CargoType, x.CompanyName, x.Pn, x.Tn, Date(x.LoadDate), x.Name, Date(x.DischargeDate),
x.Lnw, x.Dnw, x.Dnw - x.Lnw, x.Price, x.FinePrice, x.SerialNo, x.Origin, x.LoseFine, x.DemurrageFine,
x.OtherFine, x.FinalCost, x.InvoiceNumber, x.Scac);
private static FinancialBillingTotals Totals(IEnumerable<FinancialBillingRow> rows)
{
decimal lnw = 0, dnw = 0, lose = 0, dem = 0, other = 0, final = 0;
foreach (var x in rows)
{
lnw += x.Lnw; dnw += x.Dnw; lose += x.LoseFine; dem += x.DemurrageFine; other += x.OtherFine; final += x.FinalCost;
}
return new FinancialBillingTotals(lnw, dnw, lose, dem, other, final);
}
public async Task<FinancialBillingPage> GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct)
{
var paged = await repository.GetFinancialBillingPageAsync(scac, invoiceNumber, page, ct);
// Totals cover the whole invoice (legacy totalled every row), not just the current page.
var all = await repository.GetFinancialBillingAsync(scac, invoiceNumber, ct);
return new FinancialBillingPage(paged.Items.Select(Map).ToList(), paged.Page, paged.PageSize, paged.TotalCount, Totals(all));
}
public async Task<ExportFile> ExportFinancialBillingAsync(long scac, long invoiceNumber, CancellationToken ct)
{
var rows = await repository.GetFinancialBillingAsync(scac, invoiceNumber, ct);
var first = rows.FirstOrDefault();
var totals = Totals(rows);
static string E(object? v) => System.Net.WebUtility.HtmlEncode(Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty);
var h = new System.Text.StringBuilder();
h.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
h.Append("<style>.header{font-weight:bold;font-size:28px;}");
h.Append(".sub_header{font-weight:bold;font-size:14px;text-align:right;width:80px;background-color:#034878;color:#FFFFFF;text-align:center;}");
h.Append(".footer{background-color:#034878;color:#FFFFFF;font-weight:bold;}</style>");
h.Append("<table border=\"2\" bordercolor=\"#034878\"><tr><td><table align=\"center\" dir=\"rtl\" border=\"1\">");
h.Append("<tr align=\"center\" dir=\"rtl\"><td colspan=\"18\" align=\"center\" class=\"header\">شركة نافذ للخدمات اللوجستية</td></tr>");
h.Append("<tr align=\"center\" dir=\"rtl\"><td colspan=\"18\" align=\"center\" class=\"header\">قائمة بنماذج المعدة لصرف أجور النقل حسب رقم المطالبة</td></tr>");
h.Append("<tr dir=\"rtl\">");
h.Append($"<td colspan=\"6\" class=\"sub_header\">إسم الشركة : {E(first?.CompanyName)} </td>");
h.Append($"<td colspan=\"4\" class=\"sub_header\">رقم المطالبة : {E(first?.InvoiceNumber)}</td>");
h.Append($"<td colspan=\"3\" class=\"sub_header\">رقم العطاء : {GrainsOrderConstants.BillingTenderNumber}</td>");
h.Append($"<td colspan=\"3\" class=\"sub_header\">التاريخ : {E(Date(first?.LoadDate))}</td>");
h.Append("<td colspan=\"2\" class=\"sub_header\"></td></tr>");
h.Append("<tr align=\"center\" dir=\"rtl\">");
foreach (var c in new[] { "التسلسل", " رقم الارسالية", " رقم المستند", "تاريخ التحميل", "من", "الى", "نوع المادة", "رقم السيارة", "الوزن المرسل", "تاريخ التفريغ", "الوزن المستلم", "الفرق ", "السعر", "سعر التغريم", "غرامة النقص ", "غرامة التاخير", "غرامات آخرى", "القيمة النهائية" })
h.Append($"<td class=\"sub_header\">{c}</td>");
h.Append("</tr>");
decimal priceTotal = 0, finePriceTotal = 0;
var n = 0;
foreach (var x in rows)
{
n++;
priceTotal += x.Price; finePriceTotal += x.FinePrice;
h.Append("<tr align=\"center\" dir=\"rtl\">");
foreach (var v in new object?[] { n, x.Pn, x.SerialNo, Date(x.LoadDate), "عقبة", x.Name, x.CargoType, x.Tn, x.Lnw, Date(x.DischargeDate), x.Dnw, x.Dnw - x.Lnw, x.Price, x.FinePrice, x.LoseFine, x.DemurrageFine, x.OtherFine, x.FinalCost })
h.Append($"<td>{E(v)}</td>");
h.Append("</tr>");
}
if (rows.Count != 0)
{
h.Append("<tr align=\"center\" dir=\"rtl\">");
foreach (var v in new object?[] { "المجموع", null, null, null, null, null, null, null, totals.Lnw, null, totals.Dnw, null, null, null, totals.LoseFine, totals.DemurrageFine, totals.OtherFine, totals.FinalCost })
h.Append($"<td class=\"footer\">{E(v)}</td>");
h.Append("</tr>");
}
else h.Append("<tr><td colspan=\"18\">لايوجد معلومات</td></tr>");
h.Append("<tr>");
h.Append($"<td colspan=\"5\">بتاريخ : {DateTime.Now:dd/MM/yyyy HH:mm}</td>");
h.Append("<td colspan=\"5\">جميع الحقوق محفوظة لشركة نافذ للخدمات اللوجستية</td>");
h.Append($"<td colspan=\"3\">عدد النتائج : {rows.Count}</td>");
h.Append($"<td colspan=\"5\" align=\"left\">طبع التقرير بواسطة : {E(user.UserId)}</td>");
h.Append("</tr></table></td></tr></table></body></html>");
var bytes = new System.Text.UTF8Encoding(true).GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(h.ToString())).ToArray();
return new ExportFile(bytes, "application/vnd.ms-excel", "FinancialReport.xls");
}
public Task<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct) =>
repository.GetInvoiceNumbersAsync(scac, ct);
// ------------------------------------------------------------------ helpers
private ExportFile Build(IReadOnlyList<ExportTable> tables, string format, string baseName)
{
var safe = new string(baseName.Where(c => char.IsLetterOrDigit(c) || c is '_' or '-').ToArray());
return string.Equals(format, "xlsx", StringComparison.OrdinalIgnoreCase)
? new ExportFile(TabularExport.ToXlsx(tables, Ar), TabularExport.XlsxContentType, safe + ".xlsx")
: new ExportFile(TabularExport.ToCsv(tables), TabularExport.CsvContentType, safe + ".csv");
}
}