NTP_V2/src/NTP.Application/Grains/Permits/DistributionService.cs

527 lines
28 KiB
C#

using System.Collections.Concurrent;
using System.Globalization;
using System.Text;
using FluentValidation;
using NTP.Application.Abstractions;
using NTP.Application.Common;
using NTP.Domain.Grains.Permits;
namespace NTP.Application.Grains.Permits;
public interface IDistributionService
{
Task<PermitOperationResult> DistributeAsync(DistributeRequest request, CancellationToken ct = default);
Task<PermitOperationResult> ReleaseAsync(ReleasePermitRequest request, CancellationToken ct = default);
Task<PermitOperationResult> ProcessOpenPermitAsync(OpenPermitRequest request, CancellationToken ct = default);
Task<PermitOperationResult> ProcessOpenPermitWithDestinationAsync(OpenPermitWithDestinationRequest request, CancellationToken ct = default);
Task<PermitOperationResult> ProcessCompanyOpenPermitsAsync(CompanyOpenPermitsRequest request, CancellationToken ct = default);
Task<PermitOperationResult> DistributeSingleTruckAsync(string tn, CancellationToken ct = default);
Task<IReadOnlyList<DistributionSummaryRow>> GetSummaryAsync(CancellationToken ct = default);
Task<IReadOnlyList<DistributionPivotRow>> GetPivotAsync(CancellationToken ct = default);
Task<TruckDistributionDto> SearchTruckAsync(string tn, CancellationToken ct = default);
Task<IReadOnlyList<BlacklistedDistributionDto>> GetBlacklistedAsync(string tn, CancellationToken ct = default);
Task<PermitOperationResult> CheckTripsAsync(CheckTripsRequest request, CancellationToken ct = default);
Task<PermitOperationResult> RevokeAllRequestedAsync(long scrnBelow, CancellationToken ct = default);
/// <summary>jobs/checkForGabanEvents.cfm: permits whose loading window passed without an ASSIGNDEST go back to OPEN.</summary>
Task<int> RevertUnloadedPermitsAsync(string actor, CancellationToken ct = default);
// auto call
Task<PermitOperationResult> SendAutoCallFileAsync(AutoCallRequest request, CancellationToken ct = default);
Task<PermitOperationResult> TriggerIvrAsync(CancellationToken ct = default);
bool IsValidDialerApiKey(string? key);
Task<AutoCallCallbackResult> HandleDialerCallbackAsync(AutoCallResponse response, CancellationToken ct = default);
}
/// <summary>Per-user position in the company queue between two "distribute companies" runs (legacy session.QueueStart).</summary>
internal static class DistributionCursor
{
private static readonly ConcurrentDictionary<string, long> Positions = new(StringComparer.OrdinalIgnoreCase);
public static long Get(string user) => Positions.GetValueOrDefault(user, 1);
public static void Set(string user, long value) => Positions[user] = value;
}
public sealed class DistributionService(
IDistributionRepository repo,
IDestinationRepository destinations,
IPermitRepository permits,
IPhoneEventRepository phoneRepo,
IPermitService permitService,
IMobileNotificationGatewayService notifications,
IAutoCallGatewayService autoCall,
IEventLogger events,
IUnitOfWork uow,
ICurrentUser user,
IGrainsPermitsSettingsService settings) : IDistributionService
{
private GrainsPermitsOptions options => settings.Value;
// ------------------------------------------------------------------------------------------------ distributePackedBulk
private sealed record ReleaseOutcome(string ErrorMsg, long? Scac = null, string? CargoLabel = null);
public async Task<PermitOperationResult> DistributeAsync(DistributeRequest r, CancellationToken ct = default)
{
new DistributeValidator().ValidateAndThrow(r);
var cat = DistributionCategory.Parse(r.Category)!;
var totals = await repo.GetOrderTotalsAsync(cat.DistributionCode, cat.QueueType, cat.IsPacked, ct);
var used = await repo.GetUsedOrdersAsync(cat.DistributionCode, cat.QueueType, cat.IsPacked, ct);
if (totals.AllQuantity <= 0)
return PermitOperationResult.Fail("NO_ORDERS", cat.NoOrdersMessage);
await repo.PrepareDataAsync(cat.PermitCargoType, options.BadiyaScac, ct);
decimal available;
if (cat.IsPacked)
{
var comps = totals.TotalComps - (used?.UsedComps ?? 0);
var owners = totals.TotalOwners - (used?.UsedOwners ?? 0);
available = comps + owners;
}
else
{
available = totals.AllQuantity - (used is null ? 0 : used.UsedComps + used.UsedOwners);
}
var queueAvailable = (long)available;
if (available < 0)
return PermitOperationResult.Fail("NO_ORDERS", cat.IsPacked
? "لا توجد طلبات مشول مسجلة على النظام ، او قد تم توزيع كامل الطلبية"
: "لا توجد طلبات سائب مسجلة على النظام ، او قد تم توزيع كامل الطلبية");
var start = DistributionCursor.Get(user.UserId);
var (code, type) = cat.QueueFilter;
var shares = await repo.GetCompanyShareAsync(code, type, cat.IsGallabCompany, start, queueAvailable, ct);
if (shares.Count == 0)
return PermitOperationResult.Fail("NO_ORDERS", cat.NoOrdersMessage);
var picks = await repo.GetCompanyQueuePermitsAsync(shares, cat.DistributionCode, cat.PermitCargoType, cat.IsGallabCompany,
cat.DistributionCode == GrainsCargo.BulkGallab, options.BadiyaScac, ct);
var companyCounter = 0;
var ownerCounter = 0;
var ownerNotes = new List<IReadOnlyDictionary<string, object?>>();
var companyNotes = new Dictionary<string, object?>();
await uow.ExecuteInTransactionAsync(async token =>
{
foreach (var p in picks)
{
var outcome = await ReleaseCoreAsync(p.Pn ?? string.Empty, p.Scac, cat.DistributionCode, cat.QueueType, token);
if (outcome.ErrorMsg.Length > 0) continue;
if (outcome.Scac == options.BadiyaScac) ownerCounter++; else companyCounter++;
await repo.IncrementQueueCounterAsync(p.Qid, token);
if (cat.IsGallabCompany) await repo.IncrementCompanyQueueAsync(p.Scac, "BULK", "COMP", token);
await repo.SetTrackingNoAsync(p.Pn ?? string.Empty, p.Qid, token);
var label = cat.DistributionCode == GrainsCargo.BulkGallab ? outcome.CargoLabel + " قلاب " : outcome.CargoLabel;
if (!string.IsNullOrEmpty(p.Tn))
{
var d = await repo.GetOwnerDistributionDataAsync(p.Tn, options.BadiyaScac, token);
ownerNotes.Add(new Dictionary<string, object?>
{
["TN"] = p.Tn, ["PN"] = p.Pn,
["TT"] = cat.DistributionCode == GrainsCargo.BulkGallab ? d?.Name + " قلاب " : d?.Name,
["LOCATION"] = d?.Location, ["ORDERDATE"] = d?.OrderDate, ["SHIFT"] = d?.Shift
});
}
else
{
var key = p.Scac.ToString(CultureInfo.InvariantCulture).PadLeft(3, '0');
companyNotes[key] = companyNotes.TryGetValue(key, out var n) ? (int)n! + 1 : 1;
companyNotes["TT"] = label;
}
}
return true;
}, ct);
await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS", new Dictionary<string, object?> { ["NOTIFICATIONARY"] = ownerNotes }, ct);
await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_COMP", companyNotes, ct);
if (cat.Request is "BULK_COMP" or "BULK_GALLAB_COMP")
DistributionCursor.Set(user.UserId, companyCounter == 0 ? start + queueAvailable : 1);
return PermitOperationResult.Ok($"تم توزيع {companyCounter} شركات - {ownerCounter} أفراد ، من أصل{queueAvailable}",
data: new Dictionary<string, object?> { ["companies"] = companyCounter, ["owners"] = ownerCounter, ["available"] = queueAvailable });
}
// ------------------------------------------------------------------------------------------------ releasePermit
public async Task<PermitOperationResult> ReleaseAsync(ReleasePermitRequest r, CancellationToken ct = default)
{
if (!long.TryParse(r.Scac, out var scac)) throw new ValidationException("رقم الشركة غير صحيح");
var outcome = await uow.ExecuteInTransactionAsync(token => ReleaseCoreAsync(r.Pn, scac, r.Category, r.QueueType, token), ct);
return outcome.ErrorMsg.Length == 0
? PermitOperationResult.Ok(PermitOperationResult.DefaultOk)
: PermitOperationResult.Fail(outcome.ErrorMsg == "noDist" ? "NO_DESTINATION" : "INVALID_PERMIT", outcome.ErrorMsg);
}
private async Task<ReleaseOutcome> ReleaseCoreAsync(string pn, long scac, string category, string queueType, CancellationToken ct)
{
var permit = await repo.GetOpenPermitWithFirmsAsync(pn, scac, ct);
if (permit is null) return new("INVALID PERMITID");
var locations = await repo.GetAllowedLocationsForReleaseAsync(permit, scac, options.BadiyaScac, ct);
NextOrderPick? order = locations.Count == 0
? null
: await repo.GetNextOrderAsync(locations, category, category == GrainsCargo.Packed ? null : queueType, ct);
if (order is null)
{
if (scac == options.BadiyaScac)
await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Open, PermitEventType.Override,
$"لم يتم توزيع أي وجهة للسيارة رقم {permit.Tn} لعدم وجود مجهة متناسبة مع طلب الشركة", ct: ct);
return new("noDist");
}
await repo.SetRequestedWithOrderAsync(permit.Id, order.Id, ct);
var d = await destinations.GetOrderDetailsAsync(order.Id, ct);
await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
$"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: ct);
if (scac == options.BadiyaScac)
{
await repo.UpdateLastPermitAsync(order.Id, options.BadiyaScac, ct);
await repo.DeletePendingDistributionAsync(permit.Id, permit.Tn ?? string.Empty, order.Id, ct);
var orderDate = PermitDates.ParseLegacy(d?.OrderDate) ?? DateTime.Today;
await repo.InsertDistributionLogAsync(permit.Id, order.Id, orderDate, permit.Tn ?? string.Empty, "AUTO_DEST", d?.CargoTypeCode, ct);
}
return new(string.Empty, scac, d?.CargoType);
}
// ------------------------------------------------------------------------------------------------ procssOpenPermit*
public async Task<PermitOperationResult> ProcessOpenPermitAsync(OpenPermitRequest r, CancellationToken ct = default)
{
var permit = await repo.GetFirstOpenPermitByTnAsync(r.Tn.Trim(), r.CargoType, ct)
?? throw new BusinessException("TRUCK_NOT_QUEUED", "السيارة ليست على الدور");
await uow.ExecuteInTransactionAsync(async token =>
{
if (r.SaveScrn)
{
var orders = await repo.GetNextOrdersForTruckAsync(r.Tn.Trim(), token);
if (orders.Count == 0)
throw new BusinessException("NO_MATCHING_DESTINATION", "لا توجد وجهات مناسبة متوافقة مع طلب الشركة");
long orderId = 0;
foreach (var o in orders)
{
if (permit.CompanyCode == options.BadiyaScac
|| await repo.IsLocationAllowedForCompanyAsync(permit.CompanyCode ?? 0, o.Destenation, token))
{
orderId = o.Id;
break;
}
}
if (orderId == 0) throw new BusinessException("NO_ORDERS_AVAILABLE", "لا توجد طلبيات متاحة");
await repo.SetRequestedWithOrderAsync(permit.Id, orderId, token);
var d = await destinations.GetOrderDetailsAsync(orderId, token);
await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
$"تحميل: {d?.Location} / {d?.CargoType}", ct: token);
}
else
{
await repo.SetRequestedAsync(permit.Id, token);
await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token);
}
return true;
}, ct);
return PermitOperationResult.Ok("تم تحويل حالة السيارة إلى توزيع طلبية", permit.Id);
}
public async Task<PermitOperationResult> ProcessOpenPermitWithDestinationAsync(OpenPermitWithDestinationRequest r, CancellationToken ct = default)
{
new OpenPermitWithDestinationValidator().ValidateAndThrow(r);
var permit = await permits.GetByPnAsync(r.Pn, ct) ?? throw new BusinessException("PN_INVALID", "رقم الارسالية غير صحيح");
if (permit.ShipmentStatusCode != PermitStatus.Open)
throw new BusinessException("PERMIT_BAD_STATE", "حالة الارسالية غير صحيحة");
var order = await repo.GetOrderForManualAsync(r.Locations, ct) ?? throw new NotFoundException("Order", r.Locations);
var d = await destinations.GetOrderDetailsAsync(r.Locations, ct);
var orderDate = PermitDates.ParseLegacy(r.OrderDate) ?? DateTime.Today;
await uow.ExecuteInTransactionAsync(async token =>
{
var scac = permit.CompanyCode ?? 0;
var code = order.Ct == GrainsCargo.BulkGallab ? "BULK" : order.Ct ?? string.Empty;
var type = string.IsNullOrEmpty(order.Type) ? null : order.Type.Replace("AHALE", "AHALI");
var queueId = await repo.PickQueueIdAsync(scac, code, type, token)
?? throw new BusinessException("NO_QUEUE", "لا يوجد دور مسجل للشركة");
await repo.IncrementQueueCounterAsync(queueId, token);
if (order.Ct == GrainsCargo.BulkGallab && scac != options.BadiyaScac)
await repo.IncrementCompanyQueueAsync(scac, "GALLAB", "COMP", token);
await repo.SetRequestedManualAsync(permit.Id, r.Locations, queueId, token);
await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
$"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: token);
if (scac == options.BadiyaScac)
{
if (!r.ReservedQueue) await repo.SetLastPermitAsync(r.Locations, permit.Id, token);
await repo.DeletePendingDistributionAsync(permit.Id, permit.Tn ?? string.Empty, null, token);
await repo.InsertDistributionLogAsync(permit.Id, r.Locations, orderDate, permit.Tn ?? string.Empty, "MANUAL_DEST", d?.CargoTypeCode, token);
}
return true;
}, ct);
var payload = new Dictionary<string, object?>
{
["TN"] = permit.Tn, ["PN"] = r.Pn, ["TT"] = order.Ct == GrainsCargo.BulkGallab ? d?.CargoType + " قلاب " : d?.CargoType,
["LOCATION"] = d?.Location, ["ORDERDATE"] = r.OrderDate, ["SHIFT"] = d?.MobileShift
};
var wrapper = new Dictionary<string, object?> { ["NOTIFICATIONARY"] = new[] { payload } };
await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS", wrapper, ct);
await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS_COMPANIES", wrapper, ct);
return PermitOperationResult.Ok("تم تحويل حالة السيارة إلى توزيع طلبية", permit.Id);
}
public async Task<PermitOperationResult> ProcessCompanyOpenPermitsAsync(CompanyOpenPermitsRequest r, CancellationToken ct = default)
{
new CompanyOpenPermitsValidator().ValidateAndThrow(r);
var open = await repo.GetOpenCompanyPermitsAsync(options.BadiyaScac, ct);
if (open.Count == 0) throw new BusinessException("NO_OPEN_PERMITS", "لا توجد سيارات على الدور لأي شركة");
var done = 0;
foreach (var p in open)
{
var order = await repo.GetAnyNextOrderAsync(ct);
if (order is null) break;
if (await repo.IsLocationAllowedForCompanyAsync(p.CompanyCode ?? 0, order.Destenation, ct))
{
await uow.ExecuteInTransactionAsync(async token =>
{
await repo.SetRequestedWithOrderAsync(p.Id, order.Id, token);
var d = await destinations.GetOrderDetailsAsync(order.Id, token);
await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
$"تحميل: {d?.Location} / {d?.CargoType}", ct: token);
return true;
}, ct);
done++;
if (done >= r.Count) break;
}
else
{
await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Open, PermitStatus.Open, PermitEventType.Override,
$"رقم السيارة {p.Tn} لم يتم توزيعة لعدم وجود موقع متوافق مع طلب الشركة", ct: ct);
}
}
return PermitOperationResult.Ok($"نم تحويل {done} من أصل {r.Count} سيارة الى توزيع طلبية");
}
public async Task<PermitOperationResult> DistributeSingleTruckAsync(string tn, CancellationToken ct = default)
{
var permit = await repo.GetFirstOpenPermitByTnAsync(tn.Trim(), null, ct)
?? throw new BusinessException("TN_INVALID", "TN is invalid");
await uow.ExecuteInTransactionAsync(async token =>
{
await repo.SetRequestedAsync(permit.Id, token);
await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token);
return true;
}, ct);
return PermitOperationResult.Ok("Done", permit.Id);
}
// ------------------------------------------------------------------------------------------------ grids / inquiries
public Task<IReadOnlyList<DistributionSummaryRow>> GetSummaryAsync(CancellationToken ct = default) => repo.GetDistributedSummaryAsync(ct);
public Task<IReadOnlyList<DistributionPivotRow>> GetPivotAsync(CancellationToken ct = default) => repo.GetDistributionPivotAsync(ct);
public async Task<TruckDistributionDto> SearchTruckAsync(string tn, CancellationToken ct = default)
{
tn = tn.Trim();
var result = new TruckDistributionDto();
var active = (await repo.GetTruckPermitStatusesAsync(tn, ct))
.Where(r => r.Status is PermitStatus.Accepted or PermitStatus.Released or PermitStatus.ArrivedControl).ToList();
if (active.Count == 0) result.ErrorMsg = "السيارة ليس لديها إرسالية فعالة";
result.Status = await repo.GetTruckLatestStatusCaptionAsync(tn, ct) ?? string.Empty;
var company = await repo.GetTruckLatestCompanyAsync(tn, ct);
IReadOnlyList<long> locations = company == options.BadiyaScac
? await destinations.GetTruckDestinationsAsync(tn, ct)
: company is long c ? await destinations.GetCompanyLocationsAsync(c, ct) : [];
var names = await repo.GetLocationNamesAsync(locations, ct);
result.CompanyLocations = string.Concat(names.Select(n => " - " + n.Name));
var orders = await repo.GetActiveOrdersInWindowAsync(new ShiftWindow
{
Shift1First = options.OperationShift1[0], Shift1Last = options.OperationShift1[1],
Shift2First = options.OperationShift2[0], Shift2Last = options.OperationShift2[1]
}, ct);
if (orders.Count > 0)
{
var destNames = await repo.GetLocationNamesAsync(orders.Select(o => o.Destenation).ToList(), ct);
result.Order = string.Concat(orders.Select(o => " / " + destNames.FirstOrDefault(n => n.Id == o.Destenation).Name));
}
else result.Order = "لا توجد طلبيات متاحة";
long tender = 0, trucks = 0;
foreach (var o in orders)
{
tender += o.Quantity;
trucks += await destinations.CountAssignedTrucksAsync(o.Id, ct);
}
result.TenderTotalQuantity = tender;
result.TrucksTotalQuantity = trucks;
if (trucks >= tender) result.ErrorMsg += "لا توجد وجهات متاحة لهذا الشفت، تم توزيع كامل عدد الطلبية";
return result;
}
public Task<IReadOnlyList<BlacklistedDistributionDto>> GetBlacklistedAsync(string tn, CancellationToken ct = default) =>
repo.GetBlacklistedDistributionsAsync(tn.Trim(), ct);
public async Task<PermitOperationResult> CheckTripsAsync(CheckTripsRequest r, CancellationToken ct = default)
{
var count = await repo.GetTripCountAsync(r.Tn.Trim(), ct);
if (r.MaxTnCount - count <= 0)
{
// legacy wrote this event twice; once is enough
await events.LogAsAsync("SYSTEM", null, r.PermitId, PermitStatus.Open, PermitStatus.Open, PermitEventType.Override,
$"لم يتم توزيع أي وجهة للسيارة رقم {r.Tn} لأن السيارة استنفذت عدد رحلاتها", ct: ct);
return PermitOperationResult.Fail("noTrip", "noTrip", r.PermitId);
}
return PermitOperationResult.Ok(string.Empty, r.PermitId);
}
public async Task<PermitOperationResult> RevokeAllRequestedAsync(long scrnBelow, CancellationToken ct = default)
{
if (scrnBelow <= 0) throw new ValidationException("حد رقم الطلبية غير صحيح");
var rows = await repo.GetRequestedPermitsBelowOrderAsync(scrnBelow, options.BadiyaScac, ct);
var count = 0;
foreach (var p in rows)
{
await uow.ExecuteInTransactionAsync(async token =>
{
await repo.ResetPermitToOpenAsync(p.Id, "SYSTEM", token);
await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Requested, PermitStatus.Open, PermitEventType.Override,
"SYSTEM REJECT - Old Permits", ct: token);
return true;
}, ct);
count++;
}
return PermitOperationResult.Ok($"تمت بنجاح ({count})");
}
public async Task<int> RevertUnloadedPermitsAsync(string actor, CancellationToken ct = default)
{
var rows = await repo.GetUnloadedPermitsAsync(options.OperationShift1[0], ct);
if (rows.Count == 0) return 0;
await uow.ExecuteInTransactionAsync(async token =>
{
await repo.SetStatusOpenAsync(rows.Select(r => r.Id).ToList(), token);
foreach (var r in rows)
await events.LogAsAsync(actor, null, r.Id, r.ShipmentStatusCode, null, PermitEventType.Override,
"تم تبويش هذه الارسالية بسبب تجاوز المهلة الزمنية الخاصة بالتحميل", ct: token);
return true;
}, ct);
return rows.Count;
}
// ------------------------------------------------------------------------------------------------ auto call
public async Task<PermitOperationResult> SendAutoCallFileAsync(AutoCallRequest r, CancellationToken ct = default)
{
// staff choose the company, company users are limited to their own (GrainsFactoryWeb.autoCallService2)
var company = user.IsCompany(options) ? user.CompanyCodeNo()?.ToString(CultureInfo.InvariantCulture) : r.CompanyCode;
var filter = r with { CompanyCode = company };
var tender = PermitService.ParseTenderOrder(r.TenderOrder);
var rows = await repo.GetCallingDriverRowsAsync(filter, tender, ct);
var ok = await autoCall.SendCallFileAsync(BuildCallingFile(rows), ct);
return ok
? PermitOperationResult.Ok(PermitOperationResult.DefaultOk, data: new Dictionary<string, object?> { ["rows"] = rows.Count })
: PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي");
}
public async Task<PermitOperationResult> TriggerIvrAsync(CancellationToken ct = default) =>
await autoCall.TriggerIvrAsync(ct)
? PermitOperationResult.Ok(PermitOperationResult.DefaultOk)
: PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي");
/// <summary>writeCallingDriverFile: CSV consumed by the auto dialer.</summary>
internal static byte[] BuildCallingFile(IReadOnlyList<AutoCallDriverRow> rows)
{
var sb = new StringBuilder();
sb.AppendLine("\"Name\",\"Phone\",\"Code1\",\"Code2\",\"Number1\",\"Number2\",\"Number3\",\"Number4\",\"Number5\",\"Item\",\"from\",\"origin\",\"Week\",\"Day\",\"Month\",\"DayNight\",\"ID\",\"Confirmation\",\"No\",\"status\"");
foreach (var r in rows)
{
var dayNight = r.MobileShift switch { 1 => "c:\\\\D.wav", 2 => "c:\\\\E.wav", 3 => "c:\\\\N.wav", _ => string.Empty };
string[] cols =
[
r.Name ?? "", r.Phone ?? "", r.Code1 ?? "", r.Code2 ?? "", r.Number1 ?? "", r.Number2 ?? "", r.Number3 ?? "", r.Number4 ?? "",
r.Number5 ?? "", r.Item ?? "", "C:\\\\GN.wav", r.Origin ?? "", r.Week ?? "", r.Day ?? "", r.Month ?? "", dayNight,
r.Id.ToString(CultureInfo.InvariantCulture), "", "", ""
];
sb.AppendLine(string.Join(',', cols.Select(c => "\"" + c.Replace("\"", "\"\"") + "\"")));
}
return new UTF8Encoding(false).GetBytes(sb.ToString());
}
public bool IsValidDialerApiKey(string? key) =>
!string.IsNullOrEmpty(options.AutoCall.ApiKey) && string.Equals(key, options.AutoCall.ApiKey, StringComparison.Ordinal);
/// <summary>autoCallResponse.cfc autoDail: CONFIRMED -> phone accept, POSTPONED -> phone reject for N days, NO_ANSWER -> postpone one day.</summary>
public async Task<AutoCallCallbackResult> HandleDialerCallbackAsync(AutoCallResponse r, CancellationToken ct = default)
{
const string ok = "SUCCESSFULL_OPERATION";
try
{
var permitId = string.IsNullOrWhiteSpace(r.ReferenceId) ? null : await repo.GetPermitIdByPnAsync(r.ReferenceId.Trim(), ct);
if (permitId is null) return new("200", ok);
var permit = await permits.GetAsync(permitId.Value, ct);
switch (r.Key)
{
case "CONFIRMED":
await permitService.PhoneAcceptCoreAsync(permitId.Value, null, "SYSTEM", ct);
break;
case "POSTPONED":
{
if (!int.TryParse(r.Value, out var days) || days <= 0) return new("500", "invalid value");
await permitService.PhoneRejectCoreAsync(permitId.Value, $" تم التأجيل {days} يوم", days, "SYSTEM", ct);
break;
}
case "NO_ANSWER":
{
if (await phoneRepo.HasPhoneEventTodayAsync(permitId.Value, ct)) return new("200", "ALREADY_HAS_PHONE_EVENT");
await NoAnswerAsync(permit!, ct);
return new("200", "NO_ANSWER");
}
}
return new("200", ok);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
return new("500", ex.Message);
}
}
private async Task NoAnswerAsync(PermitRow permit, CancellationToken ct)
{
var order = permit.Scrn is long o ? await destinations.GetOrderAsync(o, ct) : null;
var sh = options.DistributionShift(order?.Shift ?? 1);
await uow.ExecuteInTransactionAsync(async token =>
{
await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.NoAnswer,
"تم التأجيل ليوم واحد", ct: token);
await permits.ResetToOpenAsync(permit.Id, "SYSTEM", token);
await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, PermitStatus.Open, PermitEventType.Override, ct: token);
await phoneRepo.InsertBlacklistAsync(new NewBlacklistEntry
{
Category = "NO_ANSWER", EntityId = permit.Id, CreatedBy = "SYSTEM",
ExpiryDate = PhoneRejectRules.BlacklistExpiry(DateTime.Now, sh[0], sh[1], 1),
Remarks = "تم التأجيل ليوم واحد"
}, "SYSTEM", token);
return true;
}, ct);
}
}