NTP_V2/src/NTP.Domain/Grains/Permits/PermitRules.cs

338 lines
17 KiB
C#

using System.Globalization;
namespace NTP.Domain.Grains.Permits;
/// <summary>generatePermitNumber (grains.cfc): permit number layout per company type and cargo type.</summary>
public static class PermitNumberGenerator
{
/// <param name="cargoType">BULK or PCKD (anything else yields an empty number, as in legacy).</param>
/// <param name="sequence">next value of SEQ_GRAINS_TRACKINGNO_OWN (owners) or SEQ_GRAINS_TRACKINGNO_CO (companies).</param>
/// <param name="companyCode">SCAC of the company the permit belongs to.</param>
/// <param name="badiyaScac">SCAC of the owners (individuals) pseudo company (legacy application.GN_BadiyaSCAC).</param>
/// <param name="tenderCount">max(NTP_TENDER.ID) for domain GN.</param>
public static string Generate(string cargoType, long sequence, long companyCode, long badiyaScac, long tenderCount)
{
var isOwner = companyCode == badiyaScac;
var t2 = Pad(tenderCount, 2);
if (string.Equals(cargoType, GrainsCargo.Bulk, StringComparison.OrdinalIgnoreCase))
return isOwner ? "30" + t2 + Pad(sequence, 6) : "1" + t2 + Pad(sequence, 6);
if (string.Equals(cargoType, GrainsCargo.Packed, StringComparison.OrdinalIgnoreCase))
{
var packedTender = 41 + tenderCount;
return isOwner
? "3" + packedTender.ToString(CultureInfo.InvariantCulture) + Pad(sequence, 7)
: "1" + packedTender.ToString(CultureInfo.InvariantCulture) + Pad(sequence, 6);
}
return string.Empty;
}
private static string Pad(long v, int width) => v.ToString(CultureInfo.InvariantCulture).PadLeft(width, '0');
}
/// <summary>What a weighbridge reading does to a permit.</summary>
public enum WeighbridgeAction { None, LoadingTare, LoadingGross, DischargeGross, DischargeTare }
public sealed record WeighbridgeDecision(
bool Allowed,
string ErrorCode,
string? Message,
WeighbridgeAction Action = WeighbridgeAction.None,
string? EventType = null,
string? CurrentStatus = null,
string? NewPermitStatus = null,
string? PrintAction = null)
{
public const string WrongStatus = "حالة السيارة غير صحيحة";
public const string LocationNotOnRoute = "الموقع غير موجود على مسار الشاحنة";
public const string Success = "تمت العملية بنجاح";
}
/// <summary>Weighbridge transaction state machine (ws.cfc addWeightBridgeEvent).</summary>
public static class WeighbridgeRules
{
public const string Entry = "EN";
public const string Exit = "EX";
/// <summary>
/// Origin location + EN = loading tare (LTW); origin + EX = loading gross (LGW, status ACTRL);
/// destination + EN = discharge gross (DGW, status CLRPR); destination + EX = discharge tare (DTW, CLOSE).
/// </summary>
public static WeighbridgeDecision Decide(string status, long? originId, long? destinationId, long locationId, string trxType)
{
string? locType = null;
if (originId == locationId) locType = "ORG";
else if (destinationId == locationId) locType = "DEST";
if (locType is null)
return new(false, "2", WeighbridgeDecision.LocationNotOnRoute);
bool In(params string[] s) => s.Contains(status);
var wrong = new WeighbridgeDecision(false, "1", WeighbridgeDecision.WrongStatus);
switch (locType, trxType)
{
case ("ORG", Entry):
return In(PermitStatus.Accepted, PermitStatus.Released)
? new(true, "0", WeighbridgeDecision.Success, WeighbridgeAction.LoadingTare, PermitEventType.LoadingTare, status)
: wrong;
case ("ORG", Exit):
return In(PermitStatus.Accepted, PermitStatus.Released, PermitStatus.ArrivedControl)
? new(true, "0", WeighbridgeDecision.Success, WeighbridgeAction.LoadingGross, PermitEventType.LoadingGross,
PermitStatus.ArrivedControl, PermitStatus.ArrivedControl, "printPage1")
: wrong;
case ("DEST", Entry):
return In(PermitStatus.Accepted, PermitStatus.Released, PermitStatus.ArrivedControl, PermitStatus.ClearedPreliminary)
? new(true, "0", WeighbridgeDecision.Success, WeighbridgeAction.DischargeGross, PermitEventType.DischargeGross,
PermitStatus.ClearedPreliminary, PermitStatus.ClearedPreliminary)
: wrong;
case ("DEST", Exit):
return status == PermitStatus.ClearedPreliminary
? new(true, "0", WeighbridgeDecision.Success, WeighbridgeAction.DischargeTare, PermitEventType.DischargeTare,
PermitStatus.Closed, PermitStatus.Closed, "printPage2")
: wrong;
default:
return new(false, "4", null);
}
}
/// <summary>WeightBridge.cfm: first (tare) 10000..25000, second (gross) 35000..75000 and gross greater than tare.</summary>
public static string? ValidateManualWeights(long weightIn, long weightOut)
{
if (!(weightIn is >= 10000 and <= 25000 && weightOut is >= 35000 and <= 75000))
return "الوزن الاول يجب ان يكون بين 10000 و 25000 والوزن الثاني يجب ان يكون بين 35000 و 75000";
if (weightOut <= weightIn)
return "الوزن الاول يحب أن يكون أصغر من الوزن الثاني";
return null;
}
/// <summary>loadingWeightBridge/dischargeWeightBridge.cfm: gross must be greater than tare.</summary>
public static string? ValidateGrossTare(long gross, long tare) =>
gross > tare ? null : "الوزن القائم يجب ان يكون اكبر من الفارغ";
/// <summary>saveGrainsWeights: every weight needs at least 5 digits.</summary>
public static string? ValidateStoredWeights(string? empty, string? gross) =>
(empty?.Trim().Length ?? 0) < 5 || (gross?.Trim().Length ?? 0) < 5 ? "يجب ان يكون الوزن من 5 خانات" : null;
}
/// <summary>printIn.cfm weight arithmetic (kilograms split into ton + kilo, signed difference).</summary>
public sealed record WeightBreakdown(
long LoadingNet, long DischargeNet,
long LoadingTon, long LoadingKilo, long DischargeTon, long DischargeKilo,
long TonDifference, long KiloDifference, string Sign)
{
public static WeightBreakdown Compute(decimal loadingTare, decimal loadingGross, decimal dischargeTare, decimal dischargeGross)
{
var lnw = (long)(loadingGross - loadingTare);
var dnw = (long)(dischargeGross - dischargeTare);
var dTon = dnw / 1000;
var lTon = lnw / 1000;
var dKilo = dnw - dTon * 1000;
var lKilo = lnw - lTon * 1000;
var sign = Math.Sign(dnw - lnw) switch { -1 => "(-)", 1 => "(+)", _ => " " };
return new(lnw, dnw, lTon, lKilo, dTon, dKilo, dTon - lTon, dKilo - lKilo, sign);
}
public static (long Ton, long Kilo) Split(decimal weight)
{
var w = (long)weight;
var ton = w / 1000;
return (ton, w - ton * 1000);
}
}
/// <summary>distributePackedBulk: maps the requested category to queue code / type / permit cargo type.</summary>
public sealed record DistributionCategory(string Request, string DistributionCode, string QueueType, string PermitCargoType)
{
public bool IsPacked => DistributionCode == GrainsCargo.Packed;
public bool IsGallabCompany => Request == "BULK_GALLAB_COMP";
public static readonly string[] Allowed =
["PCKD", "BULK_AHALE", "BULK_COMP", "BULK_GALLAB_COMP", "BULK_GALLAB_AHALE", "RED_SEA"];
public static DistributionCategory? Parse(string? request)
{
var r = request?.Trim() ?? string.Empty;
return r switch
{
"BULK_AHALE" => new(r, "BULK", "AHALE", "BULK"),
"BULK_COMP" => new(r, "BULK", "COMP", "BULK"),
"PCKD" => new(r, "PCKD", "", "PCKD"),
// البحر الأحمر: its own cargo class / queue code RED_SEA, not split into individuals and companies (new, no legacy counterpart)
"RED_SEA" => new(r, "RED_SEA", "", "RED_SEA"),
"BULK_GALLAB_COMP" => new(r, "BULK_GALLAB", "COMP", "BULK"),
"BULK_GALLAB_AHALE" => new(r, "BULK_GALLAB", "AHALE", "BULK"),
_ => null
};
}
/// <summary>GRAINS_COMPANIES_QUEUE code/type filter used to compute each company's share (queue spelling is AHALI).</summary>
public (string Code, string? Type) QueueFilter => Request switch
{
"BULK_AHALE" => ("BULK", "AHALI"),
"BULK_COMP" => ("BULK", "COMP"),
"PCKD" => ("PCKD", null),
"BULK_GALLAB_AHALE" => ("BULK", "AHALI"),
"BULK_GALLAB_COMP" => ("GALLAB", "COMP"),
_ => (DistributionCode, null)
};
public string NoOrdersMessage => Request switch
{
"PCKD" => "لا توجد طلبات مشول مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
"BULK_AHALE" => "لا توجد طلبات سائب أفراد مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
"BULK_COMP" => "لا توجد طلبات سائب شركات مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
"BULK_GALLAB_COMP" => "لا توجد طلبات قلاب شركات مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
"BULK_GALLAB_AHALE" => "لا توجد طلبات قلاب أفراد مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
"RED_SEA" => "لا توجد طلبات البحر الأحمر مسجلة على النظام ، او قد تم توزيع كامل الطلبية",
_ => string.Empty
};
}
/// <summary>Arabic captions used by getOrderDetails / events grids.</summary>
public static class OrderLabels
{
public static string CargoGroup(long? cargoType, string fallback) => cargoType switch
{
GrainsCargo.WheatBulk or GrainsCargo.BarleyBulk => "سائب",
GrainsCargo.PackedA or GrainsCargo.PackedBarley => "مشول",
_ => fallback
};
public static string Location(long? id, string fallback) => id switch
{
GrainsLocations.Silos => "صوامع",
GrainsLocations.Direct => "مباشر",
GrainsLocations.RiceWarehouses => "مستودعات الرز",
GrainsLocations.MainPortGeneral => "الميناء الرئيسي/البضائع العامة",
GrainsLocations.AqabaWarehouses => "مستودعات العقبة",
GrainsLocations.AqabaSouthSilos => "صوامع العقبة الجنوبية",
GrainsLocations.SouthPortDirect => "الميناء الجنوبي/مباشر",
_ => fallback
};
public static string OrderType(string? ct) => ct switch
{
"PCKD" => "مشول",
"BULK_GALLAB" => "سائب قلاب",
"BULK" => "سائب",
_ => ct ?? string.Empty
};
/// <summary>Shift label as in getOrderDetails (1 morning, 2 evening).</summary>
public static string MobileShift(long? shift) =>
shift switch { 1 => "الشفت الصباحي", 2 => "الشفت المسائي", 3 => "الشفت الليلي", _ => string.Empty };
/// <summary>Short shift label as in getPermitInfo / acceptPrint.</summary>
public static string ShiftShort(long? shift) =>
shift switch { 1 => "صباحي", 2 => "مسائي", 3 => "ليلي", _ => string.Empty };
public static string OperationType(string? inbondTypeCode) =>
inbondTypeCode switch { "EXPT" => "فارغ", "IMPT" => "محمل", _ => string.Empty };
}
/// <summary>getAllEvents: legacy Arabic event captions (EVENTS.EVENTTYPE + current status).</summary>
public static class PermitEventCaptions
{
public static string Caption(string? eventType, string? currentStatus)
{
switch (eventType)
{
case PermitEventType.AssignDest: return "تحديد وجهة";
case PermitEventType.ManualAssignDest: return "تحديد وجهة يدوي";
case PermitEventType.LoadingTare: return "قبان تحميل وزنة أولى";
case PermitEventType.LoadingGross: return "قبان تحميل وزنة ثانية";
case PermitEventType.DischargeGross: return "قبان تفريغ وزنة أولى";
case PermitEventType.DischargeTare: return "قبان تفريغ وزنة ثانية";
case PermitEventType.AssignGrainsDest: return "تحديد وجهة ارسالية تموين";
case PermitEventType.PhoneAccept: return "تأكيد الطلبية هاتفيا";
case PermitEventType.PhoneReject: return "الغاء الطلبية هاتفيا";
case PermitEventType.SaveOperationType: return "تحديد نوع العملية";
case PermitEventType.AddWeights: return "تثبيت أوزان التحميل";
case PermitEventType.ConvertToResd: return "تحويل الى تم التسريب";
case PermitEventType.NoAnswer: return "لم يتم الرد";
case PermitEventType.Override:
return currentStatus switch
{
PermitStatus.Open => "تسجيل دور",
PermitStatus.Requested => "توزيع طلبية",
PermitStatus.Planned => "تثبيت دور",
PermitStatus.Accepted => "كشف حسي",
PermitStatus.Released => "تقديم ارسالية",
_ => eventType
};
default: return eventType ?? string.Empty;
}
}
}
/// <summary>addPhoneRejectEvent rules.</summary>
public static class PhoneRejectRules
{
public static readonly string[] AbsenceReasons =
["عدم الحضور بعد التسريب", "عدم الحضور بعد التوزيع", "تجاوز عدد الإستنكافات المسموح بها"];
public static readonly string[] AllowedReasons =
[
"لايمكن الاتصال به", "رقم الهاتف غير صحيح", "الهاتف مغلق", "قائمة الانتظار", "لايرد", "غير موافق",
.. AbsenceReasons
];
public static readonly int[] AllowedExpiryDays = [1, 2, 3, 4, 5, 14, 30];
public static bool IsAbsence(string? reason) => AbsenceReasons.Contains(reason?.Trim() ?? string.Empty);
/// <summary>BL_addToBlacklist expiry: date part of (now - (24 + shiftStart) h) + days + shiftEnd h.</summary>
public static DateTime BlacklistExpiry(DateTime now, int shiftStartHour, int shiftEndHour, int days) =>
now.AddHours(-(24 + shiftStartHour)).Date.AddDays(days).AddHours(shiftEndHour);
/// <summary>autoDailerResponse: maps the dialer's word suffix to a postponement of N days.</summary>
public static int PostponeDaysFromDialerKey(string? three) => (three ?? string.Empty).ToLowerInvariant() switch
{
"one" => 1, "two" => 2, "thr" => 3, "fou" => 4, "fiv" => 5, _ => 0
};
}
/// <summary>assignDestination location filtering by truck type (packed trucks lose the bulk silo/berth set).</summary>
public static class DestinationRules
{
public static readonly long[] BulkLocations = [215, 220, 225, 350];
public static readonly string[] PackedTruckAsrns = ["201401693756", "201401693891"];
public static IReadOnlyList<long> FilterCompanyLocations(IEnumerable<long> locations, string? lastAsrn)
{
var packed = lastAsrn is not null && PackedTruckAsrns.Contains(lastAsrn);
return packed
? locations.Where(l => !BulkLocations.Contains(l)).ToList()
: locations.Where(l => BulkLocations.Contains(l)).ToList();
}
/// <summary>Cargo types that may be assigned when a permit already holds an order (38/39 and 40/41 are interchangeable).</summary>
public static long[]? CargoGroup(long? cargoType) => cargoType switch
{
38 or 39 => [38, 39],
40 or 41 => [40, 41],
_ => null
};
}
public static class OperationWindow
{
/// <summary>"sysdate between orderdate + first/24 and orderdate + last/24" for a shift given as [first,last] hours.</summary>
public static bool IsWithin(DateTime now, DateTime orderDate, int firstHour, int lastHour) =>
now >= orderDate.Date.AddHours(firstHour) && now <= orderDate.Date.AddHours(lastHour);
}
/// <summary>submitOrder/updateOrder: which plate/driver combination is acceptable for an order (pure part).</summary>
public static class PermitAssignmentRules
{
public const string TruckNotInFleet = "هذه القاطرة ليست ضمن قاطرات الشركة";
public const string TrailerNotInFleet = "هذه المقطورة ليست ضمن مقطورات الشركة";
public const string TruckOnForeignPermit = "لا يمكن تثبيت القاطرة على ارسالية غير تابعه للشركة";
public const string TrailerOnForeignPermit = "لا يمكن تثبيت المقطورة على ارسالية غير تابعه للشركة";
public const string DriverNotRegistered = "السائق يجب ان يكون مسجل في شاشة السائقين";
public const string GallabNeedsTripper = "يجب ان تكون النمط قلاب كون الطلبية قلاب";
public const string BadStatus = "حالة الارسالية غير صحيحة";
/// <summary>A gallab order (CT ends with GALLAB) needs a head of type Tripper.</summary>
public static bool IsGallabOrder(string? ct) => ct is { Length: >= 6 } && ct[^6..] == "GALLAB";
}