using NTP.Application.Abstractions; using NTP.Application.Common; namespace NTP.Application.Grains.Reports; /// Reports, dashboards and Excel exports of the Grains module (legacy reports.cfc + Reports\*.cfm + *.cfr). public sealed class ReportsService(IReportsRepository repo, IReportExcelService excel, ICurrentUser user) : IReportsService { private ReportScope Scope() => new(user.UserId, user.RoleCode, user.LocationId, user.StkId, long.TryParse(user.CompanyCode, out var c) ? c : null); public Task> CompaniesAsync(CancellationToken ct) => repo.CompaniesAsync(ct); public Task> CargoTypesAsync(CancellationToken ct) => repo.CargoTypesAsync(ct); /// ownersTurn.cfm lists: BULK => gn_type in (BULK, BULK_GALLAB), anything else => PCKD (EX locations, status 1). public Task> DestinationsAsync(string? shipmentMode, CancellationToken ct) => repo.DestinationsAsync(string.Equals(shipmentMode, "BULK", StringComparison.OrdinalIgnoreCase) ? ["BULK", "BULK_GALLAB"] : ["PCKD"], ct); private static void CheckRange(DateOnly from, DateOnly to) { if (to < from) throw new BusinessException("REPORT_RANGE_INVALID", "تاريخ النهاية يجب أن يكون بعد تاريخ البداية"); } public async Task NumOfTripsAndTrucksAsync(DateOnly from, DateOnly to, CancellationToken ct) { CheckRange(from, to); return TripsReportMath.NumOfTrips(from, to, await repo.TripsPerCompanyAsync(from, to, ct)); } public async Task QuotaAsync(DateOnly from, DateOnly to, CancellationToken ct) { CheckRange(from, to); return TripsReportMath.Quota(from, to, await repo.TripsPerCompanyAsync(from, to, ct)); } public async Task FrequencyAsync(DateOnly from, DateOnly to, string? scac, string? cargoType, CancellationToken ct) { CheckRange(from, to); scac = Zero(scac); cargoType = Zero(cargoType); return TripsReportMath.Frequency(from, to, await repo.FrequencyAsync(from, to, scac, cargoType, ct)); } /// Legacy: empty or "0" means "no filter". private static string? Zero(string? v) => string.IsNullOrWhiteSpace(v) || v.Trim() == "0" ? null : v.Trim(); public async Task DetailsAsync(DateOnly from, DateOnly to, CancellationToken ct) { CheckRange(from, to); return TripsReportMath.Details(from, to, await repo.DetailsAsync(from, to, ct)); } public async Task MotMultiTripsAsync(CancellationToken ct) => MotMultiTripsBuilder.Build(await repo.MotMultiTripsAsync(ct)); // ------------------------------------------------------------------ table reports private static ReportColumn C(string key, string ar, string en, string kind = "text") => new(key, ar, en, kind); private static string Fmt(DateOnly? d) => d?.ToString("yyyy/MM/dd") ?? ""; public async Task BuildTableAsync(string key, ReportFilter f, CancellationToken ct) { key = (key ?? "").ToLowerInvariant(); if (!ReportKeys.All.Contains(key)) throw new NotFoundException("Report", key); if (key == ReportKeys.WeighbridgeEvents) return await WeighbridgeEventsAsync(f, ct); if (key == ReportKeys.Incapability) Validate(f); if (key is ReportKeys.ClosedPermits or ReportKeys.LoadingWeights or ReportKeys.Incapability or ReportKeys.WaybridgeSummary or ReportKeys.WaybridgeDetails or ReportKeys.MotGrainCube or ReportKeys.MotGrainFrequency) { if (f.From is null || f.To is null) throw new BusinessException("REPORT_DATES_REQUIRED", "يرجى تحديد الفترة (من - إلى)"); CheckRange(f.From.Value, f.To.Value); } if ((key is ReportKeys.DistributionSummary or ReportKeys.OrderDistribution) && f.OrderDate is null) throw new BusinessException("REPORT_ORDERDATE_REQUIRED", "يرجى تحديد تاريخ الطلبية"); if (key == ReportKeys.OwnersTurn && f.DestAddressId is null) throw new BusinessException("REPORT_DEST_REQUIRED", "يرجى تحديد الوجهة"); var raw = await repo.TableAsync(key, f, Scope(), ct); return Shape(key, f, raw); } /// GRINS_INCAPABILITY: the legacy page refuses a "to" date after yesterday. private static void Validate(ReportFilter f) { var yesterday = DateOnly.FromDateTime(DateTime.Today.AddDays(-1)); if (f.To is { } to && to > yesterday) throw new BusinessException("REPORT_DATE_AFTER_YESTERDAY", "التاريخ لا يجوز ان يتجاوز " + yesterday.ToString("yyyy/MM/dd")); } private static object? Get(IDictionary r, string key) { foreach (var kv in r) if (string.Equals(kv.Key, key, StringComparison.OrdinalIgnoreCase)) return kv.Value is DBNull ? null : kv.Value; return null; } private static IReadOnlyList> Project(IReadOnlyList> raw, IReadOnlyList cols) => raw.Select(r => (IReadOnlyDictionary)cols.ToDictionary(c => c.Key, c => Get(r, c.Key))).ToList(); private ReportTable Shape(string key, ReportFilter f, IReadOnlyList> raw) { var period = new List(); if (f.From is not null) period.Add($"من: {Fmt(f.From)} إلى: {Fmt(f.To)}"); switch (key) { case ReportKeys.ClosedPermits: return Make(key, "الارساليات المكتملة", "Completed permits", period, raw, [ C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم القاطرة", "Truck no."), C("company", "الشركة", "Company"), C("cargoType", "نوع المادة", "Cargo"), C("origin", "موقع التحميل", "Loading site"), C("destination", "موقع التفريغ", "Discharge site"), C("drvr", "اسم السائق", "Driver"), C("nnpn", "الرقم الوطني", "National no."), C("closeDate", "تاريخ الإغلاق", "Closed on", "datetime") ]); case ReportKeys.LoadingWeights: return Make(key, "تقرير أوزان التحميل", "Loading weights", period, raw, [ C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم القاطرة", "Truck no."), C("company", "الشركة", "Company"), C("cargoType", "نوع المادة", "Cargo"), C("origin", "موقع التحميل", "Loading site"), C("destination", "موقع التفريغ", "Discharge site"), C("tare", "وزن الفارغ", "Tare", "number"), C("gross", "وزن القائم", "Gross", "number"), C("net", "الصافي", "Net", "number"), C("eventDate", "تاريخ التحميل", "Loaded on", "datetime") ]); case ReportKeys.Incapability: return Incapability(period, raw); case ReportKeys.WaybridgeSummary: return Make(key, "تقرير إجمالي حركات القبان", "Weighbridge totals", [.. period, EventLine(f.EventType)], raw, [ C("company", "الشركة", "Company"), C("cargoType", "نوع المادة", "Cargo"), C("trips", "عدد الحركات", "Movements", "number"), C("totalWeight", "إجمالي الوزن", "Total weight", "number") ]); case ReportKeys.WaybridgeDetails: return Make(key, "تقرير تفصيلي لحركات القبان", "Weighbridge details", [.. period, EventLine(f.EventType)], raw, [ C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم القاطرة", "Truck no."), C("company", "الشركة", "Company"), C("cargoType", "نوع المادة", "Cargo"), C("eventType", "نوع الحركة", "Event"), C("location", "الموقع", "Site"), C("weight", "الوزن", "Weight", "number"), C("eventDate", "تاريخ الحركة", "Event date", "datetime"), C("doneBy", "المستخدم", "User") ]); case ReportKeys.TenderOrder: return Make(key, "ارسالية عطاء التموين", "Tender order permits", TenderFilterLines(f), raw, [ C("phoneAccpt", "موافق : 1 | غير موافق : 0", "Phone approval"), C("statusCaption", "الحالة", "Status"), C("destName", "الوجهة", "Destination"), C("remarks", "موقع التحميل", "Loading site"), C("tn", "رقم القاطرة", "Truck no."), C("type", "نوع الحمولة", "Load type"), C("drvr", "اسم السائق", "Driver"), C("creationDate", "تاريخ الإرسالية", "Permit date", "datetime"), C("phoneNumber", "رقم هاتف الشركة", "Company phone"), C("compName", "اسم الشركة", "Company"), C("queueNo", "رقم الدور", "Queue no."), C("pn", "رقم الأرسالية", "Permit no.") ], rowFix: r => { if (r["phoneAccpt"] is null or "") r["phoneAccpt"] = "لم يتم الاتصال بعد"; }); case ReportKeys.DistributionSummary: return Make(key, "ملخص التوزيع", "Distribution summary", [$"تاريخ الطلبية : {Fmt(f.OrderDate)}"], raw, [ C("name", "الشركة", "Company"), C("cnt", "العدد", "Count", "number"), C("shift", "الشفت", "Shift"), C("orderDate", "تاريخ الطلبية", "Order date") ]); case ReportKeys.CallList: return CallList(raw); case ReportKeys.CompaniesTurn: return Make(key, "تقرير دور الشركات", "Companies turn", [$"نوع المادة: {f.ShipmentMode} نوع التوزيع: {f.DistributionType}"], raw, [ C("turn", "الدور", "Turn", "number"), C("scac", "رقم الشركة", "Company code"), C("company", "اسم الشركة", "Company"), C("code", "نوع المادة", "Cargo"), C("type", "نوع التوزيع", "Distribution"), C("counter", "العداد", "Counter", "number") ]); case ReportKeys.OwnersTurn: return Make(key, "تقرير دور الأفراد", "Individuals turn", [$"نوع المادة: {f.ShipmentMode} الوجهة: {f.DestAddressId}"], raw, [ C("turn", "الدور", "Turn", "number"), C("tn", "رقم القاطرة", "Truck no."), C("trips", "عدد الرحلات", "Trips", "number"), C("lastTrip", "آخر رحلة", "Last trip", "datetime") ]); case ReportKeys.Drivers: return Make(key, "تقرير السائقين المسجلين", "Registered drivers", [], raw, [ C("nnpn", "الرقم الوطني", "National no."), C("name", "الاسم", "Name"), C("dln", "رقم الرخصة", "Licence no."), C("dled", "انتهاء الرخصة", "Licence expiry"), C("company", "الشركة", "Company"), C("status", "الحالة", "Status"), C("createDate", "تاريخ التسجيل", "Registered on"), C("createUser", "المستخدم", "User") ]); case ReportKeys.Trucks: return Make(key, "تقرير القاطرات المسجلة", "Registered trucks", [], raw, [ C("tn", "رقم القاطرة", "Truck no."), C("chasesNumber", "رقم الشاصي", "Chassis no."), C("company", "الشركة", "Company"), C("status", "الحالة", "Status"), C("regDate", "تاريخ التسجيل", "Reg. date"), C("createDate", "تاريخ الإنشاء", "Created on"), C("createUser", "المستخدم", "User") ]); case ReportKeys.OrderDistribution: return OrderDistribution(f, raw); case ReportKeys.MotGrainCube: return Make(key, "مكعب الحبوب (وزارة النقل)", "Grain cube (MOT)", period, raw, [ C("loc", "الوجهة", "Destination"), C("company", "الشركة", "Company"), C("trucks", "الشاحنات", "Trucks", "number"), C("cTrucks", "شاحنات الشركات", "Company trucks", "number"), C("trails", "المقطورات", "Trailers", "number"), C("cTrails", "مقطورات الشركات", "Company trailers", "number"), C("trips", "الرحلات", "Trips", "number"), C("cTrips", "رحلات الشركات", "Company trips", "number") ]); case ReportKeys.MotGrainFrequency: return Make(key, "تكرار رحلات الحبوب (وزارة النقل)", "Grain trip frequency (MOT)", period, raw, [ C("c", "عدد الرحلات", "Trips", "number"), C("contCnt", "أفراد - عدد", "Individuals - count", "number"), C("contPerc", "أفراد %", "Individuals %", "number"), C("compCnt", "شركات - عدد", "Companies - count", "number"), C("compPerc", "شركات %", "Companies %", "number") ]); default: throw new NotFoundException("Report", key); } } private static string EventLine(string? t) => "نوع الحركة: " + t switch { "LTW" => "قبان دخول موقع التحميل", "LGW" => "قبان خروج موقع التحميل", "DTW" => "قبان دخول موقع التفريغ", "DGW" => "قبان خروج موقع التفريغ", _ => "الكل" }; private static List TenderFilterLines(ReportFilter f) { var l = new List(); if (!string.IsNullOrEmpty(f.ShipmentStatusCode)) l.Add($"الحالة: {f.ShipmentStatusCode}"); if (f.OrderDate is not null) l.Add($"تاريخ الطلبية: {Fmt(f.OrderDate)}"); if (f.DestAddressId is not null) l.Add($"الوجهة: {f.DestAddressId}"); if (!string.IsNullOrEmpty(f.Tn)) l.Add($"رقم القاطرة: {f.Tn}"); if (!string.IsNullOrEmpty(f.Scac)) l.Add($"رقم الشركة: {f.Scac}"); return l; } private static ReportTable Make(string key, string ar, string en, IReadOnlyList lines, IReadOnlyList> raw, ReportColumn[] cols, Action>? rowFix = null) { var rows = Project(raw, cols); if (rowFix is not null) rows = rows.Select(r => { var d = r.ToDictionary(k => k.Key, k => k.Value); rowFix(d); return (IReadOnlyDictionary)d; }).ToList(); return new ReportTable { Key = key, TitleAr = ar, TitleEn = en, Columns = cols, Rows = rows, FilterLines = lines }; } private static decimal Num(object? v) => v is null ? 0m : Convert.ToDecimal(v, System.Globalization.CultureInfo.InvariantCulture); /// GRINS_INCAPABILITY (shortage = loaded net - discharged net). Net falls back to gross - tare like the weighbridge report. private static ReportTable Incapability(IReadOnlyList period, IReadOnlyList> raw) { ReportColumn[] cols = [ C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم القاطرة", "Truck no."), C("company", "الشركة", "Company"), C("cargoType", "نوع المادة", "Cargo"), C("destination", "موقع التفريغ", "Discharge site"), C("loadNet", "صافي التحميل", "Loaded net", "number"), C("dischargeNet", "صافي التفريغ", "Discharged net", "number"), C("shortage", "العجز", "Shortage", "number"), C("orderDate", "تاريخ الطلبية", "Order date", "date") ]; var rows = new List>(); foreach (var r in raw) { var lnw = Num(Get(r, "lnw")); if (lnw == 0) lnw = Num(Get(r, "lgw")) - Num(Get(r, "ltw")); var dnw = Num(Get(r, "dnw")); if (dnw == 0) dnw = Num(Get(r, "dgw")) - Num(Get(r, "dtw")); lnw = Math.Abs(lnw); dnw = Math.Abs(dnw); rows.Add(new Dictionary { ["pn"] = Get(r, "pn"), ["tn"] = Get(r, "tn"), ["company"] = Get(r, "company"), ["cargoType"] = Get(r, "cargoType"), ["destination"] = Get(r, "destination"), ["loadNet"] = lnw, ["dischargeNet"] = dnw, ["shortage"] = lnw - dnw, ["orderDate"] = Get(r, "orderDate") }); } rows = rows.OrderByDescending(x => Num(x["shortage"])).ToList(); return new ReportTable { Key = ReportKeys.Incapability, TitleAr = "تقرير العجز", TitleEn = "Shortage report", Columns = cols, Rows = rows, FilterLines = period, Extra = new Dictionary { ["totalShortage"] = rows.Sum(x => Num(x["shortage"])) } }; } /// callRpt.cfm: IVR call list (Name, Phone, Code1.. sound-file names). "DayNight" derives from MOBILE_SHIFT. private static ReportTable CallList(IReadOnlyList> raw) { ReportColumn[] cols = [ C("name", "Name", "Name"), C("phone", "Phone", "Phone"), C("code1", "Code1", "Code1"), C("code2", "Code2", "Code2"), C("number1", "Number1", "Number1"), C("number2", "Number2", "Number2"), C("number3", "Number3", "Number3"), C("number4", "Number4", "Number4"), C("number5", "Number5", "Number5"), C("item", "Item", "Item"), C("fromDist", "From", "From"), C("origin", "Origin", "Origin"), C("week", "Week", "Week"), C("day", "Day", "Day"), C("month", "Month", "Month"), C("dayNight", "DayNight", "DayNight"), C("id", "ID", "ID") ]; var projected = Project(raw, cols); var rows = new List>(); for (var i = 0; i < projected.Count; i++) { var d = projected[i].ToDictionary(k => k.Key, k => k.Value); d["dayNight"] = Get(raw[i], "mobileShift")?.ToString() switch { "1" => @"c:\\D.wav", "2" => @"c:\\E.wav", "3" => @"c:\\N.wav", _ => "" }; rows.Add(d); } return new ReportTable { Key = ReportKeys.CallList, TitleAr = "قائمة الاتصال", TitleEn = "Call list", Columns = cols, Rows = rows }; } /// grainsOrder.cfm: first block = individuals vs companies totals, second = per destination with percentages. private static ReportTable OrderDistribution(ReportFilter f, IReadOnlyList> raw) { ReportColumn[] cols = [ C("dest", "الوجهة", "Destination"), C("ahale", "عدد الافراد", "Individuals", "number"), C("ahalePct", "نسبة الافراد", "Individuals %", "number"), C("company", "عدد الشركات", "Companies", "number"), C("companyPct", "نسبة الشركات", "Companies %", "number"), C("total", "المجموع", "Total", "number") ]; var rows = new List>(); foreach (var r in raw) { var a = Num(Get(r, "ahale")); var c = Num(Get(r, "company")); var all = a + c; rows.Add(new Dictionary { ["dest"] = Get(r, "dest"), ["ahale"] = a, ["ahalePct"] = all == 0 ? 0m : Math.Round(a / all * 100m, 1), ["company"] = c, ["companyPct"] = all == 0 ? 0m : Math.Round(c / all * 100m, 1), ["total"] = all }); } var totA = rows.Sum(x => Num(x["ahale"])); var totC = rows.Sum(x => Num(x["company"])); var tot = totA + totC; return new ReportTable { Key = ReportKeys.OrderDistribution, TitleAr = "نسب التوزيع في طلبيات السائب", TitleEn = "Bulk order distribution", Columns = cols, Rows = rows, FilterLines = [$"تاريخ الطلبية : {Fmt(f.OrderDate)}"], Extra = new Dictionary { ["individuals"] = totA, ["companies"] = totC, ["total"] = tot, ["individualsPct"] = tot == 0 ? 0m : Math.Round(totA / tot * 100m, 2), ["companiesPct"] = tot == 0 ? 0m : Math.Round(totC / tot * 100m, 2) } }; } private async Task WeighbridgeEventsAsync(ReportFilter f, CancellationToken ct) { if (f.From is null || f.To is null) throw new BusinessException("REPORT_DATES_REQUIRED", "يرجى تحديد الفترة (من - إلى)"); CheckRange(f.From.Value, f.To.Value); // Legacy: role GNDSTV only sees the movements of its own location. long? loc = user.IsInRole("GNDSTV") ? (user.LocationId ?? -1) : null; var raw = await repo.WeighbridgeEventsAsync(f.From.Value, f.To.Value, loc, ct); var pivot = WeighbridgeEventMath.Pivot(raw); ReportColumn[] cols = [ C("serial", "الرقم التسلسلي", "#", "number"), C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم السيارة", "Truck no."), C("cargoType", "نوع المادة", "Cargo"), C("scac", "الشركة", "Company"), C("loc", "موقع التفريغ", "Discharge site"), C("ltw", "وزن الفارغ (تحميل)", "Load tare", "number"), C("lgw", "وزن القائم (تحميل)", "Load gross", "number"), C("lnw", "الصافي (تحميل)", "Load net", "number"), C("loadDate", "تاريخ التحميل", "Loaded on"), C("dtw", "وزن الفارغ (تفريغ)", "Discharge tare", "number"), C("dgw", "وزن القائم (تفريغ)", "Discharge gross", "number"), C("dnw", "الصافي (تفريغ)", "Discharge net", "number"), C("dischargeDate", "تاريخ التفريغ", "Discharged on"), C("netLoss", "صافي النقص", "Net loss", "number"), C("drvr", "اسم السائق", "Driver"), C("nnpn", "الرقم الوطني", "National no."), C("origin", "جهة التحميل", "Origin") ]; var rows = pivot.Select(p => (IReadOnlyDictionary)new Dictionary { ["serial"] = p.Serial, ["pn"] = p.Pn, ["tn"] = p.Tn, ["cargoType"] = p.CargoType, ["scac"] = p.Scac, ["loc"] = p.Loc, ["ltw"] = p.Ltw, ["lgw"] = p.Lgw, ["lnw"] = p.Lnw, ["loadDate"] = p.LoadDate, ["dtw"] = p.Dtw, ["dgw"] = p.Dgw, ["dnw"] = p.Dnw, ["dischargeDate"] = p.DischargeDate, ["netLoss"] = p.NetLoss, ["drvr"] = p.Drvr, ["nnpn"] = p.Nnpn, ["origin"] = p.Origin }).ToList(); return new ReportTable { Key = ReportKeys.WeighbridgeEvents, TitleAr = "تقارير حركات قبان التحميل والتفريغ", TitleEn = "Loading and discharge weighbridge movements", Columns = cols, Rows = rows, FilterLines = [$"تاريخ الحركات : من : {Fmt(f.From)} إلى : {Fmt(f.To)}"] }; } // ------------------------------------------------------------------ paging + export public async Task PageAsync(string key, ReportFilter filter, int page, int pageSize, CancellationToken ct) { var t = await BuildTableAsync(key, filter, ct); var req = new PageRequest(page, pageSize); var items = t.Rows.Skip(req.MinRow).Take(req.SafePageSize).ToList(); return new ReportPage(items, req.SafePage, req.SafePageSize, t.Rows.Count, t.Columns, t.Extra); } public async Task<(byte[] Content, string FileName)> ExportAsync(string key, ReportFilter filter, CancellationToken ct) { var t = await BuildTableAsync(key, filter, ct); var bytes = excel.Build(t, user.UserId, DateTime.Now, user.Lang != "EN"); return (bytes, $"{t.Key}-{DateTime.Now:yyyyMMdd-HHmm}.xlsx"); } }