Refinery wage claims: تقرير الملخص (one-row summary of a claim in the legacy Excel layout)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2cdb74f082
commit
ab0d26fbf5
|
|
@ -82,6 +82,15 @@ public sealed class WageClaimsController(IWageClaimService claims) : ControllerB
|
|||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
/// <summary>تقرير الملخص: one row of totals of the claim (legacy createCFRReport).</summary>
|
||||
[HttpGet("{id:long}/export-summary")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaimsReport)]
|
||||
public async Task<IActionResult> ExportSummary(long id, CancellationToken ct)
|
||||
{
|
||||
var f = await claims.ExportSummaryAsync(id, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string> Split(string? s) =>
|
||||
(s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,20 @@ public sealed record TransfersReport(
|
|||
IReadOnlyList<double> WidthsChars,
|
||||
IReadOnlyList<IReadOnlyList<object?>> Rows);
|
||||
|
||||
/// <summary>
|
||||
/// The legacy one-row summary of a wage claim (refinerytripsxls.cfr): company and title banner, a navy row with three facts (claim number,
|
||||
/// tender, month) merged over A:E, F:L and M:O, the column captions and one row of totals. <see cref="WidthsChars"/> are in characters.
|
||||
/// </summary>
|
||||
public sealed record SummaryReport(
|
||||
string CompanyName,
|
||||
string Title,
|
||||
string Left,
|
||||
string Middle,
|
||||
string Right,
|
||||
IReadOnlyList<string> Headers,
|
||||
IReadOnlyList<double> WidthsChars,
|
||||
IReadOnlyList<object?> Values);
|
||||
|
||||
/// <summary>
|
||||
/// Writes legacy-style reports as .xlsx workbooks (right-to-left sheet, Arial Unicode MS 11, centred and wrapped cells, navy #003366 header
|
||||
/// cells with white text, thin borders). Strings are written as inline strings, so cell text can never be evaluated as a formula.
|
||||
|
|
@ -52,6 +66,44 @@ public static class LegacyReportWorkbook
|
|||
|
||||
public static byte[] ToTransfersXlsx(TransfersReport r) => Package(r.Title, TransfersStyles(), TransfersSheet(r));
|
||||
|
||||
/// <summary>Same style sheet as the الحوالات list; layout read from a legacy output file (rows 1-2 banner height 30, rows 3-5 height 20).</summary>
|
||||
public static byte[] ToSummaryXlsx(SummaryReport r) => Package(r.Title, TransfersStyles(), SummarySheet(r));
|
||||
|
||||
private static string SummarySheet(SummaryReport r)
|
||||
{
|
||||
var cols = r.Headers.Count;
|
||||
var last = TabularExport.ColumnName(cols - 1);
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
|
||||
sb.Append("<sheetViews><sheetView rightToLeft=\"1\" workbookViewId=\"0\"/></sheetViews><sheetFormatPr defaultRowHeight=\"12.75\"/><cols>");
|
||||
for (var c = 0; c < cols; c++) Col(sb, c, c < r.WidthsChars.Count ? r.WidthsChars[c] : 20);
|
||||
sb.Append("</cols><sheetData>");
|
||||
void Banner(int row, string text)
|
||||
{
|
||||
sb.Append("<row r=\"").Append(row).Append("\" ht=\"30\" customHeight=\"1\">");
|
||||
Text(sb, 0, row, text, TBanner);
|
||||
for (var c = 1; c < cols; c++) Blank(sb, c, row, TBanner);
|
||||
sb.Append("</row>");
|
||||
}
|
||||
Banner(1, r.CompanyName);
|
||||
Banner(2, r.Title);
|
||||
sb.Append("<row r=\"3\" ht=\"20\" customHeight=\"1\">");
|
||||
for (var c = 0; c < cols; c++)
|
||||
{
|
||||
if (c == 0) Text(sb, c, 3, r.Left, TLabel);
|
||||
else if (c == 5) Text(sb, c, 3, r.Middle, TLabel);
|
||||
else if (c == 12) Text(sb, c, 3, r.Right, TLabel);
|
||||
else Blank(sb, c, 3, TLabel);
|
||||
}
|
||||
sb.Append("</row><row r=\"4\" ht=\"20\" customHeight=\"1\">");
|
||||
for (var c = 0; c < cols; c++) Text(sb, c, 4, r.Headers[c], THeader);
|
||||
sb.Append("</row><row r=\"5\" ht=\"20\" customHeight=\"1\">");
|
||||
for (var c = 0; c < cols && c < r.Values.Count; c++) Value(sb, c, 5, r.Values[c], TData);
|
||||
sb.Append("</row></sheetData><mergeCells count=\"5\"><mergeCell ref=\"A1:").Append(last).Append("1\"/><mergeCell ref=\"A2:").Append(last)
|
||||
.Append("2\"/><mergeCell ref=\"A3:E3\"/><mergeCell ref=\"F3:L3\"/><mergeCell ref=\"M3:").Append(last).Append("3\"/></mergeCells></worksheet>");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static byte[] Package(string title, string styles, string sheet)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@ public sealed class WageClaimReportRaw
|
|||
public decimal? ToleranceQuantity { get; set; }
|
||||
public decimal? PenaltyQuantity { get; set; }
|
||||
public decimal? TonPrice { get; set; }
|
||||
public decimal? TonWage { get; set; }
|
||||
public decimal? PenaltyAmount { get; set; }
|
||||
public decimal? DriverTip { get; set; }
|
||||
public decimal? PermitDispatch { get; set; }
|
||||
|
|
@ -82,6 +83,12 @@ public sealed class WageClaimReportRaw
|
|||
public decimal? NetWage { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The one-row summary of a claim (legacy تقرير الملخص, refinerytripsxls.cfr): totals over its trips, deductions shown positive.</summary>
|
||||
public sealed record WageClaimSummary(
|
||||
int TripCount, decimal LoadingWeight, decimal Water, decimal DischargeWeight, decimal Difference, decimal CalculatedTon, decimal QuantityWage,
|
||||
decimal PenaltyQuantity, decimal PenaltyAmount, decimal DriverTip, decimal PermitDispatch, decimal WaybillFee, decimal DieselAdvance,
|
||||
decimal Commission, decimal NetWage, string Tender);
|
||||
|
||||
/// <summary>Values of one report line after the legacy sign changes (deductions are shown negative).</summary>
|
||||
public sealed record WageClaimReportLine(
|
||||
string? Drvr, string? Tn, string? DischargeAuthoriztionNo, long? DischargeAuthoriztionYear, DateTime? DischargeEntryDate, string? ClientNo,
|
||||
|
|
|
|||
|
|
@ -91,6 +91,33 @@ public static class WageClaimRules
|
|||
advance > 0 ? -advance : advance, -V(r.Commission), V(r.NetWage));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// تقرير الملخص: totals over the trips. Quantity * ton wage is summed unrounded; the penalty quantity follows the same tolerance rule as the
|
||||
/// trip report; the tender label is the tender number (the form number without its 3-digit serial) of the highest form, with its year.
|
||||
/// </summary>
|
||||
public static WageClaimSummary ToSummary(IReadOnlyList<WageClaimReportRaw> trips)
|
||||
{
|
||||
decimal V(decimal? d) => d ?? 0m;
|
||||
var lines = trips.Select(ToReportLine).ToList();
|
||||
return new WageClaimSummary(
|
||||
trips.Count, trips.Sum(t => V(t.NetLoadingWeight)), trips.Sum(t => V(t.WaterAmount)), trips.Sum(t => V(t.NetDischargeWeight)),
|
||||
lines.Sum(l => l.WeightDifference), trips.Sum(t => V(t.CalculatedQuantityTon)), trips.Sum(t => V(t.CalculatedQuantityTon) * V(t.TonWage)),
|
||||
lines.Sum(l => l.PenaltyQuantity), trips.Sum(t => V(t.PenaltyAmount)), trips.Sum(t => V(t.DriverTip)), trips.Sum(t => V(t.PermitDispatch)),
|
||||
trips.Sum(t => V(t.WaybillFee)), trips.Sum(t => V(t.AdvancePaymentForDiesel)), trips.Sum(t => V(t.Commission)), trips.Sum(t => V(t.NetWage)),
|
||||
TenderLabel(trips));
|
||||
}
|
||||
|
||||
/// <summary>"27/2021": form numbers are tender number + 3-digit serial (26596 = tender 26); empty when the trips have no usable form number.</summary>
|
||||
public static string TenderLabel(IEnumerable<WageClaimReportRaw> trips)
|
||||
{
|
||||
var best = trips
|
||||
.Select(t => (No: long.TryParse(t.DischargeAuthoriztionNo, out var n) ? n : 0, t.DischargeAuthoriztionYear))
|
||||
.Where(x => x.No >= 1000)
|
||||
.OrderByDescending(x => x.No)
|
||||
.FirstOrDefault();
|
||||
return best.No == 0 ? "" : $"{best.No / 1000}/{best.DischargeAuthoriztionYear}";
|
||||
}
|
||||
|
||||
/// <summary>Caption of a claim status (REFINERY_WAGE_CLAIM.STATUS.* / REFINERY_COMMISSION_CLAIM.STATUS.*).</summary>
|
||||
public static string ClaimStatusCaption(string? code) => code switch
|
||||
{
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ using NTP.Application.Abstractions;
|
|||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
using NTP.Application.Refinery.Integrations;
|
||||
using NTP.Application.Refinery.Trips;
|
||||
|
||||
namespace NTP.Application.Refinery.WageClaims;
|
||||
|
||||
|
|
@ -26,6 +27,7 @@ public interface IWageClaimService
|
|||
Task<ClaimResult> ReopenAsync(long id, string? ip, CancellationToken ct);
|
||||
Task<ClaimResult> TransferAsync(long id, string? ip, CancellationToken ct);
|
||||
Task<ExportFile> ExportAsync(long id, CancellationToken ct);
|
||||
Task<ExportFile> ExportSummaryAsync(long id, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -151,6 +153,30 @@ public sealed class WageClaimService(IWageClaimRepository repo, IUnitOfWork unit
|
|||
return new ClaimResult(sent == trips.Count ? ClaimMessages.Success : $"تم ترحيل {sent} من {trips.Count} ارسالية", id);
|
||||
}
|
||||
|
||||
/// <summary>تقرير الملخص (createCFRReport): one row of totals over the trips of the claim, in the layout of the legacy Excel file.</summary>
|
||||
public async Task<ExportFile> ExportSummaryAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var claim = await GetAsync(id, ct);
|
||||
var s = WageClaimRules.ToSummary(await repo.ReportRowsAsync(id, ct));
|
||||
static object R(decimal v) => Math.Round(v, 3, MidpointRounding.AwayFromZero); // no floating point noise in the cells
|
||||
string[] headers =
|
||||
[
|
||||
"عدد الارساليات", "كمية البوليصة كغم", "كمية الماء كغم", "كمية المصفاة كغم", "الفروقات كغم", "الكمية المحسوبة طن", "الكمية* اجرة الطن",
|
||||
"كمية التغريم كغم", "خصم قيمة فرق الكمية المغرمة", "خصم إكرامية السائق", "خصم تسريب الصهاريج", "خصم اصدار وثيقة", "خصم قيمة لتر ديزل 350",
|
||||
"خصم عمولة الصرف التنافسية", "صافي القيمة",
|
||||
];
|
||||
object?[] values =
|
||||
[
|
||||
s.TripCount, R(s.LoadingWeight), R(s.Water), R(s.DischargeWeight), R(s.Difference), R(s.CalculatedTon), R(s.QuantityWage),
|
||||
R(s.PenaltyQuantity), R(s.PenaltyAmount), R(s.DriverTip), R(s.PermitDispatch), R(s.WaybillFee), R(s.DieselAdvance), R(s.Commission), R(s.NetWage),
|
||||
];
|
||||
double[] widths = [14.56, 19.56, 19.56, 19.56, 19.56, 19.56, 19.56, 19.56, 24.67, 24.67, 24.67, 24.67, 24.67, 24.67, 14.56];
|
||||
var report = new SummaryReport(
|
||||
"شركة نافذ للخدمات اللوجستية", "خلاصة قائمة نماذج التفريغ المعدة لصرف أجور النقل حسب رقم المطالبة",
|
||||
$"رقم المطالبة :{claim.WageClaimNo}", $"رقم العطاء:{s.Tender}", $"خلال شهر:{DateTime.Now:MM/yyyy}", headers, widths, values);
|
||||
return new ExportFile(LegacyReportWorkbook.ToSummaryXlsx(report), TabularExport.XlsxContentType, $"wage_claim_summary_{claim.WageClaimNo}.xlsx");
|
||||
}
|
||||
|
||||
/// <summary>factoryweb.report: the trips of the claim with the amounts, deductions shown negative (column list of the legacy report).</summary>
|
||||
public async Task<ExportFile> ExportAsync(long id, CancellationToken ct)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -218,7 +218,7 @@ internal sealed class WageClaimRepository(IDbSession session, ILogger<WageClaimR
|
|||
t.DISCHARGE_ENTRY_DATE AS DischargeEntryDate, t.CLIENT_NO AS ClientNo, t.LOADING_NO AS LoadingNo,
|
||||
t.ACTUAL_LOADING_DATE AS ActualLoadingDate, t.NET_LOADING_WEIGHT AS NetLoadingWeight, t.WATER_AMOUNT AS WaterAmount,
|
||||
t.NET_DISCHARGE_WEIGHT AS NetDischargeWeight, t.CALCULATED_QUANTITY_TON AS CalculatedQuantityTon,
|
||||
t.TOLERANCE_QUANTITY AS ToleranceQuantity, t.PENALTY_QUANTITY AS PenaltyQuantity, t.TON_PRICE AS TonPrice,
|
||||
t.TOLERANCE_QUANTITY AS ToleranceQuantity, t.PENALTY_QUANTITY AS PenaltyQuantity, t.TON_PRICE AS TonPrice, t.TON_WAGE AS TonWage,
|
||||
t.PENALTY_AMOUNT AS PenaltyAmount, t.DRIVER_TIP AS DriverTip, t.PERMIT_DISPATCH AS PermitDispatch, t.WAYBILL_FEE AS WaybillFee,
|
||||
t.DIESEL_LITER_PRICE AS DieselLiterPrice,
|
||||
(SELECT SUM(l.AMOUNT) FROM REFINERY_CARDS_LOG l WHERE l.PN = t.PN) AS AdvancePaymentForDiesel,
|
||||
|
|
|
|||
|
|
@ -73,7 +73,8 @@ public class WageClaimServiceTests
|
|||
public Task MarkTripTransferredAsync(TransferTripRow trip, long userId, string? ip, CancellationToken ct = default) { Writes.Add("transferred:" + trip.Id); return Task.CompletedTask; }
|
||||
public Task AddLogAsync(long claimId, string method, string? oldData, string? newData, long userId, string? ip, CancellationToken ct = default) { Writes.Add($"log:{method}:{oldData}:{newData}"); return Task.CompletedTask; }
|
||||
public Task<PagedResult<ClaimLogRowDto>> LogAsync(long claimId, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<WageClaimReportRaw>> ReportRowsAsync(long claimId, CancellationToken ct = default) => Task.FromResult<IReadOnlyList<WageClaimReportRaw>>([]);
|
||||
public List<WageClaimReportRaw> Report = [];
|
||||
public Task<IReadOnlyList<WageClaimReportRaw>> ReportRowsAsync(long claimId, CancellationToken ct = default) => Task.FromResult<IReadOnlyList<WageClaimReportRaw>>(Report);
|
||||
}
|
||||
|
||||
private static WageClaimService Service(FakeRepo repo, IJopetrolGateway? gateway = null) =>
|
||||
|
|
@ -106,6 +107,42 @@ public class WageClaimServiceTests
|
|||
Assert.Equal(["tripsComplete:TESTER:77", "status:CLOSE", "log:CLAIM_CLOSE:{\"STATUS_CODE\":\"جديد\"}:{\"STATUS_CODE\":\"تم التسديد\"}"], repo.Writes);
|
||||
}
|
||||
|
||||
private static WageClaimReportRaw Trip(string no, decimal load, decimal discharge, decimal tolerance, decimal penaltyQty) => new()
|
||||
{
|
||||
DischargeAuthoriztionNo = no, DischargeAuthoriztionYear = 2021, NetLoadingWeight = load, NetDischargeWeight = discharge, WaterAmount = 0,
|
||||
CalculatedQuantityTon = discharge / 1000, TonWage = 16.747m, ToleranceQuantity = tolerance, PenaltyQuantity = penaltyQty, PenaltyAmount = 0.45m,
|
||||
DriverTip = 20, PermitDispatch = 2.5m, WaybillFee = 0.75m, AdvancePaymentForDiesel = 100, Commission = 0.45m, NetWage = 400,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Summary_adds_up_the_trips_deductions_positive_and_names_the_tender_of_the_highest_form()
|
||||
{
|
||||
var s = WageClaimRules.ToSummary([Trip("26596", 40000, 39980, 50, 100), Trip("27132", 40000, 39990, 50, 100)]);
|
||||
Assert.Equal(2, s.TripCount);
|
||||
Assert.Equal(80000, s.LoadingWeight);
|
||||
Assert.Equal(30, s.Difference); // 20 + 10
|
||||
Assert.Equal(0, s.PenaltyQuantity); // both differences are under the tolerance
|
||||
Assert.Equal(79.97m, s.CalculatedTon);
|
||||
Assert.Equal(Math.Round(79.97m * 16.747m, 3), Math.Round(s.QuantityWage, 3));
|
||||
Assert.Equal(200, s.DieselAdvance);
|
||||
Assert.Equal(800, s.NetWage);
|
||||
Assert.Equal("27/2021", s.Tender);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Summary_export_is_a_workbook_with_the_claim_number_tender_and_totals()
|
||||
{
|
||||
var repo = new FakeRepo { Report = [Trip("26596", 40000, 39980, 50, 100)] };
|
||||
var f = await Service(repo).ExportSummaryAsync(5, default);
|
||||
Assert.EndsWith(".xlsx", f.FileName);
|
||||
using var zip = new System.IO.Compression.ZipArchive(new MemoryStream(f.Content));
|
||||
var sheet = new StreamReader(zip.GetEntry("xl/worksheets/sheet1.xml")!.Open()).ReadToEnd();
|
||||
Assert.Contains("رقم المطالبة :20230100041", sheet);
|
||||
Assert.Contains("رقم العطاء:26/2021", sheet);
|
||||
Assert.Contains("<v>40000</v>", sheet);
|
||||
Assert.Contains("<mergeCell ref=\"A3:E3\"/>", sheet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reopen_puts_the_trips_and_the_claim_back_and_logs_it()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -153,9 +153,12 @@ export function WageClaimPage() {
|
|||
const c = claim.data;
|
||||
const isNew = c.statusCode === 'NEW'; // CLOSE / TRANSFER exist only on NEW claims (STATUS_ACTION_MATRIX)
|
||||
|
||||
const runExport = async () => {
|
||||
const runExport = async (summary = false) => {
|
||||
setExporting(true);
|
||||
try { await downloadFile(`${BASE}/${c.id}/export`, {}, `wage_claim_${c.wageClaimNo}.xls`); }
|
||||
try {
|
||||
if (summary) await downloadFile(`${BASE}/${c.id}/export-summary`, {}, `wage_claim_summary_${c.wageClaimNo}.xlsx`);
|
||||
else await downloadFile(`${BASE}/${c.id}/export`, {}, `wage_claim_${c.wageClaimNo}.xls`);
|
||||
}
|
||||
catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); }
|
||||
finally { setExporting(false); }
|
||||
};
|
||||
|
|
@ -170,6 +173,9 @@ export function WageClaimPage() {
|
|||
{can('refinery.wageClaims.report') && (
|
||||
<Button variant="outlined" startIcon={<DownloadIcon />} disabled={exporting} onClick={() => void runExport()}>{t('wc.report')}</Button>
|
||||
)}
|
||||
{can('refinery.wageClaims.report') && (
|
||||
<Button variant="outlined" startIcon={<DownloadIcon />} disabled={exporting} onClick={() => void runExport(true)}>{t('wc.reportSummary')}</Button>
|
||||
)}
|
||||
{isNew && can('refinery.wageClaims.transfer') && (
|
||||
<Button variant="outlined" startIcon={<SendIcon />} disabled={transfer.isPending}
|
||||
onClick={async () => { if (await confirm({ message: t('wc.transferConfirm') })) transfer.mutate(c.id); }}>
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@ export default defineStrings({
|
|||
|
||||
// ---- actions
|
||||
'wc.close': { en: 'Pay', ar: 'تسديد' }, // REFINERY_WAGE_CLAIM.CLAIM_CLOSE
|
||||
'wc.reportSummary': { en: 'Summary report', ar: 'تقرير الملخص' },
|
||||
'wc.reopen': { en: 'Back to new', ar: 'اعادة الى جديد' },
|
||||
'wc.reopenConfirm': { en: 'Return this claim to New? Its trips go back to Exchanged.', ar: 'هل تريد اعادة هذه المطالبة الى حالة جديد؟ ستعود ارسالياتها الى حالة تم الصرف.' },
|
||||
'wc.log.CLAIM_REOPEN': { en: 'Reopen', ar: 'اعادة فتح' },
|
||||
|
|
|
|||
Loading…
Reference in New Issue