using NTP.Application.Common;
namespace NTP.Application.Refinery.WageClaims;
/// User-facing texts of the claim screens: the legacy captions (NTP.LT_CAPTION), verbatim.
public static class ClaimMessages
{
public const string Success = "تمت العملية بنجاح"; // PUBLIC.SUCCESSFUL.OPERATION
public const string StatusRequired = "يجب اختيار الحالة"; // ERROR.STATUS_REQUIRED
public const string DateRequired = "يجب اختيار التاريخ"; // ERROR.DATE_REQUIRED
public const string FromGreaterThanTo = "لا يجوز ان يكون تاريخ من أكبر من تارخ الى"; // ERROR.FROM_CAN_NOT_GREATER_THAN_TO
public const string NoTripsNeedWage = "لا يوجد ارساليات جاهزة لانشاء مطالبة مالية"; // ERROR.THERS_IS_NOT_TRIPS_NEED_WAGE
public const string CloseClaim = "لا يمكن تسديد هذه المطالبة يوجد ارساليات ضمن المطالبة حالتها جاهز للدفع او تم التفريغ"; // ERROR.CLOSE_CLAIM
public const string NoAuthority = "ليس لديك صلاحية لاتمام هذه العملية"; // ERROR.NO_AUTHORITY
public const string NoWages = "لا يوجد مطالبات اجور"; // ERROR.THERE_ARE_NO_WAGES
public const string PleaseSelectClaim = "يرجى اختيار المطالبة"; // ERROR.PLEASE_SELECT_CLAIM
public const string WageClaimNotClose = "لا يمكن تسديد هذه المطالبة يوجد مطالبات اجور غير مسددة"; // ERROR.WAGE_CLAIM_IS_NOT_CLOSE
public const string NoTripsIssue = "لا يوجد ارساليات"; // ERROR.NO_TRIPS_THERE_IS_ISSUE
public const string CommissionVariableIssue = "يوجد خطأ في تعريف قيمة عمولة الاجور"; // ERROR.REFINERY_VARIABLES_COMMISSION_ISSUE
/// New text (the legacy code had no such case): the Jopetrol integration is switched off by configuration.
public const string JopetrolDisabled = "خدمة الترحيل إلى المصفاة غير مفعلة في هذه البيئة، لم يتم تغيير أي شيء";
/// New text: a closed claim that already belongs to a commission claim cannot be reopened.
public const string ReopenHasCommission = "لا يمكن اعادة فتح المطالبة لانها مرتبطة بمطالبة عمولة";
public const string NotFound ="المطالبة غير موجودة";
// log captions (method names of the *_LOG tables)
public const string StatusNew = "جديد"; // REFINERY_WAGE_CLAIM.STATUSCODE.NEW
public const string StatusClose = "تم التسديد"; // ...STATUSCODE.CLOSE
public const string StatusComplete = "مكتمل"; // ...STATUSCODE.COMPLETE
public const string TripExchanged = "تم الصرف"; // REFINERYTRIP.STATUSCODE.EXCHANGED
public const string TripComplete = "مكتمل"; // REFINERYTRIP.STATUSCODE.COMPLETE
}
/// Pure rules of the wage claim screen (refinery_wage_claimfactory.cfc).
public static class WageClaimRules
{
public const string New = "NEW";
public const string Close = "CLOSE";
public const string Complete = "COMPLETE";
/// Trip statuses the create dialog offers (REFINERY_WAGE_CLAIMMain.html); trips of other statuses are never attached.
public static readonly IReadOnlyList ClaimableTripStatuses = ["EXCHANGED", "READY_TO_PAY", "DISCHARGED"];
/// Distinct upper-case statuses, only the claimable ones (the legacy select-all option "ALL" and unknown values are dropped).
public static IReadOnlyList NormalizeTripStatuses(IEnumerable? raw) =>
(raw ?? [])
.SelectMany(s => (s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
.Select(s => s.ToUpperInvariant())
.Where(s => ClaimableTripStatuses.Contains(s))
.Distinct()
.ToList();
/// factory.create: status required, both dates required, from not after to (messages in this order).
public static void ValidateCreate(IReadOnlyList statuses, DateOnly? from, DateOnly? to)
{
if (statuses.Count == 0) throw new BusinessException("STATUS_REQUIRED", ClaimMessages.StatusRequired);
if (from is null || to is null) throw new BusinessException("DATE_REQUIRED", ClaimMessages.DateRequired);
if (from.Value > to.Value) throw new BusinessException("FROM_GREATER_THAN_TO", ClaimMessages.FromGreaterThanTo);
}
/// factory.CLAIM_CLOSE: a claim is paid only when it has trips and every one of them is EXCHANGED.
public static bool CanCloseClaim(IEnumerable tripStatuses)
{
var distinct = tripStatuses.Distinct().ToList();
return distinct.Count == 1 && distinct[0] == "EXCHANGED";
}
/// factory.TRANSFER: the Jopetrol answer must contain this text (findNoCase) for the trip to move to TRIP_STATUS 7.
public static bool IsStatus7Success(string? serviceAnswer) =>
serviceAnswer is not null && serviceAnswer.Contains("Status Updated successfully To 7", StringComparison.OrdinalIgnoreCase);
/// Last day (inclusive) of a [from, to] day range as an exclusive upper bound (legacy: between FROM000000 and TO235959).
public static DateTime ExclusiveEnd(DateOnly to) => to.AddDays(1).ToDateTime(TimeOnly.MinValue);
///
/// Report line of one trip, as legacy factoryweb.report prepares it: the deductions (driver tip, permit dispatch, waybill fee, diesel liter price,
/// diesel advance when > 0, commission) are multiplied by -1; the penalty quantity is 0 when the weight difference is below the tolerance
/// (REFINERY_CLAIMS_REPORT_VIEW).
///
public static WageClaimReportLine ToReportLine(WageClaimReportRaw r)
{
decimal V(decimal? d) => d ?? 0m;
var diff = V(r.NetLoadingWeight) - V(r.NetDischargeWeight);
var penaltyQty = diff < V(r.ToleranceQuantity) ? 0m : V(r.PenaltyQuantity);
var advance = V(r.AdvancePaymentForDiesel);
return new WageClaimReportLine(
r.Drvr, r.Tn, r.DischargeAuthoriztionNo, r.DischargeAuthoriztionYear, r.DischargeEntryDate, r.ClientNo,
r.LoadingNo, r.ActualLoadingDate, V(r.NetLoadingWeight), V(r.WaterAmount), V(r.NetDischargeWeight), diff,
V(r.CalculatedQuantityTon), V(r.ToleranceQuantity), V(r.WaterAmount) > 0, penaltyQty, V(r.TonPrice), V(r.PenaltyAmount),
-V(r.DriverTip), -V(r.PermitDispatch), -V(r.WaybillFee), -V(r.DieselLiterPrice),
advance > 0 ? -advance : advance, -V(r.Commission), V(r.NetWage));
}
///
/// تقرير الملخص: 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.
///
public static WageClaimSummary ToSummary(IReadOnlyList 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));
}
/// "27/2021": form numbers are tender number + 3-digit serial (26596 = tender 26); empty when the trips have no usable form number.
public static string TenderLabel(IEnumerable 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}";
}
/// Caption of a claim status (REFINERY_WAGE_CLAIM.STATUS.* / REFINERY_COMMISSION_CLAIM.STATUS.*).
public static string ClaimStatusCaption(string? code) => code switch
{
New => ClaimMessages.StatusNew,
Close => ClaimMessages.StatusClose,
Complete => ClaimMessages.StatusComplete,
_ => code ?? "",
};
}