Match legacy: blacklist shift, dialer callback parsing, trailer edit and revoke rules; record owner decisions

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-17 16:34:15 +03:00
parent 6d6ac06704
commit eaf52d53d9
10 changed files with 103 additions and 35 deletions

View File

@ -34,19 +34,11 @@ repository: everything a new person needs is in these two files, `docs/ENVIRONME
### 3.2 Role lists in code differ from the legacy action holders
Legacy holders (from the database): phone confirm 93 = GNSU, GOO, GTO, MOT, SU; cancel order 106 = GNSU, GOO, GPO, MOT, SU; cancel permit 167 = GTO, MOT; voice call 96 = GNAC, GNSU, GTO, MOT, SU; accept / reject / cancel-confirmation 74 / 85 / 88 = GNSU, GOO, GPO, GTO, MOT, SU. V2 uses the single list `GrainsRoles.Operators` (SU, GPO, GNSU, GNCO, GTO, CO), so GOO cannot confirm by phone or cancel an order, and the "staff" gate for accept / reject is "any non-company user" (includes GGO). Proposed: one explicit role list per action.
### 3.3 Review findings not yet fixed (from the legacy review of grains.cfc, register.cfc, autoCallResponse.cfc)
- Time zone of `DateTime.Now` expiry vs Oracle `SYSDATE` (container now Amman; verify).
- NO_ANSWER / blacklist expiry use the order's real shift; legacy always used shift 1 for typed numbers (confirm which is wanted).
- Dialer callback: strict string fields (400 on numeric JSON), no rate limit, replays duplicate blacklist rows (as in legacy).
- Company destinations save (Orders slice) deletes only PCKD / BULK / BULK_GALLAB locations; audit columns not written.
- `acceptDriver`: legacy never accepts (bug), V2 accepts; accepted drivers then disappear from the GOO grid.
- Trailer edit needs 2 attachments (stored + new), legacy effectively 1; revoke trailer always resets the truck to REGREQST.
- Not ported: company users' "registered count share/open" on the truck / trailer grids, head-type change log, Firebase push, QUED/TCS permit flow (its tables are missing on QA), the approvals-file import is a second copy of the phone logic and likely broken (SU-only; legacy button commented out).
- Production upload rules differ from legacy (legacy allowed xls / xlsx / zip, no size limit; V2 a fixed list, 10 MB).
- Performance: many queries use `TO_CHAR(pn)` / `TO_CHAR(tn)` on indexed number columns; measure a real distribution run (the command timeout is 30 s).
- Manual weighbridge entry + exit are not in one transaction; manual-input screen date list differs from legacy and assumes `GN_MANUAL_ORDER.id = GRAINSTENDERORDER.id` (unverified).
- Done-by column is still shown to company users (legacy hid it) - deliberately skipped so far.
- Used-orders count: the view `GN_USED_ORDER_BY_CATEGORY` may return several rows for PCKD; V2 sums them, legacy read the first row. Check the view's rows.
### 3.3 Review findings: owner decisions (2026-11-17)
Decided **to match legacy** (done): blacklist expiry uses shift 1 for a typed permit number and for NO_ANSWER (the real order shift only when a permit id is sent); the dialer callback accepts numbers or strings, any key case and any content type, and answers with the legacy keys `CODE` / `MSG`; trailer edit needs one document (stored or new); revoking a trailer resets its truck to REGREQST only when the revoke is made from the truck's page (trailer opened with `?truckId=`), and never a revoked truck.
Decided **to keep V2** (not open): `acceptDriver` accepts (legacy never did), upload rules (fixed extension list, 10 MB), `TO_CHAR(pn/tn)` comparisons, manual weighbridge entry+exit without an outer transaction, manual-input date list, done-by shown to company users, used-orders count summed.
Settled: time zone (container `TZ=Asia/Amman`, verified by the owner). No rate limit on the dialer callback; replays duplicate blacklist rows, as in legacy.
Still open / not ported: company destinations save (Orders slice) only deletes the locations the screen offers (PCKD / BULK / BULK_GALLAB) where legacy deleted every row of the company, and it writes only ID / SCAC / LOCATIONID where legacy also wrote date and user (check the production table's columns and NOT NULL flags: `select column_name, nullable from user_tab_columns where table_name='GRAINS_COMPANIES_LOCATION'`); company users' "registered count share/open" on the truck / trailer grids; head-type change log; Firebase push; QUED/TCS permit flow (tables missing on QA); the approvals-file import is a second copy of the phone logic and likely broken (SU-only, legacy button commented out).
### 3.4 Never tested against real data
Distribution runs, the IVR call, dialer callbacks, `SYSTEM_ERRORS` insert, the attachment folder in the container, the Amman time zone. Everything was verified only by build, unit tests, type check and read-only queries.

View File

@ -369,11 +369,26 @@ public sealed class PermitAutoCallController(IDistributionService distribution)
{
[HttpPost("callback")]
[AllowAnonymous]
public async Task<IActionResult> Callback(AutoCallResponse body, [FromHeader(Name = "X-Api-Key")] string? apiKey, CancellationToken ct)
public async Task<IActionResult> Callback([FromHeader(Name = "X-Api-Key")] string? apiKey, CancellationToken ct)
{
if (!distribution.IsValidDialerApiKey(apiKey)) return Unauthorized();
AutoCallResponse body;
try
{
// legacy: the raw body is read as UTF-8 JSON whatever the content type is
using var ms = new MemoryStream();
await Request.Body.CopyToAsync(ms, ct);
body = AutoCallResponse.FromJson(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
}
catch (Exception ex) when (ex is System.Text.Json.JsonException or FormatException)
{
return Ok(new Dictionary<string, string> { ["CODE"] = "500", ["MSG"] = ex.Message });
}
var r = await distribution.HandleDialerCallbackAsync(body, ct);
return Ok(new { code = r.Code, msg = r.Message });
// legacy answered with the struct keys CODE / MSG
return Ok(new Dictionary<string, string> { ["CODE"] = r.Code, ["MSG"] = r.Message });
}
}

View File

@ -126,7 +126,7 @@ public sealed class RegistryController(
[HttpPost("trailers/{id:long}/revoke")]
[RequirePermission(PermissionKeys.RegistryTrailers)]
public Task<RegistryResult> RevokeTrailer(long id, CancellationToken ct) => trailers.RevokeAsync(id, ct);
public Task<RegistryResult> RevokeTrailer(long id, [FromQuery] long? truckId, CancellationToken ct) => trailers.RevokeAsync(id, truckId, ct);
// ------------------------------------------------------------------------------------------ drivers (driverGrid.cfm, regesterDriver.cfm)

View File

@ -514,7 +514,9 @@ public sealed class DistributionService(
case "POSTPONED":
{
// the manual reject offers 1..30 days; anything larger is a dialer error (and AddDays would overflow)
if (!int.TryParse(r.Value, out var days) || days <= 0 || days > MaxPostponeDays) return new("500", "invalid value");
var days = 0;
if (!decimal.TryParse(r.Value, NumberStyles.Number, CultureInfo.InvariantCulture, out var dd) || (days = (int)dd) <= 0 || days > MaxPostponeDays)
return new("500", "invalid value");
await permitService.PhoneRejectCoreAsync(permitId.Value, $" تم التأجيل {days} يوم", days, "SYSTEM", ct);
break;
}
@ -539,8 +541,8 @@ public sealed class DistributionService(
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);
// legacy cleared SCRN before calling BL_addToBlacklist, so its shift lookup found no order and always used shift 1
var sh = options.DistributionShift(1);
await uow.ExecuteInTransactionAsync(async token =>
{
await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.NoAnswer,

View File

@ -613,6 +613,34 @@ public sealed class AutoCallDriverRow
}
/// <summary>Body of the dialer's callback (autoDail): referenceId = PN, key = CONFIRMED | POSTPONED | NO_ANSWER.</summary>
public sealed record AutoCallResponse(string? ReferenceId, string? Key, string? Value);
public sealed record AutoCallResponse(string? ReferenceId, string? Key, string? Value)
{
/// <summary>
/// autoCallResponse.cfc read the raw body as UTF-8 and deserialized it, so field names are case-insensitive and a number is as good as a
/// string (the provider may send referenceId or value as a JSON number). Throws <see cref="System.Text.Json.JsonException"/> on bad JSON.
/// </summary>
public static AutoCallResponse FromJson(string json)
{
using var doc = System.Text.Json.JsonDocument.Parse(json);
if (doc.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) throw new FormatException("The body is not a JSON object");
string? Get(string name)
{
foreach (var p in doc.RootElement.EnumerateObject())
{
if (!string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)) continue;
return p.Value.ValueKind switch
{
System.Text.Json.JsonValueKind.String => p.Value.GetString(),
System.Text.Json.JsonValueKind.Number => p.Value.GetRawText(),
System.Text.Json.JsonValueKind.True => "true",
System.Text.Json.JsonValueKind.False => "false",
_ => null
};
}
return null;
}
return new AutoCallResponse(Get("referenceId"), Get("key"), Get("value"));
}
}
public sealed record AutoCallCallbackResult(string Code, string Message);

View File

@ -54,8 +54,9 @@ public sealed class BlacklistService(
permitId = await repository.FindPermitIdByNumberAsync(number, ct)
?? throw new BusinessException(RegistryErrors.PermitNotFound, RegistryMessages.PermitNotFound(number));
entityId = permitId.ToString(CultureInfo.InvariantCulture);
// shift of the tender order of the permit (default 1)
shift = await repository.GetPermitShiftAsync(permitId, ct) ?? 1;
// Legacy BL_addToBlacklist looks the shift up with "p.id = ENTITYNUM": that matches only when the permit id itself was sent
// (IsId). A typed permit number never matches, so it always used shift 1.
if (request.IsId) shift = await repository.GetPermitShiftAsync(permitId, ct) ?? 1;
}
var (start, end) = settings.ShiftHours(shift);

View File

@ -12,7 +12,8 @@ public interface ITrailerRegistryService
Task<RegistryResult> CreateAsync(SaveTrailerRequest request, CancellationToken ct);
Task<RegistryResult> UpdateAsync(long id, SaveTrailerRequest request, CancellationToken ct);
Task<RegistryResult> AcceptAsync(long id, CancellationToken ct);
Task<RegistryResult> RevokeAsync(long id, CancellationToken ct);
/// <param name="truckId">The truck whose page the revoke was made from (legacy tnID); only then does the truck go back to REGREQST.</param>
Task<RegistryResult> RevokeAsync(long id, long? truckId, CancellationToken ct);
}
/// <summary>Port of register.cfc saveTrailerDetails / editTrailerDetails / getTrailerInfo / getTrailerGrid / revokeTrailer / acceptTrailer.</summary>
@ -131,8 +132,9 @@ public sealed class TrailerRegistryService(
var tempIds = await attachments.EnsureTempFilesAsync(request.AttachmentIds, ct);
var stored = (await attachments.ListAsync(RegistryAttachmentService.KindTrailer, id, ct)).Count;
// legacy editTrailer: at least 2 attached files (it counted only the files added in that session; stored files count here)
if (!RegistryRules.HasEnoughAttachments(tempIds.Count, stored))
// legacy editTrailer counted the child nodes of the file list, and a stored file already renders as several nodes, so in practice
// one document (stored or new) is enough on edit
if (!RegistryRules.HasEnoughAttachments(tempIds.Count, stored, required: 1))
throw new BusinessException(RegistryErrors.AttachmentsIncomplete, RegistryMessages.AttachmentsIncomplete);
var is327 = current.Tcscac == settings.BadiyaScac;
@ -169,7 +171,7 @@ public sealed class TrailerRegistryService(
return new RegistryResult(RegistryMessages.Accepted, id);
}
public async Task<RegistryResult> RevokeAsync(long id, CancellationToken ct)
public async Task<RegistryResult> RevokeAsync(long id, long? truckId, CancellationToken ct)
{
await access.RequireActionAsync(RegistryActions.RevokeTrailer, false, ct);
if (access.IsBadiyaCompany)
@ -183,8 +185,10 @@ public sealed class TrailerRegistryService(
await unitOfWork.ExecuteInTransactionAsync(async token =>
{
await repository.RevokeTrailerAsync(id, user.UserId, token);
// the truck goes back to "awaiting registration" (was INCOMP until 30 Dec 2020)
if (trailer.TnId is not null)
// Legacy revokeTrailer posts tnID only when the trailer page was opened from the truck page (the trailer grid opens it without),
// and only then does the truck go back to "awaiting registration" (was INCOMP until 30 Dec 2020).
// Kept stricter than legacy: it must be this trailer's own truck, and a revoked truck is not brought back.
if (truckId is not null && trailer.TnId == truckId)
{
var truck = await repository.GetTruckAsync(trailer.TnId.Value, token);
if (truck is not null && RegistryRules.CanRevoke(truck.StatusCode))

View File

@ -31,3 +31,28 @@ public class BlacklistRemarksTests
Assert.Equal(string.Empty, RegistryRules.FitBytes(null, 10));
}
}
public class DialerCallbackParsingTests
{
[Fact]
public void Strings_are_read_as_before()
{
var r = NTP.Application.Grains.Permits.AutoCallResponse.FromJson("{\"referenceId\":\"123456789\",\"key\":\"POSTPONED\",\"value\":\"3\"}");
Assert.Equal(("123456789", "POSTPONED", "3"), (r.ReferenceId, r.Key, r.Value));
}
[Fact]
public void Numbers_and_any_key_case_are_accepted_like_legacy()
{
var r = NTP.Application.Grains.Permits.AutoCallResponse.FromJson("{\"ReferenceID\":123456789,\"KEY\":\"POSTPONED\",\"Value\":3}");
Assert.Equal(("123456789", "POSTPONED", "3"), (r.ReferenceId, r.Key, r.Value));
}
[Fact]
public void Missing_fields_are_null_and_bad_json_throws()
{
var r = NTP.Application.Grains.Permits.AutoCallResponse.FromJson("{\"key\":\"NO_ANSWER\"}");
Assert.Null(r.ReferenceId);
Assert.ThrowsAny<System.Text.Json.JsonException>(() => NTP.Application.Grains.Permits.AutoCallResponse.FromJson("not json"));
}
}

View File

@ -109,7 +109,8 @@ export const useCreateTrailer = () =>
export const useUpdateTrailer = (id: number) =>
useWrite((p: Record<string, unknown>) => api.put<RegistryResult>(`${BASE}/trailers/${id}`, p), { invalidate: trailerKeys() });
export const useTrailerAction = () =>
useWrite((v: { id: number; action: 'accept' | 'revoke' }) => api.post<RegistryResult>(`${BASE}/trailers/${v.id}/${v.action}`), {
useWrite((v: { id: number; action: 'accept' | 'revoke'; truckId?: number | null }) =>
api.post<RegistryResult>(`${BASE}/trailers/${v.id}/${v.action}${v.action === 'revoke' && v.truckId ? `?truckId=${v.truckId}` : ''}`), {
invalidate: trailerKeys(),
});

View File

@ -226,12 +226,12 @@ export function TruckPage() {
<DestinationsPanel options={destOptions.data} value={dests} onChange={setDests} pending={t0?.pendingDestination} />
)}
</MetaForm>
{!isNew && t0 && <ConnectedTrailers rows={trailers.data ?? []} loading={trailers.isLoading} />}
{!isNew && t0 && <ConnectedTrailers rows={trailers.data ?? []} loading={trailers.isLoading} truckId={t0.id} />}
</Stack>
);
}
function ConnectedTrailers({ rows, loading }: { rows: TrailerRow[]; loading: boolean }) {
function ConnectedTrailers({ rows, loading, truckId }: { rows: TrailerRow[]; loading: boolean; truckId: number }) {
const { t, tr, lang } = useFeatureUi(strings);
const navigate = useNavigate();
const columns = useMemo(() => connectedTrailerColumns(), []);
@ -247,7 +247,7 @@ function ConnectedTrailers({ rows, loading }: { rows: TrailerRow[]; loading: boo
</TableHead>
<TableBody>
{rows.map((r) => (
<TableRow key={r.id} hover sx={{ cursor: 'pointer' }} onClick={() => navigate(`${ROOT}/trailers/${r.id}`)}>
<TableRow key={r.id} hover sx={{ cursor: 'pointer' }} onClick={() => navigate(`${ROOT}/trailers/${r.id}?truckId=${truckId}`)}>
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{r.tn}</TableCell>
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{r.chasesNumber}</TableCell>
<TableCell dir="ltr" sx={{ textAlign: 'start' }}>{formatDate(r.regDate, lang)}</TableCell>
@ -331,8 +331,8 @@ export function TrailerPage() {
setServerErrors({});
const { axialsKind: _kind, ...rest } = payload;
void _kind;
// legacy: two documents are needed when a Badiya trailer is registered, and on every edit at least two must exist afterwards
const needDocs = isNew ? (num(rest.tcscac) === BADIYA_SCAC ? 2 : 0) : 2;
// legacy: two documents are needed when a Badiya trailer is registered; on edit one document (stored or new) must exist
const needDocs = isNew ? (num(rest.tcscac) === BADIYA_SCAC ? 2 : 0) : 1;
if ((d?.attachments.length ?? 0) + pending.docs.length < needDocs) {
pending.setNeed(needDocs);
toast.warning(t('reg.docs.required', { n: needDocs }));
@ -367,7 +367,7 @@ export function TrailerPage() {
status={d.statusCode} busy={action.isPending}
canAccept={!!perms?.canAcceptTrailer} canRevoke={!!perms?.canRevokeTrailer && !perms.isBadiyaCompany}
onAccept={() => action.mutate({ id: d.id, action: 'accept' })}
onRevoke={() => action.mutate({ id: d.id, action: 'revoke' })}
onRevoke={() => action.mutate({ id: d.id, action: 'revoke', truckId })}
extra={d.truckId && (
<Button variant="outlined" onClick={() => navigate(`${ROOT}/trucks/${d.truckId}`)}>{t('reg.trailers.openTruck')}</Button>
)}