using System.Globalization; using System.Text.Json; using FluentValidation; using NTP.Application.Abstractions; using NTP.Application.Common; using NTP.Domain.Grains.Permits; namespace NTP.Application.Grains.Permits; public interface IPermitService { Task> SearchAsync(PermitSearchQuery query, PageRequest page, CancellationToken ct = default); Task> SearchGateListAsync(GatePermitQuery query, PageRequest page, CancellationToken ct = default); Task GetAsync(long id, CancellationToken ct = default); Task> GetEventsAsync(long id, CancellationToken ct = default); Task GetTruckInfoAsync(string tn, bool validate, CancellationToken ct = default); Task GetTrailerInfoAsync(string trn, CancellationToken ct = default); Task GetDriverInfoAsync(string nnpn, CancellationToken ct = default); Task SubmitAsync(long id, SubmitOrderRequest request, CancellationToken ct = default); Task UpdateAsync(long id, UpdateOrderRequest request, CancellationToken ct = default); Task AcceptAsync(long id, CancellationToken ct = default); Task RevokeAsync(long id, CancellationToken ct = default); Task RevokeAcceptedAsync(long id, CancellationToken ct = default); Task ConvertToResdAsync(long id, CancellationToken ct = default); Task CancelOrderAsync(long id, ReasonRequest request, CancellationToken ct = default); Task RevokePermitAsync(long id, ReasonRequest request, CancellationToken ct = default); Task ReactivateAsync(long id, CancellationToken ct = default); /// GrainsFactory.cancelGrainsPermit: a released permit goes back to ACCPT (used by integrations). Task CancelGrainsPermitAsync(long id, CancellationToken ct = default); Task CloseManualAsync(ClosePermitRequest request, CancellationToken ct = default); Task PhoneAcceptAsync(long id, PhoneAcceptRequest request, CancellationToken ct = default); Task PhoneRejectAsync(long id, PhoneRejectRequest request, CancellationToken ct = default); /// Phone accept performed by an actor other than the signed-in user (auto dialer callback = SYSTEM). Task PhoneAcceptCoreAsync(long permitId, string? remarks, string doneBy, CancellationToken ct); /// Phone reject performed by an actor other than the signed-in user (auto dialer callback = SYSTEM). Task PhoneRejectCoreAsync(long permitId, string reason, int expiryDays, string doneBy, CancellationToken ct, string category = "PHONEDECLINE"); Task ValidateReferencesAsync(string tn, string trn, string nnpn, long scac, CancellationToken ct = default); Task SaveWeightsAsync(SaveWeightsRequest request, CancellationToken ct = default); Task LookupWeightsAsync(string pn, CancellationToken ct = default); AbsenceFeatureDto GetAbsenceFeature(); Task ToggleAbsenceFeatureAsync(CancellationToken ct = default); } /// /// Order lifecycle of grain permits (legacy grains.cfc: getGNPermits, getGNList, getPermitInfo, submitOrder, updateOrder, /// Accept, revoke, RevokeAcceptedOrder, convertToResd, deleteGnOrder, RevokeGnPermit, activateGNOrder, closePermit, /// addPhoneAcceptEvent, addPhoneRejectEvent, saveGrainsWeights, permitAutoComplete, ActiveInActiveGNAbsenceFeature). /// public sealed class PermitService( IPermitRepository repo, IPhoneEventRepository phoneRepo, IDestinationRepository destinations, IQueueService queue, IMobileNotificationGatewayService notifications, IEventLogger events, IUnitOfWork uow, ICurrentUser user, IGrainsPermitsSettingsService settings) : IPermitService { private GrainsPermitsOptions options => settings.Value; private const string Entity = "Permit"; // ------------------------------------------------------------------------------------------------ lists public async Task> SearchAsync(PermitSearchQuery q, PageRequest page, CancellationToken ct = default) { // Legacy returned an empty grid until at least one filter was given ("يجب البحث اولا لتظهر لك الأرساليات"). if (!q.HasFilter) return new PagedResult([], page.SafePage, page.SafePageSize, 0); var company = q.CompanyCode; if (user.IsCompany(options)) company = user.CompanyCodeNo() ?? -1; // session.stkid = 62 -> own permits only var criteria = new PermitSearchCriteria( Trim(q.Tn), Trim(q.Pn), Trim(q.Status), q.DestAddressId, ParseTenderOrder(q.TenderOrder), Trim(q.ShipmentMode), PermitDates.ParseLegacy(q.CreationDate), company); var result = await repo.SearchAsync(criteria, page, ct); foreach (var row in result.Items) row.Actions = ActionsFor(row.ShipmentStatusCode, row.CompanyCode); return result; } public Task> SearchGateListAsync(GatePermitQuery q, PageRequest page, CancellationToken ct = default) { // getGNList: gate roles see every company, everybody else only its own company code. var restrict = !user.IsInAnyRole("GATEIN", "GATEOUT", "THRU"); return repo.SearchGateListAsync(q with { Tn = Trim(q.Tn), Trn = Trim(q.Trn), Pn = Trim(q.Pn) }, user.Domain, user.CompanyCodeNo(), restrict, page, ct); } public async Task GetAsync(long id, CancellationToken ct = default) { var info = await repo.GetInfoAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(info.CompanyCode); var truck = string.IsNullOrWhiteSpace(info.Tn) ? null : await repo.GetTruckInfoAsync(info.Tn, null, ct); var trailer = string.IsNullOrWhiteSpace(info.Trn) ? null : await repo.GetTrailerInfoAsync(info.Trn, null, ct); var driver = string.IsNullOrWhiteSpace(info.Nnpn) ? null : await repo.GetDriverInfoAsync(info.Nnpn, ct); var evs = await repo.GetEventsAsync(id, ct); return new PermitDetailDto { Id = id, Pn = info.Pn, StatusCode = info.ShipmentStatusCode, StatusCaption = info.StatusCaption, CompanyCode = info.CompanyCode, CompanyName = info.CompanyName, QueueNo = info.QueueNo, Shift = OrderLabels.ShiftShort(info.MobileShift), CargoType = info.CargoTypeName, OperationTypeCode = info.InbondTypeCode, OperationType = OrderLabels.OperationType(info.InbondTypeCode), Truck = truck is null ? (info.Tn is null ? null : new TruckInfoDto(info.Tn, null, null, null)) : ToDto(truck), Trailer = trailer is null ? (info.Trn is null ? null : new TruckInfoDto(info.Trn, null, null, null)) : ToDto(trailer), Driver = driver is null ? null : new DriverInfoDto(driver.Nnpn ?? string.Empty, driver.Name, driver.Dln, PermitDates.Display(driver.Dled)), Actions = ActionsFor(info.ShipmentStatusCode, info.CompanyCode), // createGnOrder.cfm hides the "performed by" column from company users; the API keeps the field and the UI hides it. Events = evs }; } public async Task> GetEventsAsync(long id, CancellationToken ct = default) { var p = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(p.CompanyCode); return await repo.GetEventsAsync(id, ct); } // ------------------------------------------------------------------------------------------------ lookups public async Task GetTruckInfoAsync(string tn, bool validate, CancellationToken ct = default) { tn = tn.Trim(); var companyNo = user.CompanyCodeNo(); if (validate) { if (companyNo is null) throw new BusinessException("TN_COMPANY_REQUIRED", "القاطرة غير موجودة "); await ValidateMotAsync(tn, companyNo.Value, ct); } var row = await repo.GetTruckInfoAsync(tn, user.IsCompany(options) ? companyNo : null, ct); return row is null ? null : ToDto(row); } public async Task GetTrailerInfoAsync(string trn, CancellationToken ct = default) { trn = trn.Trim(); if (user.IsCompany(options)) { var scac = await repo.GetTrailerScacAsync(trn, ct); if (scac != user.CompanyCodeNo()) throw new BusinessException("TRAILER_NOT_IN_FLEET", PermitAssignmentRules.TrailerNotInFleet); } var row = await repo.GetTrailerInfoAsync(trn, user.IsCompany(options) ? user.CompanyCodeNo() : null, ct); return row is null ? null : new TrailerInfoDto(trn, row.ChasesNumber, row.Axials, PermitDates.Display(row.RegDate)); } public async Task GetDriverInfoAsync(string nnpn, CancellationToken ct = default) { var r = await repo.GetDriverInfoAsync(nnpn.Trim(), ct); return r is null ? null : new DriverInfoDto(r.Nnpn ?? nnpn, r.Name, r.Dln, PermitDates.Display(r.Dled)); } private async Task ValidateMotAsync(string tn, long companyNo, CancellationToken ct) { // register.cfc validateOwnerTN + validateTNMOT (trucktype.general.cargo). var rows = await repo.GetMotTruckAsync(companyNo, tn, ct); if (rows.Count == 0) throw new BusinessException("MOT_NOT_REGISTERED", "خطأ في تسجيل السيارة/ السيارة غير مؤتلفة"); var ownership = rows[0].OwnershipCode; if (companyNo == options.BadiyaScac) { if (options.BadiyaOwnershipCodes.Length > 0 && !options.BadiyaOwnershipCodes.Contains(ownership ?? string.Empty)) throw new BusinessException("MOT_OWNERSHIP", "لا يجوز اضافة سيارات الاهالي على الشركات"); } else if (options.OtherOwnershipCodes.Length > 0 && !options.OtherOwnershipCodes.Contains(ownership ?? string.Empty)) { throw new BusinessException("MOT_OWNERSHIP", "لا يجوز اضافة سيارات الاهالي على الشركات"); } if (!rows.Any(r => r.TruckTypeCode is "trucktype.general.cargo" or "trucktype.all")) throw new BusinessException("MOT_WRONG_TYPE", "النمط غير صحيح"); } // ------------------------------------------------------------------------------------------------ submit / update public async Task SubmitAsync(long id, SubmitOrderRequest r, CancellationToken ct = default) { new SubmitOrderValidator().ValidateAndThrow(r); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); // legacy: an order already ACCPT / RESD cannot be submitted again. if (permit.ShipmentStatusCode is PermitStatus.Released or PermitStatus.Accepted) throw new BusinessException("PERMIT_BAD_STATE", PermitAssignmentRules.BadStatus); await ValidateAssignmentAsync(permit, r.Tn, r.Trn, r.Nnpn, isSubmit: true, ct); var dled = PermitDates.ParseLegacy(r.Dled); await uow.ExecuteInTransactionAsync(async token => { await repo.SubmitAsync(id, r, dled, user.UserId, token); var remarks = r.OpType == "IMPT" ? "محمل" : "فارغ"; await events.LogAsync(user, id, PermitStatus.Requested, PermitStatus.Planned, PermitEventType.SaveOperationType, remarks, ct: token); await events.LogAsync(user, id, PermitStatus.Requested, PermitStatus.Planned, PermitEventType.Override, ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } public async Task UpdateAsync(long id, UpdateOrderRequest r, CancellationToken ct = default) { new UpdateOrderValidator().ValidateAndThrow(r); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); // Deviation: legacy did not check the status; the UI only offers "edit" for REQST / PLND / OPEN (on the turn), so the API enforces it. if (permit.ShipmentStatusCode is not (PermitStatus.Requested or PermitStatus.Planned or PermitStatus.Open)) throw new BusinessException("PERMIT_BAD_STATE", PermitAssignmentRules.BadStatus); await ValidateAssignmentAsync(permit, r.Tn, r.Trn, r.Nnpn, isSubmit: false, ct); var dled = PermitDates.ParseLegacy(r.Dled); await uow.ExecuteInTransactionAsync(async token => { await repo.UpdateOrderAsync(id, r, dled, user.UserId, token); await events.LogAsync(user, id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.Modify, ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } /// Ownership / fleet rules shared by submitOrder and updateOrder (messages kept verbatim). private async Task ValidateAssignmentAsync(PermitRow permit, string tn, string trn, string nnpn, bool isSubmit, CancellationToken ct) { var isCompany = user.IsCompany(options); var companyNo = user.CompanyCodeNo(); var truck = await repo.GetTruckRegistrationAsync(tn, ct); if (truck?.TcsCac != companyNo && isCompany) throw new BusinessException("TRUCK_NOT_IN_FLEET", PermitAssignmentRules.TruckNotInFleet); if (truck?.TcsCac == companyNo && isCompany && permit.CompanyCode != companyNo) throw new BusinessException("TRUCK_ON_FOREIGN_PERMIT", PermitAssignmentRules.TruckOnForeignPermit); var trailerScac = await repo.GetTrailerScacAsync(trn, ct); if (trailerScac != companyNo && isCompany) throw new BusinessException("TRAILER_NOT_IN_FLEET", PermitAssignmentRules.TrailerNotInFleet); if (trailerScac == companyNo && isCompany && permit.CompanyCode != companyNo) throw new BusinessException("TRAILER_ON_FOREIGN_PERMIT", PermitAssignmentRules.TrailerOnForeignPermit); if (isSubmit) { if (permit.CompanyCode != trailerScac) throw new BusinessException("TRAILER_NOT_IN_FLEET", PermitAssignmentRules.TrailerNotInFleet); if (!await repo.DriverIsRegisteredAsync(nnpn, ct)) throw new BusinessException("DRIVER_NOT_REGISTERED", PermitAssignmentRules.DriverNotRegistered); } var dup = await repo.FindActiveConflictAsync("TN", tn, permit.Id, ct); if (dup is not null) throw new BusinessException("TRUCK_HAS_ACTIVE_PERMIT", $"يوجد ارسالية فعالة للشاحنة, رقم الارسالية الفعالة {dup.Pn}"); dup = await repo.FindActiveConflictAsync("TRN", trn, permit.Id, ct); if (dup is not null) throw new BusinessException("TRAILER_HAS_ACTIVE_PERMIT", $"يوجد ارسالية فعالة للمقطورة, رقم الارسالية الفعالة {dup.Pn}"); dup = await repo.FindActiveConflictAsync("NNPN", nnpn, permit.Id, ct); if (dup is not null) throw new BusinessException("DRIVER_HAS_ACTIVE_PERMIT", $"يوجد ارسالية فعالة للسائق, رقم الارسالية الفعالة {dup.Pn}"); // A gallab order needs a tripper head. (submitOrder applies it to owner trailers only, updateOrder always.) if (!isSubmit || trailerScac == options.BadiyaScac) { var order = await repo.GetPermitOrderAsync(permit.Id, ct); if (order is not null && PermitAssignmentRules.IsGallabOrder(order.Ct) && !string.Equals(truck?.HeadType, "Tripper", StringComparison.Ordinal)) throw new BusinessException("GALLAB_NEEDS_TRIPPER", PermitAssignmentRules.GallabNeedsTripper); } } // ------------------------------------------------------------------------------------------------ accept / revoke public async Task AcceptAsync(long id, CancellationToken ct = default) { var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); if (permit.ShipmentStatusCode != PermitStatus.Planned) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); var invalid = await ValidateReferencesAsync(permit.Tn ?? string.Empty, permit.Trn ?? string.Empty, permit.Nnpn ?? string.Empty, permit.CompanyCode ?? 0, ct); if (invalid.Length > 0) throw new BusinessException("PERMIT_REFERENCES_INVALID", invalid); await uow.ExecuteInTransactionAsync(async token => { // AddToQueue(TN, TT, COMPANYCODE, TRN, 'false'): opens the truck's next turn; its message is ignored by legacy. await queue.AddToQueueInternalAsync(permit.Tn ?? string.Empty, permit.Tt ?? string.Empty, user.UserId, false, token); await repo.SetStatusAsync(id, PermitStatus.Accepted, user.UserId, token); await events.LogAsync(user, id, PermitStatus.Planned, PermitStatus.Accepted, PermitEventType.Override, ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } /// validatePermitReferences: returns an Arabic error text or empty when everything is registered and in an allowed status. public async Task ValidateReferencesAsync(string tn, string trn, string nnpn, long scac, CancellationToken ct = default) { var allowed = options.AllowedStatuses; var truck = await repo.GetTruckStatusAsync(scac, tn, ct); if (truck is null) return "السيارة غير مسجلة"; if (!allowed.Contains(truck)) return "حالة السيارة غير صحيحة"; var trailer = await repo.GetTrailerStatusAsync(trn, ct); if (trailer is null || !allowed.Contains(trailer)) return "حالة المقطورة غير صحيحة"; var driver = await repo.GetDriverStatusAsync(nnpn, ct); if (driver is null || !allowed.Contains(driver)) return "حالة السائق غير صحيحة"; return string.Empty; } public async Task RevokeAsync(long id, CancellationToken ct = default) { var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); if (permit.ShipmentStatusCode != PermitStatus.Planned) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); await uow.ExecuteInTransactionAsync(async token => { await repo.SetStatusAsync(id, PermitStatus.Requested, user.UserId, token); await repo.ResetTruckValidationAsync(permit.Tn ?? string.Empty, user.UserId, token); await events.LogAsync(user, id, PermitStatus.Planned, PermitStatus.Requested, PermitEventType.Override, ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } public async Task RevokeAcceptedAsync(long id, CancellationToken ct = default) { var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); EnsureCompanyAccess(permit.CompanyCode); if (permit.ShipmentStatusCode is not (PermitStatus.Accepted or PermitStatus.Released)) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة ، يجب ان تكون الإرسالية جاهز للتسريب لتتمكن من الغاء تثبيتها"); await uow.ExecuteInTransactionAsync(async token => { await repo.SetStatusAsync(id, PermitStatus.Planned, user.UserId, token); await events.LogAsync(user, id, permit.ShipmentStatusCode, PermitStatus.Planned, PermitEventType.Cancel, ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } public async Task ConvertToResdAsync(long id, CancellationToken ct = default) { if (!user.IsInAnyRole(GrainsRoles.ConvertToResd.Split(','))) throw new ForbiddenException("FORBIDDEN", "غير مصرح لك بهذه العملية"); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); // Deviation: legacy converted by PN with no status check; the UI shows the button for ACCPT only. if (permit.ShipmentStatusCode != PermitStatus.Accepted) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); await uow.ExecuteInTransactionAsync(async token => { await repo.SetStatusAsync(id, PermitStatus.Released, user.UserId, token); await events.LogAsync(user, id, permit.ShipmentStatusCode, PermitStatus.Released, PermitEventType.ConvertToResd, ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } public async Task CancelOrderAsync(long id, ReasonRequest r, CancellationToken ct = default) { new ReasonValidator().ValidateAndThrow(r); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); // Deviation: the legacy button exists for RESD only (action 106) but the CFC had no check. if (permit.ShipmentStatusCode != PermitStatus.Released) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); await uow.ExecuteInTransactionAsync(async token => { await repo.ResetToOpenAsync(id, user.UserId, token); // legacy logs the target status as RVKD although the permit goes back to OPEN await events.LogAsync(user, id, permit.ShipmentStatusCode, PermitStatus.Revoked, PermitEventType.Override, r.Reason, ct: token); await repo.RevokeNextOpenPermitsAsync(id, user.UserId, token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } public async Task RevokePermitAsync(long id, ReasonRequest r, CancellationToken ct = default) { new ReasonValidator().ValidateAndThrow(r); var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); // Deviation: legacy button exists for OPEN only (action 167); enforced here. if (permit.ShipmentStatusCode != PermitStatus.Open) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); await uow.ExecuteInTransactionAsync(async token => { await repo.SetStatusAsync(id, PermitStatus.Revoked, user.UserId, token); await events.LogAsync(user, id, permit.ShipmentStatusCode, PermitStatus.Revoked, PermitEventType.Revoked, r.Reason, ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } public async Task ReactivateAsync(long id, CancellationToken ct = default) { var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); if (permit.ShipmentStatusCode != PermitStatus.Revoked) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); var conflict = await repo.FindOpenConflictForReactivationAsync(permit, ct); if (conflict is not null) throw new BusinessException("PERMIT_REACTIVATE_CONFLICT", $"لا يمكن اعادة الارسالية الى على الدور القاطرة لديها ارسالية رقم {conflict.Pn}"); await uow.ExecuteInTransactionAsync(async token => { await repo.SetStatusAsync(id, PermitStatus.Open, user.UserId, token); await events.LogAsync(user, id, PermitStatus.Revoked, PermitStatus.Open, PermitEventType.Override, ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } public async Task CancelGrainsPermitAsync(long id, CancellationToken ct = default) { var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); if (permit.ShipmentStatusCode != PermitStatus.Released) throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); await uow.ExecuteInTransactionAsync(async token => { await repo.SetStatusAsync(id, PermitStatus.Accepted, user.UserId, token); await events.LogAsAsync(user.UserId, null, id, PermitStatus.Released, PermitStatus.Accepted, PermitEventType.Override, "cancelGrainsPermit(GrainsFactory)", ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); } public async Task CloseManualAsync(ClosePermitRequest r, CancellationToken ct = default) { new ClosePermitValidator().ValidateAndThrow(r); var permit = await repo.FindClosablePermitAsync(r.Pn, ct) ?? throw new BusinessException("PN_INVALID", "رقم التصريح المدخل غير صحيح"); await uow.ExecuteInTransactionAsync(async token => { await repo.SetStatusAsync(permit.Id, PermitStatus.Closed, user.UserId, token); await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, PermitStatus.Closed, PermitEventType.Override, "اغلاق تصريح يدوي", withLocation: false, ct: token); return true; }, ct); return PermitOperationResult.Ok("تم اغلاق التصريح بنجاح", permit.Id); } // ------------------------------------------------------------------------------------------------ phone events public Task PhoneAcceptAsync(long id, PhoneAcceptRequest r, CancellationToken ct = default) => PhoneAcceptCoreAsync(id, r.Remarks, user.UserId, ct); public Task PhoneRejectAsync(long id, PhoneRejectRequest r, CancellationToken ct = default) { new PhoneRejectValidator().ValidateAndThrow(r); return PhoneRejectCoreAsync(id, r.Reason.Trim(), r.ExpiryDays, user.UserId, ct); } /// addPhoneAcceptEvent. Also used by the dialer callback (autoCall) with doneBy = SYSTEM. public async Task PhoneAcceptCoreAsync(long permitId, string? remarks, string doneBy, CancellationToken ct) { var permit = await repo.GetAsync(permitId, ct) ?? throw new NotFoundException(Entity, permitId); var orderDetails = permit.Scrn is long o ? await destinations.GetOrderDetailsAsync(o, ct) : null; if (permit.Scrn is long order && await phoneRepo.HasClosedDistributionAsync(permitId, order, ct)) throw new BusinessException("ALREADY_APPROVED_MOBILE", "تمت الموافقة مسبقا من مستخدم تطبيق نافذ"); var text = string.IsNullOrWhiteSpace(remarks) ? " تمت الموافقة هاتفيا ، تم تحديد الوجهة " + $"{orderDetails?.CargoType} - {orderDetails?.Location}" : remarks!; await uow.ExecuteInTransactionAsync(async token => { // legacy logs REQST -> REQST regardless of the actual status await events.LogAsAsync(doneBy, null, permitId, PermitStatus.Requested, PermitStatus.Requested, PermitEventType.PhoneAccept, text, ct: token); if (permit.Scrn is long ord) await phoneRepo.CloseDistributionAsync(permitId, ord, text, token); return true; }, ct); var phone = await phoneRepo.GetTruckPhoneAsync(permit.Tn ?? string.Empty, ct); await notifications.SendAsync("CONFIRM_PN", new Dictionary { ["TN"] = permit.Tn, ["MOBILE"] = phone ?? string.Empty, ["PN"] = permit.Pn, ["ORDERDATE"] = orderDetails?.OrderDate, ["TT"] = orderDetails?.CtCaption }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, permitId); } /// addPhoneRejectEvent (+ BL_addToBlacklist). Also used by the dialer callback with doneBy = SYSTEM. public async Task PhoneRejectCoreAsync(long permitId, string reason, int expiryDays, string doneBy, CancellationToken ct, string category = "PHONEDECLINE") { var permit = await repo.GetAsync(permitId, ct) ?? throw new NotFoundException(Entity, permitId); var order = permit.Scrn is long o ? await destinations.GetOrderAsync(o, ct) : null; var shift = order?.Shift ?? 1; var sh = options.DistributionShift(shift); var expiry = PhoneRejectRules.BlacklistExpiry(DateTime.Now, sh[0], sh[1], expiryDays); var isAbsence = PhoneRejectRules.IsAbsence(reason); long blacklistId = 0; await uow.ExecuteInTransactionAsync(async token => { blacklistId = await phoneRepo.InsertBlacklistAsync(new NewBlacklistEntry { Category = category, EntityId = permitId, CreatedBy = doneBy, ExpiryDate = expiry, Remarks = reason + "، سيتم فك الانتظار بشكل تلقائي بتاريخ " + expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture) }, doneBy, token); if (permit.Scrn is long ord && await phoneRepo.GetOrderDateDiffDaysAsync(ord, token) < 0 && permit.TrackingNo is long queueId) { // The order is for a future date: give the queue turn back. await phoneRepo.DecrementQueueCounterAsync(queueId, token); if (permit.CompanyCode != options.BadiyaScac && permit.CompanyCode is long scac) { var (code, _) = await phoneRepo.GetQueueInfoAsync(queueId, token); if (code == "GALLAB") await phoneRepo.DecrementCompanyBulkQueueAsync(scac, token); } } await repo.ResetToOpenAsync(permitId, doneBy, token); await repo.RevokeNextOpenPermitsAsync(permitId, doneBy, token); return true; }, ct); // Notification (after the transaction, as in legacy). var phone = await phoneRepo.GetTruckPhoneAsync(permit.Tn ?? string.Empty, ct); await notifications.SendAsync(isAbsence ? "PHONE_REJECT" : "DELAY_PN", new Dictionary { ["MOBILE"] = phone ?? string.Empty, ["NUMOFEXPIRYDAY"] = expiryDays, ["EXPIRYDATE"] = DateTime.Now.AddDays(expiryDays).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), ["PN"] = permit.Pn, ["TN"] = permit.Tn, ["TT"] = OrderLabels.OrderType(order?.Ct) }, ct); await events.LogAsAsync(doneBy, null, permitId, PermitStatus.Requested, PermitStatus.Open, PermitEventType.PhoneReject, reason, ct: ct); // TRUCK_DISTRIBUTION_LOG bookkeeping if (permit.Scrn is long ordId) { var closed = await phoneRepo.GetClosedDistributionAsync(permitId, ordId, ct); if (closed is not null) { if (!isAbsence) await phoneRepo.PostponeApprovedDistributionAsync(closed, permitId, ordId, blacklistId, "تم تاجيل الارسالية من خلال نظام نافذ للعملاء علما بان هذه الارسالية تم الموافقة عليها من تطبيق نافذ مسبقا", ct); else await phoneRepo.MarkDistributionRevokedAsync(closed.Id, blacklistId, $"الإضافة على قائمة المنع بسبب {reason}", ct); return PermitOperationResult.Ok("تمت العملية بنجاح.اضيفت الارسالية الى قائمة المنع", permitId, Data(blacklistId, expiry)); } } if (!isAbsence) await phoneRepo.MarkPendingDistributionAsync(permitId, blacklistId, reason, false, ct); else await phoneRepo.MarkPendingDistributionAsync(permitId, blacklistId, $"الإضافة على قائمة المنع بسبب {reason}", true, ct); return PermitOperationResult.Ok("تمت العملية بنجاح.اضيفت الارسالية الى قائمة المنع", permitId, Data(blacklistId, expiry)); } private static IReadOnlyDictionary Data(long blId, DateTime expiry) => new Dictionary { ["blacklistId"] = blId, ["expiryDate"] = expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture) }; // ------------------------------------------------------------------------------------------------ weights / feature flag public async Task SaveWeightsAsync(SaveWeightsRequest r, CancellationToken ct = default) { new SaveWeightsValidator().ValidateAndThrow(r); var weightMsg = WeighbridgeRules.ValidateStoredWeights(r.EmptyWeight, r.GrossWeight); if (weightMsg is not null) throw new BusinessException("WEIGHT_LENGTH", weightMsg); var permit = await repo.GetByPnAsync(r.Pn, ct) ?? throw new BusinessException("PN_INVALID", "رقم الارسالية غير موجود"); await uow.ExecuteInTransactionAsync(async token => { var existing = await repo.GetStoredWeightsIdAsync(permit.Id, token); await repo.UpsertStoredWeightsAsync(permit.Id, existing, r, user.UserId, token); await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.AddWeights, $"الوزن القائم: {r.GrossWeight} الوزن الفارغ: {r.EmptyWeight}", withLocation: false, ct: token); return true; }, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, permit.Id); } public async Task LookupWeightsAsync(string pn, CancellationToken ct = default) => await repo.GetStoredWeightsAsync(pn.Trim(), options.BadiyaScac, ct) ?? throw new BusinessException("PN_INVALID", "الرجاء التأكد من رقم الارسالية"); public AbsenceFeatureDto GetAbsenceFeature() => new(AbsenceFeatureState.IsEnabled(options.AbsenceFeatureEnabled)); public async Task ToggleAbsenceFeatureAsync(CancellationToken ct = default) { var enabled = AbsenceFeatureState.Toggle(options.AbsenceFeatureEnabled); var json = JsonSerializer.Serialize(new { ONOROFF = enabled, userid = user.UserId, userrolecode = user.RoleCode }); await repo.LogActivationAsync("GN_ABSENCE_FEATURE", user.UserId, user.RoleCode, json, ct); return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, null, new Dictionary { ["enabled"] = enabled }); } // ------------------------------------------------------------------------------------------------ helpers private IReadOnlyList ActionsFor(string? status, long? companyCode) => PermitActionRules.For(status, companyCode, user.IsCompany(options), user.IsInAnyRole(GrainsRoles.Operators.Split(',')), user.IsInAnyRole(GrainsRoles.ConvertToResd.Split(',')), user.IsInAnyRole("SU", "GTO"), options.BadiyaScac); private void EnsureCompanyAccess(long? permitCompany) { if (user.IsCompany(options) && permitCompany != user.CompanyCodeNo()) throw new ForbiddenException("PERMIT_FOREIGN_COMPANY", "لا تملك صلاحية على هذه الإرسالية"); } private static string? Trim(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); private static TruckInfoDto ToDto(TruckInfoRow r) => new(r.Tn ?? string.Empty, r.ChasesNumber, r.Axials, PermitDates.Display(r.RegDate)); /// TENDERORDER filter = "dd/MM/yyyy,shift". internal static DateTime? ParseTenderOrder(string? value) { if (string.IsNullOrWhiteSpace(value)) return null; var first = value.Split(',')[0].Trim(); return DateTime.TryParseExact(first, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d) ? d.Date : PermitDates.ParseLegacy(first); } }