230 lines
14 KiB
C#
230 lines
14 KiB
C#
using System.Text.Encodings.Web;
|
|
using System.Text.Json;
|
|
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;
|
|
|
|
/// <summary>JSON of the OLD_DATA / NEW_DATA columns of the *_LOG tables: <c>{"STATUS_CODE":"..."}</c> with real (unescaped) Arabic, as legacy logs.saveLog.</summary>
|
|
public static class ClaimLogJson
|
|
{
|
|
private static readonly JsonSerializerOptions Opts = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
|
|
public static string Status(string caption) => JsonSerializer.Serialize(new Dictionary<string, string> { ["STATUS_CODE"] = caption }, Opts);
|
|
}
|
|
|
|
public interface IWageClaimService
|
|
{
|
|
Task<PagedResult<WageClaimRowDto>> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct);
|
|
Task<WageClaimRowDto> GetAsync(long id, CancellationToken ct);
|
|
Task<PagedResult<ClaimTripRowDto>> TripsAsync(long id, PageRequest page, CancellationToken ct);
|
|
Task<PagedResult<ClaimTripRowDto>> CandidateTripsAsync(IReadOnlyList<string>? statusCodes, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct);
|
|
Task<PagedResult<ClaimLogRowDto>> LogAsync(long id, PageRequest page, CancellationToken ct);
|
|
Task<ClaimResult> CreateAsync(CreateWageClaimRequest request, string? ip, CancellationToken ct);
|
|
Task<ClaimResult> CloseAsync(long id, string? ip, CancellationToken ct);
|
|
Task<ClaimResult> SetClosedAsync(long id, string? ip, CancellationToken ct);
|
|
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>
|
|
/// Port of refinery_wage_claimfactory.cfc. Who may do what is decided by the permission keys on the controller
|
|
/// (PermissionKeys.RefineryWageClaims*), not by the legacy role branches.
|
|
/// </summary>
|
|
public sealed class WageClaimService(IWageClaimRepository repo, IUnitOfWork unit, IJopetrolGateway jopetrol, ICurrentUser user) : IWageClaimService
|
|
{
|
|
public Task<PagedResult<WageClaimRowDto>> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct) => repo.SearchAsync(query, page, ct);
|
|
|
|
public async Task<WageClaimRowDto> GetAsync(long id, CancellationToken ct) =>
|
|
await repo.GetAsync(id, ct) ?? throw new NotFoundException("REFINERY_WAGE_CLAIM", id);
|
|
|
|
public async Task<PagedResult<ClaimTripRowDto>> TripsAsync(long id, PageRequest page, CancellationToken ct)
|
|
{
|
|
await GetAsync(id, ct);
|
|
return await repo.ClaimTripsAsync(id, page, ct);
|
|
}
|
|
|
|
public Task<PagedResult<ClaimTripRowDto>> CandidateTripsAsync(IReadOnlyList<string>? statusCodes, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct)
|
|
{
|
|
// legacy searchClaimTrips: no status = the three statuses of the dialog; from after to is refused
|
|
var statuses = WageClaimRules.NormalizeTripStatuses(statusCodes);
|
|
if (statuses.Count == 0) statuses = WageClaimRules.ClaimableTripStatuses;
|
|
if (from is not null && to is not null && from.Value > to.Value) throw new BusinessException("FROM_GREATER_THAN_TO", ClaimMessages.FromGreaterThanTo);
|
|
return repo.CandidateTripsAsync(statuses, from, to, page, ct);
|
|
}
|
|
|
|
public async Task<PagedResult<ClaimLogRowDto>> LogAsync(long id, PageRequest page, CancellationToken ct)
|
|
{
|
|
await GetAsync(id, ct);
|
|
return await repo.LogAsync(id, page, ct);
|
|
}
|
|
|
|
/// <summary>factory.create: attaches the trips of the chosen statuses and loading dates that have no wage claim to a new NEW claim.</summary>
|
|
public async Task<ClaimResult> CreateAsync(CreateWageClaimRequest request, string? ip, CancellationToken ct)
|
|
{
|
|
var statuses = WageClaimRules.NormalizeTripStatuses(request.StatusCodes);
|
|
WageClaimRules.ValidateCreate(statuses, request.LoadingDateFrom, request.LoadingDateTo);
|
|
var from = request.LoadingDateFrom!.Value;
|
|
var to = request.LoadingDateTo!.Value;
|
|
|
|
var id = await unit.ExecuteInTransactionAsync(async c =>
|
|
{
|
|
if (await repo.CountCandidateTripsAsync(statuses, from, to, c) == 0)
|
|
throw new BusinessException("NO_TRIPS_NEED_WAGE", ClaimMessages.NoTripsNeedWage);
|
|
var claimId = await repo.InsertClaimAsync(user.UserId, c);
|
|
await repo.AttachTripsAsync(claimId, statuses, from, to, c);
|
|
await repo.AddLogAsync(claimId, "CREATE", "{}", ClaimLogJson.Status(WageClaimRules.New), user.Id, ip, c);
|
|
return claimId;
|
|
}, ct);
|
|
return new ClaimResult(ClaimMessages.Success, id);
|
|
}
|
|
|
|
/// <summary>factory.CLAIM_CLOSE (تسديد, claim screen): NEW claim whose trips are all EXCHANGED -> trips COMPLETE (+ trip log), claim CLOSE (+ log).</summary>
|
|
public async Task<ClaimResult> CloseAsync(long id, string? ip, CancellationToken ct)
|
|
{
|
|
var claim = await GetAsync(id, ct);
|
|
if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority);
|
|
await EnsureCommissionNewAsync(claim, ct);
|
|
if (!WageClaimRules.CanCloseClaim(await repo.ClaimTripStatusesAsync(id, ct)))
|
|
throw new BusinessException("CLOSE_CLAIM", ClaimMessages.CloseClaim);
|
|
|
|
await unit.ExecuteInTransactionAsync(async c =>
|
|
{
|
|
await repo.CompleteClaimTripsAsync(id, user.UserId, user.Id, ip, c);
|
|
await repo.SetClaimStatusAsync(id, WageClaimRules.Close, user.UserId, c);
|
|
await repo.AddLogAsync(id, "CLAIM_CLOSE", ClaimLogJson.Status(ClaimMessages.StatusNew), ClaimLogJson.Status(ClaimMessages.StatusClose), user.Id, ip, c);
|
|
return 0;
|
|
}, ct);
|
|
return new ClaimResult(ClaimMessages.Success, id);
|
|
}
|
|
|
|
/// <summary>Grid status change NEW -> CLOSE: only the REFINERY_WAGE_CLAIM record (+ log); the trips keep their status.</summary>
|
|
public async Task<ClaimResult> SetClosedAsync(long id, string? ip, CancellationToken ct)
|
|
{
|
|
var claim = await GetAsync(id, ct);
|
|
if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority);
|
|
await EnsureCommissionNewAsync(claim, ct);
|
|
|
|
await unit.ExecuteInTransactionAsync(async c =>
|
|
{
|
|
await repo.SetClaimStatusAsync(id, WageClaimRules.Close, user.UserId, c);
|
|
await repo.AddLogAsync(id, "CLAIM_CLOSE", ClaimLogJson.Status(ClaimMessages.StatusNew), ClaimLogJson.Status(ClaimMessages.StatusClose), user.Id, ip, c);
|
|
return 0;
|
|
}, ct);
|
|
return new ClaimResult(ClaimMessages.Success, id);
|
|
}
|
|
|
|
/// <summary>The status of a wage claim changes only when it has no commission claim or that commission claim is NEW.</summary>
|
|
private async Task EnsureCommissionNewAsync(WageClaimRowDto claim, CancellationToken ct)
|
|
{
|
|
if (claim.CommissionClaimId is null) return;
|
|
if (await repo.CommissionClaimStatusAsync(claim.CommissionClaimId.Value, ct) != WageClaimRules.New)
|
|
throw new BusinessException("COMMISSION_NOT_NEW", ClaimMessages.CommissionNotNew);
|
|
}
|
|
|
|
/// <summary>Reopen: CLOSE claim -> NEW (+ log), trips untouched. Refused when its commission claim is not NEW.</summary>
|
|
public async Task<ClaimResult> ReopenAsync(long id, string? ip, CancellationToken ct)
|
|
{
|
|
var claim = await GetAsync(id, ct);
|
|
if (claim.StatusCode != WageClaimRules.Close) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority);
|
|
await EnsureCommissionNewAsync(claim, ct);
|
|
|
|
await unit.ExecuteInTransactionAsync(async c =>
|
|
{
|
|
await repo.SetClaimStatusAsync(id, WageClaimRules.New, user.UserId, c);
|
|
await repo.AddLogAsync(id, "CLAIM_REOPEN", ClaimLogJson.Status(ClaimMessages.StatusClose), ClaimLogJson.Status(ClaimMessages.StatusNew), user.Id, ip, c);
|
|
return 0;
|
|
}, ct);
|
|
return new ClaimResult(ClaimMessages.Success, id);
|
|
}
|
|
|
|
/// <summary>
|
|
/// factory.TRANSFER (ترحيل): each trip of the claim with TRIP_STATUS 6 is sent to Jopetrol; when the service answers "Status Updated successfully To 7"
|
|
/// the trip gets TRIP_STATUS 7 and a TRANSFER_TO_REFINERY log row. When the integration is disabled nothing is called and nothing is changed.
|
|
/// </summary>
|
|
public async Task<ClaimResult> TransferAsync(long id, string? ip, CancellationToken ct)
|
|
{
|
|
var claim = await GetAsync(id, ct);
|
|
if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority);
|
|
|
|
var trips = await repo.TripsToTransferAsync(id, ct);
|
|
var sent = 0;
|
|
foreach (var trip in trips)
|
|
{
|
|
string? answer;
|
|
try
|
|
{
|
|
answer = await jopetrol.SendClaimAndUpdateStatusTo7Async(trip.Pn ?? "", claim.WageClaimNo?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "", ct);
|
|
}
|
|
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException or System.Xml.XmlException)
|
|
{
|
|
// the service is down: stop here, what was already moved stays moved
|
|
throw new BusinessException("JOPETROL_FAILED", $"تعذر الاتصال بخدمة المصفاة، تم ترحيل {sent} من {trips.Count} ارسالية");
|
|
}
|
|
if (answer is null) throw new BusinessException("JOPETROL_DISABLED", ClaimMessages.JopetrolDisabled);
|
|
if (!WageClaimRules.IsStatus7Success(answer)) continue;
|
|
|
|
await unit.ExecuteInTransactionAsync(async c =>
|
|
{
|
|
await repo.MarkTripTransferredAsync(trip, user.Id, ip, c);
|
|
return 0;
|
|
}, ct);
|
|
sent++;
|
|
}
|
|
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)
|
|
{
|
|
var claim = await GetAsync(id, ct);
|
|
var lines = (await repo.ReportRowsAsync(id, ct)).Select(WageClaimRules.ToReportLine).ToList();
|
|
string[] headers =
|
|
[
|
|
"متسلسل", "اسم السائق", "رقم الشاحنة", "رقم النموذج", "السنة", "تاريخ النموذج", "رقم الناقل الفرعي", "اسم الناقل الفرعي", "رقم البوليصة",
|
|
"تاريخ البوليصة", "كمية البوليصة", "كمية الماء (كغم)", "كمية المصفاة (كغم)", "الفروقات", "الكمية المحسوبة طن", "كمية السماح", "الماء المصاحب",
|
|
"كمية التغريم (كغم)", "سعر الطن", "خصم قيمة فرق كمية مغرمة", "اكرامية السائق", "خصم تسريب الصهريج", "خصم اصدار وثيقة", "سعر لتر دينار/لتر",
|
|
"خصم قيمة 350 لتر ديزل", "خصم عمولة الصرف التنافسي", "صافي قيمة الصرف الفعلي",
|
|
];
|
|
var i = 0;
|
|
var rows = lines.Select(l => new object?[]
|
|
{
|
|
++i, l.Drvr, l.Tn, l.DischargeAuthoriztionNo, l.DischargeAuthoriztionYear, ClaimExcel.D(l.DischargeEntryDate), l.ClientNo, "", l.LoadingNo,
|
|
ClaimExcel.D(l.ActualLoadingDate), ClaimExcel.N(l.NetLoadingWeight), ClaimExcel.N(l.WaterAmount), ClaimExcel.N(l.NetDischargeWeight),
|
|
ClaimExcel.N(l.WeightDifference), ClaimExcel.N(l.CalculatedQuantityTon), ClaimExcel.N(l.ToleranceQuantity), l.WaterExist ? "نعم" : "لا",
|
|
ClaimExcel.N(l.PenaltyQuantity), ClaimExcel.N(l.TonPrice), ClaimExcel.N(l.PenaltyAmount), ClaimExcel.N(l.DriverTip), ClaimExcel.N(l.PermitDispatch),
|
|
ClaimExcel.N(l.WaybillFee), ClaimExcel.N(l.DieselLiterPrice), ClaimExcel.N(l.AdvancePaymentForDiesel), ClaimExcel.N(l.Commission), ClaimExcel.N(l.NetWage),
|
|
});
|
|
return ClaimExcel.Build("شاشة مطالبات صرف أجور النقل",
|
|
[$"رقم مطالبة اجور النقل : {claim.WageClaimNo}"], headers, rows, user.UserId, $"wage_claim_{claim.WageClaimNo}");
|
|
}
|
|
}
|