Jobs, OneSignal push, registrar, receipts, GN communication, report loading card

- OneSignal push ported from MobileNotification.cfc (REST, MOBILENOTIFICATIONSLOG)
- Jobs: refinery-oil-sync, refinery-daily-exchange-report, josilos-integration (built-in SMTP mail service; all off until configured)
- Registrar (التسجيل العام): driver / truck / trailer licences from the mobile app (GOO screens, reports SU only), push on confirm / reject
- Receipts (سندات القبض والمطالبات المالية): list, create, confirm, paid, cancel flow, print, Excel, audit, log
- GN communication (شاشة موظف الاتصالات): answers grid, blacklist action, Excel
- Blocking "generating the report" card for all Excel downloads; MetaForm onFieldChange hook
- Menu captions: تسجيل التموين, التسجيل العام; compact scheduled jobs cards
- db/registrar-, receipts-, communication-permissions.sql; docs updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Samer Salameh 2026-11-25 10:44:14 +03:00
parent 31771e3c73
commit 28e629ccac
72 changed files with 7482 additions and 87 deletions

View File

@ -0,0 +1,13 @@
-- Voice communication screen (شاشة موظف الاتصالات, legacy AqabaTCS entity GN_COMMUNICATION). Primary (NAFITHTCS) schema. Safe to re-run; not run by the app.
-- Legacy STATUS_ACTION_MATRIX: SEARCH / VIEW and ADD_PERMIT_GN_BLACKLIST are GTO and SU, REPORT is SU only (SU needs no rows).
-- grains.communication the screen
-- grains.communication.blacklist stop the postponement of the permits that did not answer
-- grains.communication.report Excel (SU only: no rows)
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
SELECT v.rolecode, v.resource_key
FROM (SELECT 'GTO' AS rolecode, 'grains.communication' AS resource_key FROM dual UNION ALL
SELECT 'GTO', 'grains.communication.blacklist' FROM dual) v
WHERE NOT EXISTS (SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p WHERE p.ROLECODE = v.rolecode AND p.RESOURCE_KEY = v.resource_key);
COMMIT;

View File

@ -0,0 +1,56 @@
-- Permit receipts (سندات القبض والمطالبات المالية): legacy AqabaTCS entity PERMITSRECEIPTS. Translates the ACTIVE rows of the legacy
-- STATUS_ACTION_MATRIX (NTP schema) into GRAINS_SCREEN_PERMISSIONS keys. Primary (NAFITHTCS) schema. Safe to re-run; not run by the app. SU needs no rows.
--
-- receipts the list and the receipt page (SEARCH / VIEW): AC, AM, QUEUE_OP, SAP, TENDER_SUP, YM
-- receipts.create CREATE: QUEUE_OP, TENDER_SUP
-- receipts.confirm CONFIRM: QUEUE_OP, SAP, TENDER_SUP (NOT_RECEIVED -> RECEIVED)
-- receipts.update UPDATE: TENDER_SUP (RECEIVED / UNPAID)
-- receipts.paid PAID: QUEUE_OP, SAP, TENDER_SUP (UNPAID -> PAID + a cash receipt)
-- receipts.print PRINT: QUEUE_OP, SAP, TENDER_SUP
-- receipts.revokeRequest REVOKE to PENDING_RVKD: QUEUE_OP (and SU) (RECEIVED / UNPAID, waits for approval)
-- receipts.revoke REVOKE to RVKD: TENDER_SUP (RECEIVED / UNPAID)
-- receipts.revokeAudited REVOKE AUDITED: SAP, TENDER_SUP
-- receipts.acceptRevoke / receipts.rejectRevoke: TENDER_SUP (PENDING_RVKD)
-- receipts.audit AUDIT / FIN_AUDIT: AM, SAP, TENDER_SUP (AC has the legacy AUDIT row but the legacy code has no status list for it: it failed, so it gets no key)
-- receipts.report REPORT: AC, AM, QUEUE_OP, SAP, TENDER_SUP
-- Generated 2026-11-25; change a row to change who may do what.
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
SELECT v.rolecode, v.resource_key
FROM (
SELECT 'AC' AS rolecode, 'receipts' AS resource_key FROM dual UNION ALL
SELECT 'AM' AS rolecode, 'receipts' AS resource_key FROM dual UNION ALL
SELECT 'QUEUE_OP' AS rolecode, 'receipts' AS resource_key FROM dual UNION ALL
SELECT 'SAP' AS rolecode, 'receipts' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts' AS resource_key FROM dual UNION ALL
SELECT 'YM' AS rolecode, 'receipts' AS resource_key FROM dual UNION ALL
SELECT 'QUEUE_OP' AS rolecode, 'receipts.create' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.create' AS resource_key FROM dual UNION ALL
SELECT 'QUEUE_OP' AS rolecode, 'receipts.confirm' AS resource_key FROM dual UNION ALL
SELECT 'SAP' AS rolecode, 'receipts.confirm' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.confirm' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.update' AS resource_key FROM dual UNION ALL
SELECT 'QUEUE_OP' AS rolecode, 'receipts.paid' AS resource_key FROM dual UNION ALL
SELECT 'SAP' AS rolecode, 'receipts.paid' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.paid' AS resource_key FROM dual UNION ALL
SELECT 'QUEUE_OP' AS rolecode, 'receipts.print' AS resource_key FROM dual UNION ALL
SELECT 'SAP' AS rolecode, 'receipts.print' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.print' AS resource_key FROM dual UNION ALL
SELECT 'QUEUE_OP' AS rolecode, 'receipts.revokeRequest' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.revoke' AS resource_key FROM dual UNION ALL
SELECT 'SAP' AS rolecode, 'receipts.revokeAudited' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.revokeAudited' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.acceptRevoke' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.rejectRevoke' AS resource_key FROM dual UNION ALL
SELECT 'AM' AS rolecode, 'receipts.audit' AS resource_key FROM dual UNION ALL
SELECT 'SAP' AS rolecode, 'receipts.audit' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.audit' AS resource_key FROM dual UNION ALL
SELECT 'AC' AS rolecode, 'receipts.report' AS resource_key FROM dual UNION ALL
SELECT 'AM' AS rolecode, 'receipts.report' AS resource_key FROM dual UNION ALL
SELECT 'QUEUE_OP' AS rolecode, 'receipts.report' AS resource_key FROM dual UNION ALL
SELECT 'SAP' AS rolecode, 'receipts.report' AS resource_key FROM dual UNION ALL
SELECT 'TENDER_SUP' AS rolecode, 'receipts.report' AS resource_key FROM dual
) v
WHERE NOT EXISTS (SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p WHERE p.ROLECODE = v.rolecode AND p.RESOURCE_KEY = v.resource_key);
COMMIT;

View File

@ -0,0 +1,29 @@
-- Registrar (التسجيل العام): review of the trucks, trailers and drivers registered from the mobile app (legacy AqabaTCS entities
-- TRUCKINFO / TRAILERINFO / DRIVERINFO). Owner decision: only role GOO sees the screens; the Excel reports (registrar.<kind>.report) are for SU only
-- (SU needs no rows), so no report rows are written. Within GOO the legacy STATUS_ACTION_MATRIX still decides which actions exist:
-- GOO may update PENDING records and confirm / reject drivers and trailers (not trucks); reopen needs no GOO row in the legacy matrix.
-- Primary (NAFITHTCS) schema. Safe to re-run; not run by the app.
--
-- registrar.<kind> screen; kind = drivers | trucks | trailers
-- registrar.<kind>.update UPDATE of a PENDING record
-- registrar.<kind>.complete PENDING -> COMPLETED (drivers, trailers)
-- registrar.<kind>.revoke PENDING -> REVOKE (drivers, trailers)
-- To give another role access, copy the rows with its code (legacy holders of each action are listed in docs/HANDOVER.md).
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
SELECT v.rolecode, v.resource_key
FROM (
SELECT 'GOO' AS rolecode, 'registrar.drivers' AS resource_key FROM dual UNION ALL
SELECT 'GOO' AS rolecode, 'registrar.drivers.update' AS resource_key FROM dual UNION ALL
SELECT 'GOO' AS rolecode, 'registrar.drivers.complete' AS resource_key FROM dual UNION ALL
SELECT 'GOO' AS rolecode, 'registrar.drivers.revoke' AS resource_key FROM dual UNION ALL
SELECT 'GOO' AS rolecode, 'registrar.trucks' AS resource_key FROM dual UNION ALL
SELECT 'GOO' AS rolecode, 'registrar.trucks.update' AS resource_key FROM dual UNION ALL
SELECT 'GOO' AS rolecode, 'registrar.trailers' AS resource_key FROM dual UNION ALL
SELECT 'GOO' AS rolecode, 'registrar.trailers.update' AS resource_key FROM dual UNION ALL
SELECT 'GOO' AS rolecode, 'registrar.trailers.complete' AS resource_key FROM dual UNION ALL
SELECT 'GOO' AS rolecode, 'registrar.trailers.revoke' AS resource_key FROM dual
) v
WHERE NOT EXISTS (SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p WHERE p.ROLECODE = v.rolecode AND p.RESOURCE_KEY = v.resource_key);
COMMIT;

View File

@ -34,7 +34,12 @@ Set these in the server's environment (IIS application settings, a Windows servi
| `Jwt__Key` | JWT signing key, at least 32 random characters. The app refuses to start outside Development without it | | `Jwt__Key` | JWT signing key, at least 32 random characters. The app refuses to start outside Development without it |
| `Cors__AllowedOrigins__0` | Origin of the web app, e.g. `https://<web-host>`. Replaces the placeholder in the settings file; until it is set no browser origin is allowed | | `Cors__AllowedOrigins__0` | Origin of the web app, e.g. `https://<web-host>`. Replaces the placeholder in the settings file; until it is set no browser origin is allowed |
| `Auth__SuperUsers__0`, `__1` ... | Logins that may hold role `SU`. Empty in production by default; QA lists its own in `appsettings.QA.json` | | `Auth__SuperUsers__0`, `__1` ... | Logins that may hold role `SU`. Empty in production by default; QA lists its own in `appsettings.QA.json` |
| `Grains__Permits__Notifications__Sms__UserName`, `__Password` | SMS provider account (production only; secret). Notification settings: `Grains:Permits:Notifications` (Enabled, PushUrl, SendSmsToOwnersWithoutApp = legacy SEND_SMS_GN_DIST, Sms:Enabled/Provider). Development: off; QA: push on, SMS off; production: push on, SMS on | | `Mail__Enabled`, `Mail__Host`, `Mail__Port`, `Mail__UseSsl`, `Mail__From`, `Mail__UserName`, `Mail__Password` | SMTP server for the e-mails of the jobs (legacy cfmail). Off by default; `UserName` / `Password` are secrets |
| `Refinery__Jobs__DailyReportRecipients__0` ..., `Refinery__Jobs__CancelledTripRecipients__0` ... | Receivers of the daily refinery exchange report (legacy application.REFINERY_EMAIL) and of the "crude oil trip cancelled" mail |
| `Refinery__Jobs__JopetrolWriteBack` | `true` on production only: lets the job "مزامنة ارساليات النفط الخام" change statuses at Jopetrol (UpdateStatusTo1 / UpdateStatusToMinus2), as the legacy job did only on the live server. `Refinery__Jopetrol__Enabled/UserName/Password` must be set too |
| `ExternalIntegration__JoSilos__Enabled` (+ `SilosUrl`, `AqabaSilosUrl`) | Job "ارسال التصاريح الى JoSilos". Off by default; the two URLs are in appsettings.json |
| `Grains__Permits__Notifications__OneSignal__AppId`, `__ApiKey`, `__AndroidChannelId` | OneSignal account of the mobile app for the push (production and QA; `ApiKey` is secret). The values are the ones the legacy `MobileNotification.cfc` (SendNotificationToOneSignal) uses. Without AppId and ApiKey no push is sent (one warning in the API log) |
| `Grains__Permits__Notifications__Sms__UserName`, `__Password` | SMS provider account (production only; secret). Notification settings: `Grains:Permits:Notifications` (Enabled, OneSignal, SendSmsToOwnersWithoutApp = legacy SEND_SMS_GN_DIST, Sms:Enabled/Provider). Development: off; QA: push on, SMS off; production: push on, SMS on |
Connection string shape (values are examples only): Connection string shape (values are examples only):
`User Id=<schema>;Password=<secret>;Data Source=<host>:1521/<service>;Min Pool Size=1;Max Pool Size=50;Connection Timeout=15;Statement Cache Size=50` `User Id=<schema>;Password=<secret>;Data Source=<host>:1521/<service>;Min Pool Size=1;Max Pool Size=50;Connection Timeout=15;Statement Cache Size=50`
@ -60,6 +65,9 @@ Apply these scripts once per database (not run by the application), in this orde
6. `db/gnac-finance-screens.sql` - GNAC gets claims, fines, wages, invoices and the invoice check report (safe to re-run) 6. `db/gnac-finance-screens.sql` - GNAC gets claims, fines, wages, invoices and the invoice check report (safe to re-run)
8. `db/refinery-permissions.sql` - refinery (المصفاة) modules: REFINERY_MGR gets the 6 screens and every action key (47 rows); SU needs none (safe to re-run). The external services are OFF until configured: `Refinery__Dinarak__Enabled/BaseUrl/UserName/Password` (trip payment) and `Refinery__Jopetrol__Enabled/Url/UserName/Password` (wage claim ترحيل); `Refinery__Trips__MaxPaymentAmount` (default 500, unverified) 8. `db/refinery-permissions.sql` - refinery (المصفاة) modules: REFINERY_MGR gets the 6 screens and every action key (47 rows); SU needs none (safe to re-run). The external services are OFF until configured: `Refinery__Dinarak__Enabled/BaseUrl/UserName/Password` (trip payment) and `Refinery__Jopetrol__Enabled/Url/UserName/Password` (wage claim ترحيل); `Refinery__Trips__MaxPaymentAmount` (default 500, unverified)
9. `db/refinery-op-permissions.sql` - role REFINERY_OP (موظف عطاء الصرف): the الارساليات screen, the شحن الديزل (Excel) report, print and the payment actions (13 keys); part 1 (role row, NTP schema) is only needed where the row is missing, part 2 (primary schema) writes the rows (safe to re-run). Everything else of the refinery module stays with REFINERY_MGR and SU 9. `db/refinery-op-permissions.sql` - role REFINERY_OP (موظف عطاء الصرف): the الارساليات screen, the شحن الديزل (Excel) report, print and the payment actions (13 keys); part 1 (role row, NTP schema) is only needed where the row is missing, part 2 (primary schema) writes the rows (safe to re-run). Everything else of the refinery module stays with REFINERY_MGR and SU
10. `db/registrar-permissions.sql` - registrar (التسجيل العام: رخص السائقين / الشاحنات / المقطورات): screens and edit / confirm / reject keys for role GOO only, reports SU only (10 rows); SU needs none (safe to re-run). Setting `Registrar__AttachmentsBaseUrl` (default: the legacy upload host, where the pictures stay)
11. `db/receipts-permissions.sql` - permit receipts (سندات القبض والمطالبات المالية): screen and action keys `receipts.*` from the legacy STATUS_ACTION_MATRIX (32 rows); SU needs none (safe to re-run)
12. `db/communication-permissions.sql` - voice communication screen (شاشة موظف الاتصالات): GTO gets the screen and the blacklist action, the Excel report is SU only (safe to re-run). Setting `Grains__Communication__AutoPostponeMinutes` (default 30, unverified)
**Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU **Switching a feature off for everybody:** a row with `ROLECODE = 'DISABLED'` takes that resource out of the system for all users, SU
included: the menu entry and buttons disappear and the API answers 403. It overrides every other row. Delete the row to bring the included: the menu entry and buttons disappear and the API answers 403. It overrides every other row. Delete the row to bring the

View File

@ -23,7 +23,7 @@ repository: everything a new person needs is in these two files, `docs/ENVIRONME
4. `Grains:Registry:UploadedFilesPath` must be a plain path (`/mnt/NTPFiles`), never a `host:container` mapping. 4. `Grains:Registry:UploadedFilesPath` must be a plain path (`/mnt/NTPFiles`), never a `host:container` mapping.
5. `appsettings.Production.json` sets: attachment paths, `Grains:Permits:AutoCall` (enabled, IVR WSDL address), ownership code lists (`BadiyaOwnershipCodes 3,2`, `OtherOwnershipCodes 1,2` - confirm against production `SYSTEM_VARIABLES`). 5. `appsettings.Production.json` sets: attachment paths, `Grains:Permits:AutoCall` (enabled, IVR WSDL address), ownership code lists (`BadiyaOwnershipCodes 3,2`, `OtherOwnershipCodes 1,2` - confirm against production `SYSTEM_VARIABLES`).
6. The provider of the dialer must call `/api/v1/grains/permit-autocall/callback` with header `X-Api-Key`; nothing in the repo repoints it. 6. The provider of the dialer must call `/api/v1/grains/permit-autocall/callback` with header `X-Api-Key`; nothing in the repo repoints it.
7. Mobile notifications are ported (see 3.5): production pushes through the legacy web service `http://aqtcs.nafith.net/backend/common/MobileNotification.cfc` and sends the SMS for owners without the app (`SEND_SMS_GN_DIST` = 1). Put the SMS account in the server `.env`: `Grains__Permits__Notifications__Sms__UserName` and `__Password` (until then the SMS is skipped with a warning). Provider `JORMALL` is a guess (the AqabaTCS app uses it): confirm which provider NTP used (`application.SMS_PROVIDER`). 7. Mobile notifications are ported (see 3.5): production pushes straight to the OneSignal REST API (account in the server `.env`: `Grains__Permits__Notifications__OneSignal__AppId`, `__ApiKey`, `__AndroidChannelId`; the legacy web service is no longer called) and sends the SMS for owners without the app (`SEND_SMS_GN_DIST` = 1). Put the SMS account in the server `.env`: `Grains__Permits__Notifications__Sms__UserName` and `__Password` (until then the SMS is skipped with a warning). Provider `JORMALL` is a guess (the AqabaTCS app uses it): confirm which provider NTP used (`application.SMS_PROVIDER`).
8. The NTP database user needs INSERT on `SYSTEM_ERRORS` and SELECT on `SEQ_SYSTEM_ERRORS`, otherwise error logging only writes a warning to the API log. 8. The NTP database user needs INSERT on `SYSTEM_ERRORS` and SELECT on `SEQ_SYSTEM_ERRORS`, otherwise error logging only writes a warning to the API log.
9. After deploy: `docker exec ntpv2-prod date` (Amman time), `/health/ready`, sign in, open a truck attachment, click الاتصال الصوتي once (it really dials every requested truck: do not test casually). 9. After deploy: `docker exec ntpv2-prod date` (Amman time), `/health/ready`, sign in, open a truck attachment, click الاتصال الصوتي once (it really dials every requested truck: do not test casually).
10. Database scripts: see docs/ENVIRONMENTS.md ("Database objects"). They are applied by hand; which ones ran on which environment is not recorded: check the tables before re-running (all are safe to re-run). 10. Database scripts: see docs/ENVIRONMENTS.md ("Database objects"). They are applied by hand; which ones ran on which environment is not recorded: check the tables before re-running (all are safe to re-run).
@ -58,6 +58,28 @@ Screen rights per role: `select rolecode, count(*) from grains_screen_permission
Ownership lists: `select name, value from system_variables where upper(name) like '%OWNERSHIP%'`. Ownership lists: `select name, value from system_variables where upper(name) like '%OWNERSHIP%'`.
### 3.5 Mobile notifications (ported from components/MobileNotifications.cfc) ### 3.5 Mobile notifications (ported from components/MobileNotifications.cfc)
Flow per template (CONFIRM_PN, PHONE_REJECT, DELAY_PN, DISTRIBUTE_PACKED_BULK_OWNERS / _OWNERS_COMPANIES / _COMP): find the app users (driver DRVR and owner TRKOWNER by the truck phone, dispatchers DISP by company login), read their ACTIVE devices (USERDEVICEINFO), fill the NOTIFICATIONMESSAGETEMPLATE text (VAR1..VARn, first occurrence only, as ColdFusion Replace), call SendFromCF9 of the legacy push web service (it sends the OneSignal push and writes MOBILENOTIFICATIONSLOG). It runs in the background in its own scope (legacy used a thread); a failure only goes to the API log and SYSTEM_ERRORS. Owners distribution: an account with no active device gets an SMS with the app link when SendSmsToOwnersWithoutApp (legacy SEND_SMS_GN_DIST) is on, logged in USER_SMS_LOGS. Same legacy quirk: no account for the phone = no SMS. Flow per template (CONFIRM_PN, PHONE_REJECT, DELAY_PN, DISTRIBUTE_PACKED_BULK_OWNERS / _OWNERS_COMPANIES / _COMP): find the app users (driver DRVR and owner TRKOWNER by the truck phone, dispatchers DISP by company login), read their ACTIVE devices (USERDEVICEINFO), fill the NOTIFICATIONMESSAGETEMPLATE text (VAR1..VARn, first occurrence only, as ColdFusion Replace), send the OneSignal push (legacy SendNotificationToOneSignal: Android with channel, iOS with the app sound; template id in `data`) and write MOBILENOTIFICATIONSLOG (SUCCESS / FAILURE, SOURCE_FROM = NTPV2). It runs in the background in its own scope (legacy used a thread); a failure only goes to the API log and SYSTEM_ERRORS. Owners distribution: an account with no active device gets an SMS with the app link when SendSmsToOwnersWithoutApp (legacy SEND_SMS_GN_DIST) is on, logged in USER_SMS_LOGS. Same legacy quirk: no account for the phone = no SMS.
The SQL was checked read-only on the QA database (all 7 templates exist). **Not tested end to end**: no real push or SMS was sent, and the SOAP envelope for SendFromCF9 was built from its WSDL, not captured from legacy. Difference: the SMS log status is the real HTTP result (legacy always wrote SUCCESS). Still not ported: the push of addPhoneAcceptEvent (phone approval import) and the tender-order publishMobile switch. The legacy files hold the old Firebase and SMS provider keys in clear text (MobileNotifications.cfc, SMS.cfc): rotate them. The SQL was checked read-only on the QA database (all 7 templates exist). **Not tested end to end**: no real push or SMS was sent, and the OneSignal request was ported from the legacy code, not captured from a real send; the old Firebase fallback after a OneSignal error is not ported. Difference: the SMS log status is the real HTTP result (legacy always wrote SUCCESS). Still not ported: the push of addPhoneAcceptEvent (phone approval import) and the tender-order publishMobile switch. The legacy files hold the old Firebase and SMS provider keys in clear text (MobileNotifications.cfc, SMS.cfc): rotate them.
### Jobs ported from AqabaTCS (refinery and JoSilos)
Three more entries in the job catalog (screen /jobs, SU): `refinery-oil-sync` (jobs/REFINERY_OIL.cfm: Jopetrol QueryOnTransByStatus -1..6 -> REFINERY_TRIPS insert / update, status 0 -> UpdateStatusTo1, -1 -> UpdateStatusToMinus2 + mail; the two status-changing calls only with `Refinery:Jobs:JopetrolWriteBack`), `refinery-daily-exchange-report` (jobs/RefineryTrip_Exchange_email.cfm: daily mail, needs the `Mail` section and `Refinery:Jobs:DailyReportRecipients`) and `josilos-integration` (jobs/ExternalIntegrationJoSilos.cfm: old silos service once per permit + new Aqaba silos service until RECEIVED, log in EXTERNAL_INTEGRATION_QUEUE_LOG; `ExternalIntegration:JoSilos:Enabled`). All three are off until configured. Not tested against the real services (QA SELECTs of the permit queries only). Differences: the JoSilos JSON is built with real escaping (legacy concatenated strings); the cancel mail recipient is configuration (legacy hard-coded one address); the daily mail amounts use one thousands format; the sync logs a trip as a JSON of the Jopetrol fields (legacy logged a ColdFusion query JSON); CREATED_BY / UPDATED_BY keep the legacy value 16186973 (setting `Refinery:Jobs:SyncUser`).
### Registrar (نظام التسجيل): driver, truck and trailer licences from the mobile app (ported from AqabaTCS entities driverinfo / truckinfo / trailerinfo)
Menu group "نظام التسجيل" with رخص السائقين / الشاحنات / المقطورات (`/registrar/drivers|trucks|trailers`, `src/NTP.Application/Registrar`, `web/src/features/registrar`). The registrar opens the records the companies registered in the app (DRIVERS_INFO / TRUCKS_INFO / TRAILERS_INFO, status PENDING first), edits them, and confirms (PENDING -> COMPLETED), rejects with a reason (PENDING -> REVOKE) or sends a COMPLETED one back to review. A push goes to the user who registered it (legacy REGISTRATION template, via the OneSignal gateway). Excel per screen in the legacy column layout.
- **Permissions**: the legacy STATUS_ACTION_MATRIX decides by role AND status, so there is one key per transition (`registrar.<kind>`, `.update`, `.updateCompleted` (drivers: COMPLETED), `.complete`, `.revoke`, `.reopen`, `.report`); `db/registrar-permissions.sql` (10 rows) gives the screens to role GOO only (owner decision 2026-11-25, menu group "التسجيل العام"); the Excel reports are SU only (no rows); trucks can only be edited by GOO, confirming / rejecting / reopening a truck needs SU (the legacy matrix has no GOO row for it). Other roles: copy the rows with their code.
- **Rules kept**: Jordanian registrations need the whole form, foreign ones only the short list (legacy `*_excludedVaildFieldsArr`); driver: Arabic or English name, letters only, issue date not after the expiry; year / weights digits only; a Jordanian chassis number (VIN) may be used by one non-revoked truck or trailer only (truck checks trailers then trucks, trailer the reverse); confirming validates the stored data (the legacy screen validated the form before COMPLETE).
- **Differences**: an empty optional field is now cleared on save (legacy DAO skipped empty values, so a field could never be emptied); only one date bound in the filter is applied (legacy needed both); the status filter is one status or all (chips), the API still accepts a list.
- **Pictures** stay on the legacy upload host (`Registrar:AttachmentsBaseUrl`, legacy `application.aqTcsUploadedPath`); the API fetches and streams them (the page's CSP only allows own images). If that host is not reachable from the V2 server the pictures show "could not be loaded".
- **Not tested**: the screens were not opened in a browser (no sign-in available in the pane) and the UPDATE statements were not run (only the SELECTs, against QA); nothing was run against production data.
### Permit receipts (سندات القبض والمطالبات المالية, ported from AqabaTCS entity permitsreceipts)
Menu entry `/receipts` (`src/NTP.Application/Receipts`, `web/src/features/receipts`): list with the legacy filters, receipt page with log, create (company 327), edit (RECEIVED / UNPAID), confirm (NOT_RECEIVED -> RECEIVED), paid (UNPAID -> PAID + a new cash receipt), cancel (QUEUE_OP / SU ask: PENDING_RVKD; TENDER_SUP cancels at once; AUDITED by SAP / TENDER_SUP) with accept / reject, print (A5 PDF made in the browser, zero-fee receipts refused), Excel, and the audit (upload of the permits `.xlsx`, comparison with the receipts of a user / period, matching ones move to AUDITED, or COMPLETED for AM, result workbook downloaded). Every status change writes LOG_PERMITS_RECEIPTS like the legacy saveLog.
- **Permissions**: `db/receipts-permissions.sql` (32 rows) from the legacy STATUS_ACTION_MATRIX; keys `receipts`, `.create`, `.confirm`, `.update`, `.paid`, `.print`, `.revokeRequest`, `.revoke`, `.revokeAudited`, `.acceptRevoke`, `.rejectRevoke`, `.audit`, `.report`. AC has the legacy AUDIT row but the legacy code failed for it (no status list), so it gets no audit key.
- **Differences**: create is offered for company 327 only (326 has no receipt types in the data); a double move takes the first and second cargo type in two fields (legacy typed "FM-SM"); SU asks for a cancellation like QUEUE_OP (the legacy DAO cancelled at once for SU although its check and log said PENDING_RVKD); the legacy GNPN field (not a column) is only a hint; audit reads `.xlsx` only (legacy also read `.xls`), header on the 3rd row as legacy; the legacy audit result file was written to the server, here it is the download; the printed slip is drawn in the page (barcode of the receipt number).
- **Not tested**: screens not opened in a browser (no sign-in), INSERT / UPDATE statements and the PERMITS-based checks (types 8, 9, 10) not run, audit not run against a real file; the SELECTs were run on QA.
### Voice communication screen (شاشة موظف الاتصالات, ported from AqabaTCS entity gn_communication)
Menu entry "نظام الاتصال الصوتي" (`/grains/communication`, `src/NTP.Application/Grains/Communication`, `web/src/features/grains-communication`): the permits distributed in the last 30 days (TRUCK_DISTRIBUTION_LOG_VIEW) with the owner's answer (confirmed / postponed / no reply + minutes left), filters as the legacy screen, opens on "no reply". The action "إضافة على قائمة المنع" marks the unanswered permits of company 327 as blocked (TRUCK_DISTRIBUTION_LOG.ISBLOCKED = 1) and sends the push BLOCKED_DISTRIBUTED_PERMIT_OWNERS to the drivers and owners of those trucks. Keys `grains.communication`, `.blacklist` (GTO, `db/communication-permissions.sql`), `.report` (Excel, SU only).
- **Unverified**: the legacy `application.AUTO_POSTPONE_PERIOD` (minutes to answer) is not in the legacy code; `Grains:Communication:AutoPostponeMinutes` defaults to 30, set the real value. The legacy action also had its blacklist insert commented out (only the marking is done), kept as is.
- **Not tested**: screen not opened in a browser; the UPDATE and the push were not run (the view SELECT was).

View File

@ -0,0 +1,42 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using NTP.Api.Authorization;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Grains.Communication;
namespace NTP.Api.Controllers.V1.Grains;
/// <summary>Voice communication screen (شاشة موظف الاتصالات): port of gn_communication.</summary>
[ApiController]
[ApiVersion(1.0)]
[Route("api/v{version:apiVersion}/grains/communication")]
[Produces("application/json")]
[RequirePermission(PermissionKeys.Communication)]
public sealed class CommunicationController(ICommunicationService communication) : ControllerBase
{
private static CommunicationQuery Query(string? tn, string? pn, string? cargoTypeCode, string? statusCode, string? shift, string? isBlocked, DateTime? orderDateFrom, DateTime? orderDateTo) =>
new(tn, pn, cargoTypeCode, statusCode, shift, isBlocked, orderDateFrom, orderDateTo);
[HttpGet]
public Task<PagedResult<CommunicationItem>> Search([FromQuery] string? tn, [FromQuery] string? pn, [FromQuery] string? cargoTypeCode, [FromQuery] string? statusCode,
[FromQuery] string? shift, [FromQuery] string? isBlocked, [FromQuery] DateTime? orderDateFrom, [FromQuery] DateTime? orderDateTo,
[FromQuery] int page = 1, [FromQuery] int pageSize = 16, CancellationToken ct = default) =>
communication.SearchAsync(Query(tn, pn, cargoTypeCode, statusCode, shift, isBlocked, orderDateFrom, orderDateTo), new PageRequest(page, pageSize), ct);
[HttpGet("export")]
public async Task<IActionResult> Export([FromQuery] string? tn, [FromQuery] string? pn, [FromQuery] string? cargoTypeCode, [FromQuery] string? statusCode,
[FromQuery] string? shift, [FromQuery] string? isBlocked, [FromQuery] DateTime? orderDateFrom, [FromQuery] DateTime? orderDateTo, CancellationToken ct)
{
var f = await communication.ExportAsync(Query(tn, pn, cargoTypeCode, statusCode, shift, isBlocked, orderDateFrom, orderDateTo), ct);
return File(f.Content, f.ContentType, f.FileName);
}
/// <summary>Cargo types of the order filter.</summary>
[HttpGet("cargo-types")]
public Task<IReadOnlyList<CargoOption>> CargoTypes(CancellationToken ct) => communication.GetCargoTypesAsync(ct);
/// <summary>Stops the postponement of the permits that did not answer and tells their owners.</summary>
[HttpPost("blacklist")]
public Task<CommunicationResult> AddToBlacklist(CancellationToken ct) => communication.AddToBlacklistAsync(ct);
}

View File

@ -0,0 +1,102 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using NTP.Api.Authorization;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Receipts;
namespace NTP.Api.Controllers.V1.Receipts;
/// <summary>Permit receipts (سندات القبض والمطالبات المالية): port of the AqabaTCS entity permitsreceipts. The screen is a permission key; each action also needs its own key and status.</summary>
[ApiController]
[ApiVersion(1.0)]
[Route("api/v{version:apiVersion}/receipts")]
[Produces("application/json")]
[RequirePermission(PermissionKeys.Receipts)]
public sealed class ReceiptsController(IReceiptService receipts) : ControllerBase
{
private string? Ip => HttpContext.Connection.RemoteIpAddress?.ToString();
private static ReceiptQuery Query(string? receiptNo, string? pn, string? tn, string? trn, string? statusCode, string? creationSource, string? credit,
string? shipmentMode, DateTime? createDateFrom, DateTime? createDateTo) =>
new(receiptNo, pn, tn, trn, (statusCode ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
creationSource, credit, shipmentMode, createDateFrom, createDateTo);
[HttpGet]
public Task<PagedResult<ReceiptRow>> Search([FromQuery] string? receiptNo, [FromQuery] string? pn, [FromQuery] string? tn, [FromQuery] string? trn,
[FromQuery] string? statusCode, [FromQuery] string? creationSource, [FromQuery] string? credit, [FromQuery] string? shipmentMode,
[FromQuery] DateTime? createDateFrom, [FromQuery] DateTime? createDateTo, [FromQuery] int page = 1, [FromQuery] int pageSize = 16, CancellationToken ct = default) =>
receipts.SearchAsync(Query(receiptNo, pn, tn, trn, statusCode, creationSource, credit, shipmentMode, createDateFrom, createDateTo), new PageRequest(page, pageSize), ct);
[HttpGet("export")]
public async Task<IActionResult> Export([FromQuery] string? receiptNo, [FromQuery] string? pn, [FromQuery] string? tn, [FromQuery] string? trn,
[FromQuery] string? statusCode, [FromQuery] string? creationSource, [FromQuery] string? credit, [FromQuery] string? shipmentMode,
[FromQuery] DateTime? createDateFrom, [FromQuery] DateTime? createDateTo, CancellationToken ct)
{
var f = await receipts.ExportAsync(Query(receiptNo, pn, tn, trn, statusCode, creationSource, credit, shipmentMode, createDateFrom, createDateTo), ct);
return File(f.Content, f.ContentType, f.FileName);
}
/// <summary>Receipt types, rejection reasons and cargo types for the forms.</summary>
[HttpGet("lookups")]
public Task<ReceiptLookups> Lookups(CancellationToken ct) => receipts.GetLookupsAsync(ct);
/// <summary>Create form: the trailer and driver of the truck's grains permit (legacy getGNPermit).</summary>
[HttpGet("autofill/truck")]
public async Task<ActionResult<ReceiptAutoFill>> Truck([FromQuery] string tn, CancellationToken ct) =>
await receipts.GnPermitAsync(tn, ct) is { } hit ? hit : NoContent();
/// <summary>Create form: name and mobile of a registered driver (legacy driverAutoComplete).</summary>
[HttpGet("autofill/driver")]
public async Task<ActionResult<ReceiptAutoFill>> Driver([FromQuery] string nnpn, CancellationToken ct) =>
await receipts.DriverAsync(nnpn, ct) is { } hit ? hit : NoContent();
[HttpGet("{id:long}")]
public Task<ReceiptDetail> Get(long id, CancellationToken ct) => receipts.GetAsync(id, ct);
[HttpGet("{id:long}/log")]
public Task<PagedResult<ReceiptLogRow>> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 5, CancellationToken ct = default) =>
receipts.GetLogAsync(id, new PageRequest(page, pageSize), ct);
[HttpPost]
public Task<ReceiptResult> Create([FromBody] CreateReceiptRequest request, CancellationToken ct) => receipts.CreateAsync(request, ct);
[HttpPut("{id:long}")]
public Task<ReceiptResult> Update(long id, [FromBody] UpdateReceiptRequest request, CancellationToken ct) => receipts.UpdateAsync(id, request, ct);
[HttpPost("{id:long}/confirm")]
public Task<ReceiptResult> Confirm(long id, CancellationToken ct) => receipts.ConfirmAsync(id, Ip, ct);
/// <summary>The claim is paid: it becomes PAID and a cash receipt is created from it.</summary>
[HttpPost("{id:long}/paid")]
public Task<ReceiptResult> Paid(long id, CancellationToken ct) => receipts.PaidAsync(id, Ip, ct);
[HttpPost("{id:long}/revoke")]
public Task<ReceiptResult> Revoke(long id, [FromBody] RevokeReceiptRequest request, CancellationToken ct) => receipts.RevokeAsync(id, request, Ip, ct);
[HttpPost("{id:long}/accept-revoke")]
public Task<ReceiptResult> AcceptRevoke(long id, CancellationToken ct) => receipts.AcceptRevokeAsync(id, Ip, ct);
[HttpPost("{id:long}/reject-revoke")]
public Task<ReceiptResult> RejectRevoke(long id, CancellationToken ct) => receipts.RejectRevokeAsync(id, Ip, ct);
/// <summary>What the slip shows; logs the print.</summary>
[HttpPost("{id:long}/print")]
public Task<ReceiptPrint> Print(long id, CancellationToken ct) => receipts.PrintAsync(id, Ip, ct);
/// <summary>Audit: the permits Excel file against the receipts of a user / period; answers the result workbook.</summary>
[HttpPost("audit")]
[RequestSizeLimit(20_000_000)]
public async Task<IActionResult> Audit(IFormFile file, [FromForm] string? confirmationBy, [FromForm] DateTime? dateFrom, [FromForm] DateTime? dateTo,
[FromForm] string? timeFrom, [FromForm] string? timeTo, CancellationToken ct)
{
if (file is null || file.Length == 0) throw new BusinessException(ReceiptErrors.AuditInput, ReceiptMessages.UploadFile);
static TimeSpan? Time(string? s) => TimeSpan.TryParse(s, out var t) ? t : null;
await using var stream = file.OpenReadStream();
var r = await receipts.AuditAsync(stream, file.FileName, new AuditFilter(confirmationBy, dateFrom, dateTo, Time(timeFrom), Time(timeTo)), Ip, ct);
Response.Headers["X-Audit-Compared"] = r.Compared.ToString();
Response.Headers["X-Audit-Advanced"] = r.Advanced.ToString();
Response.Headers.AccessControlExposeHeaders = "X-Audit-Compared, X-Audit-Advanced, Content-Disposition";
return File(r.Workbook, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", r.FileName);
}
}

View File

@ -0,0 +1,97 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using NTP.Api.Authorization;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Registrar;
namespace NTP.Api.Controllers.V1.Registrar;
/// <summary>
/// Registrar (نظام التسجيل): the trucks, trailers and drivers companies register from the mobile app, reviewed here (legacy entities truckinfo, trailerinfo,
/// driverinfo). The screen is gated by its permission key on the controller; every action is decided by role and record status inside the service.
/// </summary>
[ApiController]
public abstract class RegistrarControllerBase(IRegistrarService registrar, RegistrarKind kind) : ControllerBase
{
private static IReadOnlyList<string> Split(string? statusCode) =>
(statusCode ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
private static RegistrarQuery Query(string? number, string? licenseNo, string? name, string? ownerName, string? vinNumber,
DateTime? createDateFrom, DateTime? createDateTo, string? statusCode) =>
new(number, licenseNo, name, ownerName, vinNumber, createDateFrom, createDateTo, Split(statusCode));
/// <summary>search: number (NNPN / TN / TRN) and licenseNo / vinNumber exact; name (drivers) and ownerName (trucks, trailers) contain; createDateFrom / createDateTo; statusCode one or several, comma separated.</summary>
[HttpGet]
public Task<PagedResult<RegistrarRecord>> Search([FromQuery] string? number, [FromQuery] string? licenseNo, [FromQuery] string? name, [FromQuery] string? ownerName,
[FromQuery] string? vinNumber, [FromQuery] DateTime? createDateFrom, [FromQuery] DateTime? createDateTo, [FromQuery] string? statusCode,
[FromQuery] int page = 1, [FromQuery] int pageSize = 16, CancellationToken ct = default) =>
registrar.SearchAsync(kind, Query(number, licenseNo, name, ownerName, vinNumber, createDateFrom, createDateTo, statusCode), new PageRequest(page, pageSize), ct);
/// <summary>Excel report of the same filters (needs the kind's report key).</summary>
[HttpGet("export")]
public async Task<IActionResult> Export([FromQuery] string? number, [FromQuery] string? licenseNo, [FromQuery] string? name, [FromQuery] string? ownerName,
[FromQuery] string? vinNumber, [FromQuery] DateTime? createDateFrom, [FromQuery] DateTime? createDateTo, [FromQuery] string? statusCode, CancellationToken ct)
{
var f = await registrar.ExportAsync(kind, Query(number, licenseNo, name, ownerName, vinNumber, createDateFrom, createDateTo, statusCode), ct);
return File(f.Content, f.ContentType, f.FileName);
}
/// <summary>The record, its pictures and what the caller may do with it in its current status.</summary>
[HttpGet("{id:long}")]
public Task<RegistrarDetail> Get(long id, CancellationToken ct) => registrar.GetAsync(kind, id, ct);
/// <summary>One picture of the registration (front / back of the licence).</summary>
[HttpGet("{id:long}/attachments/{attachmentId:long}")]
public async Task<IActionResult> Attachment(long id, long attachmentId, CancellationToken ct)
{
var f = await registrar.GetAttachmentAsync(kind, id, attachmentId, ct);
Response.Headers.CacheControl = "private, max-age=3600";
return File(f.Content, f.ContentType);
}
[HttpPut("{id:long}")]
public Task<RegistrarResult> Update(long id, [FromBody] RegistrarUpdateRequest request, CancellationToken ct) => registrar.UpdateAsync(kind, id, request, ct);
/// <summary>PENDING to COMPLETED (legacy COMPLETE).</summary>
[HttpPost("{id:long}/complete")]
public Task<RegistrarResult> Complete(long id, CancellationToken ct) => registrar.CompleteAsync(kind, id, ct);
/// <summary>PENDING to REVOKE with a reason from the revoke-reason list (legacy REVOKE).</summary>
[HttpPost("{id:long}/revoke")]
public Task<RegistrarResult> Revoke(long id, [FromBody] RegistrarRevokeRequest request, CancellationToken ct) => registrar.RevokeAsync(kind, id, request.Reason, ct);
/// <summary>COMPLETED back to PENDING (legacy toPending).</summary>
[HttpPost("{id:long}/reopen")]
public Task<RegistrarResult> Reopen(long id, CancellationToken ct) => registrar.ReopenAsync(kind, id, ct);
}
[ApiVersion(1.0)]
[Route("api/v{version:apiVersion}/registrar/drivers")]
[Produces("application/json")]
[RequirePermission(PermissionKeys.RegistrarDrivers)]
public sealed class RegistrarDriversController(IRegistrarService registrar) : RegistrarControllerBase(registrar, RegistrarKind.Driver);
[ApiVersion(1.0)]
[Route("api/v{version:apiVersion}/registrar/trucks")]
[Produces("application/json")]
[RequirePermission(PermissionKeys.RegistrarTrucks)]
public sealed class RegistrarTrucksController(IRegistrarService registrar) : RegistrarControllerBase(registrar, RegistrarKind.Truck);
[ApiVersion(1.0)]
[Route("api/v{version:apiVersion}/registrar/trailers")]
[Produces("application/json")]
[RequirePermission(PermissionKeys.RegistrarTrailers)]
public sealed class RegistrarTrailersController(IRegistrarService registrar) : RegistrarControllerBase(registrar, RegistrarKind.Trailer);
/// <summary>The drop-down lists shared by the three forms.</summary>
[ApiController]
[ApiVersion(1.0)]
[Route("api/v{version:apiVersion}/registrar/lookups")]
[Produces("application/json")]
[RequirePermission(PermissionKeys.RegistrarDrivers, PermissionKeys.RegistrarTrucks, PermissionKeys.RegistrarTrailers)]
public sealed class RegistrarLookupsController(IRegistrarService registrar) : ControllerBase
{
[HttpGet]
public Task<RegistrarLookups> Get(CancellationToken ct) => registrar.GetLookupsAsync(ct);
}

View File

@ -33,7 +33,8 @@
"Permits": { "Permits": {
"Notifications": { "Notifications": {
"Enabled": false, "Enabled": false,
"PushUrl": "http://aqtcs.nafith.net/backend/common/MobileNotification.cfc?wsdl", // OneSignal (push). AppId / ApiKey are set in the environment: Grains__Permits__Notifications__OneSignal__AppId, __ApiKey (secret), __AndroidChannelId.
"OneSignal": { "Url": "https://onesignal.com/api/v1/notifications", "AppId": "", "AndroidChannelId": "" },
"SendSmsToOwnersWithoutApp": false, "SendSmsToOwnersWithoutApp": false,
"Sms": { "Enabled": false, "Provider": "JORMALL", "SenderId": "Nafith" } "Sms": { "Enabled": false, "Provider": "JORMALL", "SenderId": "Nafith" }
} }
@ -63,6 +64,26 @@
"CommandTimeoutSeconds": 30 "CommandTimeoutSeconds": 30
}, },
// Mail (legacy cfmail): OFF. UserName / Password are secrets: env vars Mail__UserName / Mail__Password. Host / Port / From are per environment.
"Mail": { "Enabled": false, "Host": "", "Port": 587, "UseSsl": true, "From": "notifications@nafith.com", "TimeoutSeconds": 30 },
// JoSilos (legacy jobs/ExternalIntegrationJoSilos.cfm): OFF, nothing is sent while Enabled is false. SilosUrl = old ministry service (once per permit),
// AqabaSilosUrl = new service (retried until it answers RECEIVED).
"ExternalIntegration": {
"JoSilos": {
"Enabled": false,
"SilosUrl": "http://46.185.128.246:8484/SILOSAPI/POST_MINISTRY_SEQ_INFO",
"AqabaSilosUrl": "http://194.165.156.202:4001/api/TransportRequests/AddTransportRequest_Aq",
"TimeoutSeconds": 30
}
},
// Registrar (نظام التسجيل): the pictures of the mobile registrations stay on the legacy upload host (legacy application.aqTcsUploadedPath);
// the API fetches {AttachmentsBaseUrl}/{TRUCKINFO|TRAILERINFO|DRIVERINFO}/{file} for the screens.
"Registrar": {
"AttachmentsBaseUrl": "https://aqtcs2.nafith.net/uploadedfiles1/AqabaTCS"
},
// Refinery (المصفاة). Dinarak is the e-wallet payment API used by the trip action "صرف" (legacy RefinaryDinarakApi.cfc). // Refinery (المصفاة). Dinarak is the e-wallet payment API used by the trip action "صرف" (legacy RefinaryDinarakApi.cfc).
// Off here: while Enabled is false nothing is called (the action answers that the service is disabled). UserName / Password are SECRETS: // Off here: while Enabled is false nothing is called (the action answers that the service is disabled). UserName / Password are SECRETS:
// env vars Refinery__Dinarak__UserName / Refinery__Dinarak__Password (server .env); BaseUrl is set per environment // env vars Refinery__Dinarak__UserName / Refinery__Dinarak__Password (server .env); BaseUrl is set per environment
@ -72,6 +93,8 @@
// Jopetrol claim web service used by the wage claim "ترحيل" action: OFF, nothing is called while Enabled is false. // Jopetrol claim web service used by the wage claim "ترحيل" action: OFF, nothing is called while Enabled is false.
// UserName / Password are secrets: env vars Refinery__Jopetrol__UserName / Refinery__Jopetrol__Password (server .env), never in a file. // UserName / Password are secrets: env vars Refinery__Jopetrol__UserName / Refinery__Jopetrol__Password (server .env), never in a file.
"Jopetrol": { "Enabled": false, "Url": "http://fueltrans.jopetrol.com.jo:6060/TransportPmt/TransportPaymentWS.asmx", "TimeoutSeconds": 30 }, "Jopetrol": { "Enabled": false, "Url": "http://fueltrans.jopetrol.com.jo:6060/TransportPmt/TransportPaymentWS.asmx", "TimeoutSeconds": 30 },
"Trips": { "MaxPaymentAmount": 500 } "Trips": { "MaxPaymentAmount": 500 },
// Jobs: JopetrolWriteBack = legacy "live server only" guard of the trip sync (UpdateStatusTo1 / ToMinus2 at Jopetrol). Receivers are environment settings.
"Jobs": { "JopetrolWriteBack": false, "SyncUser": "16186973", "CancelledTripRecipients": [], "DailyReportRecipients": [] }
} }
} }

View File

@ -0,0 +1,7 @@
namespace NTP.Application.Abstractions;
/// <summary>Sends an HTML e-mail (legacy cfmail). Does nothing and returns false when mail is switched off or not configured.</summary>
public interface IMailService
{
Task<bool> SendHtmlAsync(IReadOnlyList<string> to, string subject, string htmlBody, CancellationToken ct = default);
}

View File

@ -0,0 +1,13 @@
namespace NTP.Application.Access;
/// <summary>
/// Voice communication screen (شاشة موظف الاتصالات, legacy AqabaTCS entity GN_COMMUNICATION): the distributed grains permits and the answers of their owners.
/// Granted by rows in GRAINS_SCREEN_PERMISSIONS (db/communication-permissions.sql): GTO holds the screen and the blacklist action, the Excel report is SU only.
/// </summary>
public static partial class PermissionKeys
{
public const string Communication = "grains.communication";
/// <summary>ADD_PERMIT_GN_BLACKLIST: stop the postponement of the permits that did not answer.</summary>
public const string CommunicationBlacklist = "grains.communication.blacklist";
public const string CommunicationReport = "grains.communication.report";
}

View File

@ -0,0 +1,31 @@
namespace NTP.Application.Access;
/// <summary>
/// Permit receipts (سندات القبض والمطالبات المالية, legacy AqabaTCS entity PERMITSRECEIPTS, tables PERMITS_RECEIPTS*). Granted ONLY by rows in
/// GRAINS_SCREEN_PERMISSIONS (db/receipts-permissions.sql translates the legacy STATUS_ACTION_MATRIX). The legacy matrix decides by role and receipt
/// status; the status rules live in code (<c>ReceiptRules</c>), the keys say which role may do which action.
/// </summary>
public static partial class PermissionKeys
{
/// <summary>The list and the receipt page (legacy SEARCH + VIEW).</summary>
public const string Receipts = "receipts";
public const string ReceiptsCreate = "receipts.create";
/// <summary>NOT_RECEIVED to RECEIVED (legacy CONFIRM).</summary>
public const string ReceiptsConfirm = "receipts.confirm";
/// <summary>Edit a RECEIVED / UNPAID receipt (legacy UPDATE).</summary>
public const string ReceiptsUpdate = "receipts.update";
/// <summary>UNPAID to PAID (legacy PAID).</summary>
public const string ReceiptsPaid = "receipts.paid";
public const string ReceiptsPrint = "receipts.print";
/// <summary>RECEIVED / UNPAID to PENDING_RVKD (legacy REVOKE of QUEUE_OP and SU): the cancellation waits for approval.</summary>
public const string ReceiptsRevokeRequest = "receipts.revokeRequest";
/// <summary>RECEIVED / UNPAID straight to RVKD (legacy REVOKE of TENDER_SUP).</summary>
public const string ReceiptsRevoke = "receipts.revoke";
/// <summary>AUDITED to RVKD (legacy REVOKE AUDITED).</summary>
public const string ReceiptsRevokeAudited = "receipts.revokeAudited";
public const string ReceiptsAcceptRevoke = "receipts.acceptRevoke";
public const string ReceiptsRejectRevoke = "receipts.rejectRevoke";
/// <summary>Audit of the receipts against the permits Excel file (legacy AUDIT / FIN_AUDIT).</summary>
public const string ReceiptsAudit = "receipts.audit";
public const string ReceiptsReport = "receipts.report";
}

View File

@ -0,0 +1,34 @@
namespace NTP.Application.Access;
/// <summary>
/// Registrar (نظام التسجيل) keys: review of the trucks, trailers and drivers registered from the mobile app (legacy AqabaTCS entities
/// DRIVERINFO / TRUCKINFO / TRAILERINFO, tables DRIVERS_INFO / TRUCKS_INFO / TRAILERS_INFO). Granted ONLY by rows in GRAINS_SCREEN_PERMISSIONS
/// (db/registrar-permissions.sql translates the legacy STATUS_ACTION_MATRIX rows); none of them is in <see cref="PermissionDefaults"/>.
/// The legacy matrix decides an action by role AND record status, so the action keys are per status transition:
/// screen = SEARCH + VIEW, update = UPDATE of a PENDING record, updateCompleted = UPDATE of a COMPLETED record (drivers only),
/// complete = PENDING to COMPLETED, revoke = PENDING to REVOKE, reopen = COMPLETED back to PENDING, report = Excel.
/// </summary>
public static partial class PermissionKeys
{
public const string RegistrarDrivers = "registrar.drivers";
public const string RegistrarDriversUpdate = "registrar.drivers.update";
public const string RegistrarDriversUpdateCompleted = "registrar.drivers.updateCompleted";
public const string RegistrarDriversComplete = "registrar.drivers.complete";
public const string RegistrarDriversRevoke = "registrar.drivers.revoke";
public const string RegistrarDriversReopen = "registrar.drivers.reopen";
public const string RegistrarDriversReport = "registrar.drivers.report";
public const string RegistrarTrucks = "registrar.trucks";
public const string RegistrarTrucksUpdate = "registrar.trucks.update";
public const string RegistrarTrucksComplete = "registrar.trucks.complete";
public const string RegistrarTrucksRevoke = "registrar.trucks.revoke";
public const string RegistrarTrucksReopen = "registrar.trucks.reopen";
public const string RegistrarTrucksReport = "registrar.trucks.report";
public const string RegistrarTrailers = "registrar.trailers";
public const string RegistrarTrailersUpdate = "registrar.trailers.update";
public const string RegistrarTrailersComplete = "registrar.trailers.complete";
public const string RegistrarTrailersRevoke = "registrar.trailers.revoke";
public const string RegistrarTrailersReopen = "registrar.trailers.reopen";
public const string RegistrarTrailersReport = "registrar.trailers.report";
}

View File

@ -0,0 +1,198 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NTP.Application.ExternalIntegration;
/// <summary>Settings of the JoSilos integration (section "ExternalIntegration:JoSilos"). OFF by default: nothing is sent while Enabled is false.</summary>
public sealed class JoSilosOptions
{
public const string SectionName = "ExternalIntegration:JoSilos";
public bool Enabled { get; set; }
/// <summary>Old ministry service (legacy SendPermitToJOSILOS, POST_MINISTRY_SEQ_INFO); permits are sent once.</summary>
public string SilosUrl { get; set; } = string.Empty;
/// <summary>New service (legacy SendPermitToJOSILOS1, AddTransportRequest_Aq); permits are sent until it answers RECEIVED.</summary>
public string AqabaSilosUrl { get; set; } = string.Empty;
public int TimeoutSeconds { get; set; } = 30;
public int SilosBatch { get; set; } = 50;
public int AqabaSilosBatch { get; set; } = 100;
}
public interface IJoSilosSettingsService
{
JoSilosOptions Value { get; }
}
/// <summary>A released grains permit that is not yet known to the old service (legacy qry1 of ExternalIntegrationJoSilos.cfm). All values are text, like the legacy JSON.</summary>
public sealed class JoSilosPermitRow
{
public long Id { get; set; }
public string? RequestNo { get; set; }
public string? RequestDate { get; set; }
public string? ToLocation { get; set; }
public string? ItemCode { get; set; }
public string? ItemName { get; set; }
public string? FirstPlateNo { get; set; }
public string? SecondPlateNo { get; set; }
public string? DriverName { get; set; }
public string? DriverNatId { get; set; }
public string? DriverLicenseNo { get; set; }
public string? DriverMobileNo { get; set; }
public string? TrailerType { get; set; }
public string? CarrierId { get; set; }
public string? CarrierName { get; set; }
public string? TimeStamp { get; set; }
}
/// <summary>A released grains permit that the new service has not confirmed yet (legacy qry2).</summary>
public sealed class AqabaSilosPermitRow
{
public long PermitId { get; set; }
public string? Pn { get; set; }
public string? ReferenceNo { get; set; }
public string? CreationDate { get; set; }
public string? Tn { get; set; }
public string? Trn { get; set; }
public string? Location { get; set; }
public string? Item { get; set; }
public string? ItemCode { get; set; }
public string? ItemName { get; set; }
public string? ExpArrivalDate { get; set; }
public string? Driver { get; set; }
public string? DriverNnpn { get; set; }
public string? LicenseNo { get; set; }
public long? LocationId { get; set; }
}
public interface IJoSilosRepository
{
Task<IReadOnlyList<JoSilosPermitRow>> GetPermitsForSilosAsync(int max, CancellationToken ct = default);
Task<IReadOnlyList<AqabaSilosPermitRow>> GetPermitsForAqabaSilosAsync(int max, CancellationToken ct = default);
/// <summary>Legacy ADD_INTEGRATION_LOG: removes the earlier PENDING row of the same permit / type / status / leg / event, inserts a PENDING row and returns its id.</summary>
Task<long> AddQueueLogAsync(string type, string operationType, long permitId, string permitStatusCode, int currentLeg, long eventId, string queueData, CancellationToken ct = default);
/// <summary>The service answered RECEIVED: status PROCESSED, result text, date now.</summary>
Task MarkProcessedAsync(long logId, string result, CancellationToken ct = default);
/// <summary>Any other answer: only the result text is kept (the row stays PENDING).</summary>
Task SetResultAsync(long logId, string result, CancellationToken ct = default);
}
/// <summary>POST of a JSON body to one of the two services; returns the answer text. Throws on network errors and time-outs.</summary>
public interface IJoSilosGatewayService
{
Task<string> PostJsonAsync(string url, string json, CancellationToken ct = default);
}
public sealed record JoSilosResult(int SilosSent, int SilosFailed, int AqabaSent, int AqabaFailed, string? Note = null)
{
public int Total => SilosSent + AqabaSent;
}
public interface IJoSilosService
{
Task<JoSilosResult> RunAsync(CancellationToken ct);
}
/// <summary>Pure builders of the two JSON bodies.</summary>
public static class JoSilosPayloads
{
private static readonly JsonSerializerOptions Json = new()
{
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
};
/// <summary>XML_DATA of the old service: the fields and their order are the legacy ones; the strings are really escaped (legacy concatenated them).</summary>
public static string Silos(JoSilosPermitRow r)
{
var date = r.RequestDate ?? "";
var body = new Dictionary<string, object?>
{
["id"] = 0, ["requestNo"] = r.RequestNo, ["requestDate"] = date, ["versionNo"] = "1", ["versionDate"] = date, ["sourceId"] = 1,
["fromLocation"] = " Aqaba", ["toLocation"] = r.ToLocation, ["itemName"] = r.ItemName, ["itemCode"] = r.ItemCode,
["requestWeight"] = 0.0, ["emptyWeight"] = 0.0, ["weight"] = 0.0, ["actualWeight"] = 0.0,
["firstPlateNo"] = r.FirstPlateNo, ["secondPlateNo"] = r.SecondPlateNo, ["axleLoads"] = 0, ["licenseNo"] = "0",
["isEnsured"] = true, ["insuranceNo"] = "0", ["driverName"] = r.DriverName, ["driverNatId"] = r.DriverNatId,
["driverLicenseNo"] = r.DriverLicenseNo, ["driverMobileNo"] = r.DriverMobileNo, ["driverLicenseExpiryDate"] = null,
["createdBy"] = "nafith", ["timeStamp"] = r.TimeStamp, ["trailerType"] = r.TrailerType, ["carrierId"] = r.CarrierId, ["carrierName"] = r.CarrierName,
};
return JsonSerializer.Serialize(body, Json);
}
/// <summary>Queue data of the old service's log row (legacy serializeJSON of its struct: upper-case keys, XML_DATA holding the body).</summary>
public static string SilosQueueData(JoSilosPermitRow r) =>
JsonSerializer.Serialize(new Dictionary<string, object?>
{
["PERMIT_ID"] = r.Id.ToString(System.Globalization.CultureInfo.InvariantCulture), ["PERMIT_STATUS_CODE"] = "CLOSE", ["TYPE"] = "JOSILOS",
["OPERATION_TYPE"] = "CREATE", ["CURRENTLEG"] = "0", ["EVENT_ID"] = "0", ["XML_DATA"] = Silos(r),
}, Json);
/// <summary>The new service's body: the legacy struct serialised (upper-case keys; the log id last).</summary>
public static string AqabaSilos(AqabaSilosPermitRow r, long? logId)
{
var body = new Dictionary<string, object?>
{
["TYPE"] = "AQABASILOS", ["OPERATION_TYPE"] = "CREATE", ["PERMIT_ID"] = r.PermitId, ["PN"] = r.Pn, ["REFERENCENO"] = r.ReferenceNo,
["CREATIONDATE"] = r.CreationDate, ["TN"] = r.Tn, ["TRN"] = r.Trn, ["LOCATION"] = r.Location, ["ITEM"] = r.Item, ["ITEMCODE"] = r.ItemCode,
["ITEMNAME"] = r.ItemName, ["EXPARRIVALDATE"] = r.ExpArrivalDate, ["DRIVER"] = r.Driver, ["DRIVERNNPN"] = r.DriverNnpn, ["LICENSENO"] = r.LicenseNo,
["DESTINATION"] = 10184, ["EVENT_ID"] = 0, ["CURRENTLEG"] = 0, ["PERMIT_STATUS_CODE"] = "RESD", ["LOCATIONID"] = r.LocationId,
};
if (logId is not null) body["LOGID"] = logId.Value;
return JsonSerializer.Serialize(body, Json);
}
}
/// <summary>
/// Port of jobs/ExternalIntegrationJoSilos.cfm. Two feeds of released grains permits (domain GN) to the Jordan silos services:
/// the old one (once per permit, answer RECEIVED = PROCESSED) and the new Aqaba silos one (retried every run until the service answers "RECEIVED").
/// Every attempt has a row in EXTERNAL_INTEGRATION_QUEUE_LOG. One failing permit never stops the others.
/// </summary>
public sealed class JoSilosService(IJoSilosRepository repo, IJoSilosGatewayService gateway, IJoSilosSettingsService settings) : IJoSilosService
{
public async Task<JoSilosResult> RunAsync(CancellationToken ct)
{
var o = settings.Value;
if (!o.Enabled) return new JoSilosResult(0, 0, 0, 0, "التكامل مع JoSilos غير مفعل (ExternalIntegration:JoSilos:Enabled)");
int silosOk = 0, silosFail = 0, aqabaOk = 0, aqabaFail = 0;
var notes = new List<string>();
if (!string.IsNullOrWhiteSpace(o.SilosUrl))
{
foreach (var p in await repo.GetPermitsForSilosAsync(Math.Max(1, o.SilosBatch), ct))
{
ct.ThrowIfCancellationRequested();
try
{
var logId = await repo.AddQueueLogAsync("JOSILOS", "CREATE", p.Id, "CLOSE", 0, 0, JoSilosPayloads.SilosQueueData(p), ct);
var answer = await gateway.PostJsonAsync(o.SilosUrl, JoSilosPayloads.Silos(p), ct);
if (answer == "RECEIVED") { await repo.MarkProcessedAsync(logId, answer, ct); silosOk++; }
else { await repo.SetResultAsync(logId, answer, ct); silosFail++; }
}
catch (Exception ex) when (!ct.IsCancellationRequested) { silosFail++; if (notes.Count < 3) notes.Add($"JOSILOS {p.RequestNo}: {ex.Message}"); }
}
}
if (!string.IsNullOrWhiteSpace(o.AqabaSilosUrl))
{
foreach (var p in await repo.GetPermitsForAqabaSilosAsync(Math.Max(1, o.AqabaSilosBatch), ct))
{
ct.ThrowIfCancellationRequested();
try
{
var logId = await repo.AddQueueLogAsync("AQABASILOS", "CREATE", p.PermitId, "RESD", 0, 0, JoSilosPayloads.AqabaSilos(p, null), ct);
var answer = await gateway.PostJsonAsync(o.AqabaSilosUrl, JoSilosPayloads.AqabaSilos(p, logId), ct);
if (answer == "\"RECEIVED\"") { await repo.MarkProcessedAsync(logId, answer, ct); aqabaOk++; }
else { await repo.SetResultAsync(logId, answer, ct); aqabaFail++; }
}
catch (Exception ex) when (!ct.IsCancellationRequested) { aqabaFail++; if (notes.Count < 3) notes.Add($"AQABASILOS {p.Pn}: {ex.Message}"); }
}
}
return new JoSilosResult(silosOk, silosFail, aqabaOk, aqabaFail, notes.Count == 0 ? null : string.Join(" | ", notes));
}
}

View File

@ -0,0 +1,150 @@
using System.Globalization;
using NTP.Application.Abstractions;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Grains.Orders;
using NTP.Application.Grains.Permits;
using NTP.Application.Grains.Reports;
namespace NTP.Application.Grains.Communication;
/// <summary>Row of TRUCK_DISTRIBUTION_LOG_VIEW (the last 30 days of distributed permits that were announced to the owners). Settable properties: Dapper + Oracle NUMBER.</summary>
public class CommunicationRow
{
public long Id { get; set; }
public long PermitId { get; set; }
public string? Tn { get; set; }
public long? Pn { get; set; }
public string? StatusCode { get; set; }
public long? BlackListId { get; set; }
public int IsBlocked { get; set; }
public string? PhoneNumber { get; set; }
public decimal LogDuration { get; set; }
public string? CargoType { get; set; }
public string? DistDate { get; set; }
public string? OrderDate { get; set; }
public string? ExpiryDate { get; set; }
public string? Shift { get; set; }
}
/// <summary>Row of the screen: the owner's answer and the minutes left to answer.</summary>
public sealed record CommunicationItem(
long Id, string? Tn, long? Pn, string? CargoType, string? PhoneNumber, string? DistDate, string? OrderDate, string? Shift,
string Answer, string Notes, int? RemainingMinutes, bool IsBlocked);
/// <summary>Filters: statusCode is PENDING (no answer yet), CLOSE (confirmed) or DELETED (postponed, the permit is on the blacklist).</summary>
public sealed record CommunicationQuery(string? Tn, string? Pn, string? CargoTypeCode, string? StatusCode, string? Shift, string? IsBlocked, DateTime? DateFrom, DateTime? DateTo);
public sealed class CargoOption { public long Id { get; set; } public string? Name { get; set; } }
public sealed record CommunicationResult(string Message, int Count);
public sealed class CommunicationOptions
{
public const string SectionName = "Grains:Communication";
/// <summary>Legacy application.AUTO_POSTPONE_PERIOD (minutes an owner has to answer). Its value is not in the legacy code: 30 is an unverified default.</summary>
public int AutoPostponeMinutes { get; set; } = 30;
}
public interface ICommunicationSettingsService
{
CommunicationOptions Value { get; }
}
public interface ICommunicationRepository
{
/// <summary>Newest first (legacy sort to_number(ID) DESC).</summary>
Task<PagedResult<CommunicationRow>> SearchAsync(CommunicationQuery query, PageRequest page, CancellationToken ct = default);
/// <summary>Permits (company 327, status REQST) whose log row is PENDING, without answer and not yet stopped: (permit id, truck).</summary>
Task<IReadOnlyList<CargoOption>> GetCargoTypesAsync(CancellationToken ct = default);
Task<IReadOnlyList<(long PermitId, string Tn)>> GetUnansweredAsync(CancellationToken ct = default);
/// <summary>TRUCK_DISTRIBUTION_LOG rows of the permits: UPDATEDATE now, CREATEDBY the user, ISBLOCKED = 1.</summary>
Task BlockAsync(IReadOnlyList<long> permitIds, string userId, CancellationToken ct = default);
}
public interface ICommunicationService
{
Task<PagedResult<CommunicationItem>> SearchAsync(CommunicationQuery query, PageRequest page, CancellationToken ct);
Task<CommunicationResult> AddToBlacklistAsync(CancellationToken ct);
Task<IReadOnlyList<CargoOption>> GetCargoTypesAsync(CancellationToken ct);
Task<ExportFile> ExportAsync(CommunicationQuery query, CancellationToken ct);
}
/// <summary>
/// Port of gn_communication (factory, factoryweb, dao). The screen shows each announced permit with the owner's answer; the action stops the
/// postponement of the ones that did not answer (they are marked blocked and their owners get the push BLOCKED_DISTRIBUTED_PERMIT_OWNERS).
/// </summary>
public sealed class CommunicationService(
ICommunicationRepository repository,
IUnitOfWork unitOfWork,
IMobileNotificationGatewayService notifications,
IReportExcelService excel,
IPermissionService permissions,
ICommunicationSettingsService settings,
ICurrentUser user) : ICommunicationService
{
private int PostponeMinutes => Math.Max(0, settings.Value.AutoPostponeMinutes);
public async Task<PagedResult<CommunicationItem>> SearchAsync(CommunicationQuery q, PageRequest page, CancellationToken ct)
{
if (q.DateFrom is { } f && q.DateTo is { } t && f.Date > t.Date) throw new BusinessException("ERROR.CREATEDATEFROM_NOT_GT_CREATEDATETO", "تاريخ الطلبية (من) يجب ان لا يكون اكبر من تاريخ الطلبية (الى)");
var r = await repository.SearchAsync(q, page, ct);
return new PagedResult<CommunicationItem>(r.Items.Select(Item).ToList(), r.Page, r.PageSize, r.TotalCount);
}
/// <summary>factoryweb.search: CLOSE = confirmed; a blacklisted PENDING row = answered with a postponement; otherwise "no reply" with the minutes left.</summary>
public CommunicationItem Item(CommunicationRow r)
{
string answer, notes;
int? remaining = null;
if (string.Equals(r.StatusCode, "CLOSE", StringComparison.OrdinalIgnoreCase)) { answer = "CLOSE"; notes = "تم الإجابة - موافق"; }
else if (r.BlackListId is not null) { answer = "DELETED"; notes = "تم الإجابة - تأجيل ، سيتم فك التأجيل بتاريخ " + r.ExpiryDate; }
else { answer = "PENDING"; notes = "لم يتم الرد"; remaining = (int)Math.Max(0, PostponeMinutes - r.LogDuration); }
return new CommunicationItem(r.Id, r.Tn, r.Pn, r.CargoType, r.PhoneNumber, r.DistDate, r.OrderDate, r.Shift, answer, notes, remaining, r.IsBlocked == 1);
}
public Task<IReadOnlyList<CargoOption>> GetCargoTypesAsync(CancellationToken ct) => repository.GetCargoTypesAsync(ct);
public async Task<CommunicationResult> AddToBlacklistAsync(CancellationToken ct)
{
if (!await permissions.IsAllowedAsync(PermissionKeys.CommunicationBlacklist, ct)) throw new ForbiddenException("ERROR.NO_AUTHORITY", "ليس لديك صلاحية لاتمام هذه العملية");
var rows = await repository.GetUnansweredAsync(ct);
if (rows.Count == 0) return new CommunicationResult(string.Empty, 0);
var permitIds = rows.Select(x => x.PermitId).Distinct().ToList();
await unitOfWork.ExecuteInTransactionAsync(async c => { await repository.BlockAsync(permitIds, user.UserId, c); return true; }, ct);
// legacy: the trucks of ALL found rows, in one push batch
var payload = new Dictionary<string, object?>
{
["NOTIFICATIONARY"] = rows.Select(x => new Dictionary<string, object?> { ["TN"] = x.Tn }).ToArray(),
};
_ = notifications.SendAsync(NotificationRules.BlockedDistributedOwners, payload, CancellationToken.None);
return new CommunicationResult($"تم ايقاف خاصية التثبيت والتأجيل عن ( {rows.Count.ToString(CultureInfo.InvariantCulture)} ) ارسالية", rows.Count);
}
public async Task<ExportFile> ExportAsync(CommunicationQuery q, CancellationToken ct)
{
if (!await permissions.IsAllowedAsync(PermissionKeys.CommunicationReport, ct)) throw new ForbiddenException("ERROR.NO_AUTHORITY", "ليس لديك صلاحية لاتمام هذه العملية");
var items = new List<CommunicationItem>();
for (var p = 1; items.Count < 50_000; p++)
{
var r = await SearchAsync(q, new PageRequest(p, PageRequest.MaxPageSize), ct);
items.AddRange(r.Items);
if (r.Items.Count == 0 || items.Count >= r.TotalCount) break;
}
var cols = new List<ReportColumn>
{
new("counter", "متسلسل", "#"), new("tn", "رقم الشاحنة", "Truck"), new("pn", "رقم الارسالية", "Permit"), new("cargo", "نوع المادة", "Cargo"),
new("mobile", "رقم الموبايل", "Mobile"), new("dist", "وقت التوزيع", "Distributed"), new("order", "تاريخ الطلبية", "Order date"),
new("status", "الحالة", "Status"), new("notes", "الملاحظات", "Notes"),
};
var rows = items.Select((x, i) => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
{
["counter"] = i + 1, ["tn"] = x.Tn, ["pn"] = x.Pn, ["cargo"] = x.CargoType, ["mobile"] = x.PhoneNumber, ["dist"] = x.DistDate, ["order"] = x.OrderDate,
["status"] = x.Answer == "CLOSE" ? "مغلق" : x.Answer == "DELETED" ? "مؤجل" : "قيد الانتظار", ["notes"] = x.Notes,
}).ToList();
var table = new ReportTable { Key = "COMMUNICATION", TitleAr = "شاشة موظف الاتصالات", TitleEn = "Communication officer screen", Columns = cols, Rows = rows };
return new ExportFile(excel.Build(table, user.UserId, DateTime.Now, true), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "COMMUNICATION.xlsx");
}
}

View File

@ -91,9 +91,9 @@ public sealed class NotificationOptions
/// <summary>Off by default: a switched-on environment pushes to the real devices found in USERDEVICEINFO.</summary> /// <summary>Off by default: a switched-on environment pushes to the real devices found in USERDEVICEINFO.</summary>
public bool Enabled { get; set; } public bool Enabled { get; set; }
/// <summary>?wsdl address of the legacy push web service (backend/common/MobileNotification.cfc, operation SendFromCF9). It sends the push /// <summary>OneSignal account the push goes to (legacy MobileNotification.cfc SendNotificationToOneSignal). V2 calls the OneSignal REST API itself;
/// (OneSignal) and writes MOBILENOTIFICATIONSLOG itself, so V2 only has to call it with the same arguments as legacy.</summary> /// the legacy web service is no longer used. AppId and ApiKey come from the environment (Grains__Permits__Notifications__OneSignal__AppId / __ApiKey).</summary>
public string PushUrl { get; set; } = string.Empty; public OneSignalOptions OneSignal { get; set; } = new();
public int TimeoutSeconds { get; set; } = 15; public int TimeoutSeconds { get; set; } = 15;
@ -107,6 +107,20 @@ public sealed class NotificationOptions
public SmsOptions Sms { get; set; } = new(); public SmsOptions Sms { get; set; } = new();
} }
/// <summary>OneSignal REST API settings. <see cref="ApiKey"/> is a SECRET: environment variable only, never a file of the repository.</summary>
public sealed class OneSignalOptions
{
public string Url { get; set; } = "https://onesignal.com/api/v1/notifications";
public string AppId { get; set; } = string.Empty;
public string ApiKey { get; set; } = string.Empty;
/// <summary>Android notification channel of the app (legacy android_channel_id); optional.</summary>
public string AndroidChannelId { get; set; } = string.Empty;
/// <summary>iOS sound file of the app (legacy ios_sound).</summary>
public string IosSound { get; set; } = "nafith_notification_sound.caf";
public bool IsConfigured => !string.IsNullOrWhiteSpace(AppId) && !string.IsNullOrWhiteSpace(ApiKey);
}
/// <summary>SMS provider (legacy NTP.components.SMS; application.SEND_SMS and application.SMS_PROVIDER). UserName / Password are secrets: environment variables only.</summary> /// <summary>SMS provider (legacy NTP.components.SMS; application.SEND_SMS and application.SMS_PROVIDER). UserName / Password are secrets: environment variables only.</summary>
public sealed class SmsOptions public sealed class SmsOptions
{ {

View File

@ -30,8 +30,8 @@ public interface INotificationRepository
{ {
Task<NotificationTemplateRow?> GetTemplateAsync(string type, CancellationToken ct = default); Task<NotificationTemplateRow?> GetTemplateAsync(string type, CancellationToken ct = default);
/// <summary>NTPUSERS ids with this role and the given mobile number, exact login, or login containing <paramref name="loginContains"/> (case-insensitive).</summary> /// <summary>NTPUSERS ids with this role (any role when <paramref name="roleCode"/> is null) and the given mobile number, exact login, or login containing <paramref name="loginContains"/> (case-insensitive).</summary>
Task<IReadOnlyList<long>> FindUserIdsAsync(string roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default); Task<IReadOnlyList<long>> FindUserIdsAsync(string? roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default);
Task<IReadOnlyList<DeviceRow>> GetActiveDevicesAsync(long userId, CancellationToken ct = default); Task<IReadOnlyList<DeviceRow>> GetActiveDevicesAsync(long userId, CancellationToken ct = default);
@ -41,11 +41,14 @@ public interface INotificationRepository
/// <summary>Login of the active dispatcher (role DISP) of a company.</summary> /// <summary>Login of the active dispatcher (role DISP) of a company.</summary>
Task<string?> GetCompanyDispatcherLoginAsync(long scac, CancellationToken ct = default); Task<string?> GetCompanyDispatcherLoginAsync(long scac, CancellationToken ct = default);
/// <summary>MOBILENOTIFICATIONSLOG row of one push (legacy LoggingNotification).</summary>
Task InsertPushLogAsync(string userId, string deviceId, string status, string request, string? response, string os, long templateId, CancellationToken ct = default);
Task InsertSmsLogAsync(string userLogin, string mobile, string status, string request, string? response, string provider, string serviceType, Task InsertSmsLogAsync(string userLogin, string mobile, string status, string request, string? response, string provider, string serviceType,
CancellationToken ct = default); CancellationToken ct = default);
} }
/// <summary>The legacy push web service (backend/common/MobileNotification.cfc, SendFromCF9) which sends the push and keeps the MOBILENOTIFICATIONSLOG row.</summary> /// <summary>Sends one push through OneSignal (legacy MobileNotification.cfc SendNotificationToOneSignal) and keeps the MOBILENOTIFICATIONSLOG row.</summary>
public interface IPushGatewayService public interface IPushGatewayService
{ {
Task<bool> SendAsync(PushMessage message, CancellationToken ct = default); Task<bool> SendAsync(PushMessage message, CancellationToken ct = default);

View File

@ -14,6 +14,49 @@ public static class NotificationRules
public const string PhoneReject = "PHONE_REJECT"; public const string PhoneReject = "PHONE_REJECT";
public const string DelayPn = "DELAY_PN"; public const string DelayPn = "DELAY_PN";
public const string SmsWithoutApp = "DISTRIBUTE_GRAINS_SMS_TO_USER_WITHNO_APP"; public const string SmsWithoutApp = "DISTRIBUTE_GRAINS_SMS_TO_USER_WITHNO_APP";
/// <summary>Registrar: a truck / trailer / driver registration was approved or rejected (legacy MobileNotification REGISTRATION).</summary>
/// <summary>Communication screen: the postponement of an unanswered permit was stopped (legacy BLOCKED_DISTRIBUTED_PERMIT_OWNERS).</summary>
public const string BlockedDistributedOwners = "BLOCKED_DISTRIBUTED_PERMIT_OWNERS";
public const string RegistrationApprove = "REGISTRATION_APPROVE";
public const string RegistrationRevoke = "REGISTRATION_REVOKE";
/// <summary>
/// Body of the OneSignal request, as the legacy SendNotificationToOneSignal built it: the device (player) id, title, text and the template id in
/// <c>data</c>; Android adds the notification channel, every other OS (iOS) is flagged <c>isIos</c> with the app sound.
/// </summary>
public static string OneSignalBody(OneSignalOptions o, string token, string title, string message, string os, long templateId)
{
var body = new Dictionary<string, object?>
{
["app_id"] = o.AppId,
["include_player_ids"] = new[] { token },
};
if (string.Equals(os, "ANDROID", StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrWhiteSpace(o.AndroidChannelId)) body["android_channel_id"] = o.AndroidChannelId;
}
else
{
body["isIos"] = true;
body["ios_sound"] = o.IosSound;
}
body["headings"] = new Dictionary<string, string> { ["en"] = title.Trim() };
body["contents"] = new Dictionary<string, string> { ["en"] = message.Trim() };
body["data"] = new Dictionary<string, string> { ["MSG_TEMPLATE_ID"] = templateId.ToString(CultureInfo.InvariantCulture) };
return System.Text.Json.JsonSerializer.Serialize(body, new System.Text.Json.JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
}
/// <summary>Legacy: the push failed when the OneSignal answer holds an "errors" key (or is not JSON at all).</summary>
public static bool OneSignalSucceeded(string? answer)
{
if (string.IsNullOrWhiteSpace(answer)) return false;
try
{
using var doc = System.Text.Json.JsonDocument.Parse(answer);
return doc.RootElement.ValueKind == System.Text.Json.JsonValueKind.Object && !doc.RootElement.TryGetProperty("errors", out _);
}
catch (System.Text.Json.JsonException) { return false; }
}
/// <summary>Driver and truck-owner app accounts are found by the truck's phone number.</summary> /// <summary>Driver and truck-owner app accounts are found by the truck's phone number.</summary>
public static readonly string[] PhoneRoles = ["DRVR", "TRKOWNER"]; public static readonly string[] PhoneRoles = ["DRVR", "TRKOWNER"];

View File

@ -1,4 +1,6 @@
using NTP.Application.ExternalIntegration;
using NTP.Application.Grains.Permits; using NTP.Application.Grains.Permits;
using NTP.Application.Refinery.Sync;
namespace NTP.Application.Jobs; namespace NTP.Application.Jobs;
@ -41,6 +43,41 @@ public static class JobCatalog
var n = await Get<IQueueService>(sp).FillCompanySharesAsync(ct); var n = await Get<IQueueService>(sp).FillCompanySharesAsync(ct);
return new JobOutcome(n, $"تم إنشاء {n} إرسالية"); return new JobOutcome(n, $"تم إنشاء {n} إرسالية");
}), }),
new("refinery-oil-sync",
"مزامنة ارساليات النفط الخام مع جوبترول", "Sync crude oil trips with Jopetrol",
"jobs/REFINERY_OIL.cfm: لكل حالة من -1 إلى 6 تُقرأ الارساليات من خدمة جوبترول: الجديدة تُنشأ، والتي تغيرت حالتها تُحدّث (ما لم تكن في مرحلة الصرف)، والحالة 0 تُحوَّل إلى 1 (تسريب)، والحالة -1 تُلغى (-2) مع بريد إشعار. تعديل حالة جوبترول يعمل فقط عند تفعيل Refinery:Jobs:JopetrolWriteBack.",
"jobs/REFINERY_OIL.cfm: for each status from -1 to 6 the trips are read from the Jopetrol service: new ones are created, changed ones updated (unless already in the payment phase), status 0 is moved to 1 (released) and -1 is cancelled (-2) with a mail. Changing statuses at Jopetrol only runs when Refinery:Jobs:JopetrolWriteBack is on.",
async (sp, ct) =>
{
var r = await Get<IRefineryOilSyncService>(sp).RunAsync(ct);
var msg = r.Note is not null && r.Total == 0 && r.Errors == 0
? r.Note
: $"أنشئت {r.Inserted}، حُدّثت {r.Updated}، سُرّبت {r.Released}، أُلغيت {r.Cancelled}" + (r.Errors > 0 ? $"، أخطاء {r.Errors}" : "") + (r.Note is not null ? " (" + r.Note + ")" : "");
return new JobOutcome(r.Total, msg);
}),
new("refinery-daily-exchange-report",
"التقرير اليومي لعطاء الصرف (بريد)", "Daily refinery exchange report (mail)",
"jobs/RefineryTrip_Exchange_email.cfm: بريد يومي بإجمالي صافي أجور النقل للارساليات المصروفة بلا مطالبة ولمطالبات الصرف غير المسددة. المستلمون من Refinery:Jobs:DailyReportRecipients والبريد من قسم Mail.",
"jobs/RefineryTrip_Exchange_email.cfm: a daily mail with the net wage of exchanged trips without a claim and of unpaid wage claims. Receivers from Refinery:Jobs:DailyReportRecipients, mail server from the Mail section.",
async (sp, ct) =>
{
var sent = await Get<IRefineryDailyReportService>(sp).SendAsync(ct);
return new JobOutcome(sent ? 1 : 0, sent ? "تم إرسال التقرير" : "لم يُرسل التقرير (البريد غير مفعل أو لا يوجد مستلمون أو فشل الإرسال)");
}),
new("josilos-integration",
"ارسال التصاريح الى JoSilos", "Send permits to JoSilos",
"jobs/ExternalIntegrationJoSilos.cfm: ارسال الارساليات (الحبوب) المسرّبة إلى خدمتي الصوامع: القديمة مرة واحدة، والجديدة (Aqaba) حتى تردّ RECEIVED. لكل محاولة سجل في EXTERNAL_INTEGRATION_QUEUE_LOG. معطل حتى تفعيل ExternalIntegration:JoSilos.",
"jobs/ExternalIntegrationJoSilos.cfm: sends released grains permits to the two silos services: the old one once, the new (Aqaba) one until it answers RECEIVED. Every attempt is logged in EXTERNAL_INTEGRATION_QUEUE_LOG. Off until ExternalIntegration:JoSilos is enabled.",
async (sp, ct) =>
{
var r = await Get<IJoSilosService>(sp).RunAsync(ct);
var msg = r.Note is not null && r.Total == 0 && r.SilosFailed + r.AqabaFailed == 0
? r.Note
: $"الخدمة القديمة: {r.SilosSent} ناجحة / {r.SilosFailed} فاشلة، الخدمة الجديدة: {r.AqabaSent} ناجحة / {r.AqabaFailed} فاشلة" + (r.Note is not null ? " (" + r.Note + ")" : "");
return new JobOutcome(r.Total, msg);
}),
]; ];
public static JobDefinition? Find(string key) => All.FirstOrDefault(j => string.Equals(j.Key, key, StringComparison.OrdinalIgnoreCase)); public static JobDefinition? Find(string key) => All.FirstOrDefault(j => string.Equals(j.Key, key, StringComparison.OrdinalIgnoreCase));

View File

@ -0,0 +1,64 @@
using NTP.Application.Common;
using NTP.Application.Grains.Orders;
namespace NTP.Application.Receipts;
/// <summary>PERMITS_RECEIPTS and its view, types, reasons and log (primary schema; NTP tables are read as NTP.&lt;table&gt; like the legacy queries).</summary>
public interface IReceiptRepository
{
/// <summary>Oldest first (legacy sort RECEIPT_NO ASC).</summary>
Task<PagedResult<ReceiptRow>> SearchAsync(ReceiptQuery query, PageRequest page, CancellationToken ct = default);
Task<ReceiptRow?> GetAsync(long id, CancellationToken ct = default);
Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct = default);
Task<IReadOnlyList<ReceiptTypeRow>> GetTypesAsync(long? scac, long? exceptId, CancellationToken ct = default);
Task<ReceiptTypeRow?> GetTypeAsync(long id, CancellationToken ct = default);
Task<IReadOnlyList<NamedRow>> GetRejectReasonsAsync(CancellationToken ct = default);
Task<IReadOnlyList<NamedRow>> GetCargoTypesAsync(CancellationToken ct = default);
/// <summary>The permit of a receipt type 8, 9 or 10 matches the rule of that type (legacy checks of create).</summary>
Task<bool> PermitMatchesTypeAsync(long receiptType, long pn, CancellationToken ct = default);
/// <summary>Inserts the receipt with the next receipt number of its kind (cash / claim); returns the id.</summary>
Task<long> InsertAsync(CreateReceiptRequest request, decimal fees, string status, string userLogin, CancellationToken ct = default);
/// <summary>Copy of a paid claim as a cash receipt (credit 0, RECEIVED) with a new number (legacy PAID).</summary>
Task<long> InsertPaidCopyAsync(long sourceId, CancellationToken ct = default);
/// <summary>The guarded changes: false when the receipt is no longer in the expected status.</summary>
Task<bool> ConfirmAsync(long id, string userLogin, CancellationToken ct = default);
Task<bool> UpdateAsync(long id, UpdateReceiptRequest request, string userLogin, CancellationToken ct = default);
Task<bool> PayAsync(long id, CancellationToken ct = default);
Task<bool> RequestRevokeAsync(long id, long reason, string? note, CancellationToken ct = default);
Task<bool> RevokeAsync(long id, string fromStatus, long? reason, string? note, string userLogin, CancellationToken ct = default);
Task<bool> RejectRevokeAsync(long id, CancellationToken ct = default);
Task AddLogAsync(long receiptId, string method, string oldData, string newData, long userId, string? ip, string? fileName, CancellationToken ct = default);
Task<ReceiptAutoFill?> GetGnPermitAsync(string tn, CancellationToken ct = default);
Task<ReceiptAutoFill?> GetDriverAsync(string nnpn, CancellationToken ct = default);
Task<bool> UserExistsAsync(string login, CancellationToken ct = default);
Task<AuditLookups> GetAuditLookupsAsync(CancellationToken ct = default);
Task<IReadOnlyList<ReceiptRow>> GetForAuditAsync(IReadOnlyList<string> statuses, AuditFilter filter, CancellationToken ct = default);
Task SetStatusAsync(IReadOnlyList<long> ids, string status, CancellationToken ct = default);
}
public interface IReceiptService
{
Task<PagedResult<ReceiptRow>> SearchAsync(ReceiptQuery query, PageRequest page, CancellationToken ct);
Task<ReceiptDetail> GetAsync(long id, CancellationToken ct);
Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct);
Task<ReceiptLookups> GetLookupsAsync(CancellationToken ct);
Task<ReceiptResult> CreateAsync(CreateReceiptRequest request, CancellationToken ct);
Task<ReceiptResult> ConfirmAsync(long id, string? ip, CancellationToken ct);
Task<ReceiptResult> UpdateAsync(long id, UpdateReceiptRequest request, CancellationToken ct);
Task<ReceiptResult> PaidAsync(long id, string? ip, CancellationToken ct);
Task<ReceiptResult> RevokeAsync(long id, RevokeReceiptRequest request, string? ip, CancellationToken ct);
Task<ReceiptResult> AcceptRevokeAsync(long id, string? ip, CancellationToken ct);
Task<ReceiptResult> RejectRevokeAsync(long id, string? ip, CancellationToken ct);
Task<ReceiptPrint> PrintAsync(long id, string? ip, CancellationToken ct);
Task<ReceiptAutoFill?> GnPermitAsync(string tn, CancellationToken ct);
Task<ReceiptAutoFill?> DriverAsync(string nnpn, CancellationToken ct);
Task<ExportFile> ExportAsync(ReceiptQuery query, CancellationToken ct);
Task<AuditResult> AuditAsync(Stream file, string originalName, AuditFilter filter, string? ip, CancellationToken ct);
}

View File

@ -0,0 +1,191 @@
namespace NTP.Application.Receipts;
/// <summary>The lookups the audit compares the file with (legacy CARGOTYPE, OPERATIONTYPE of ASEZA, LOCATIONS EN / EX of ASEZA, PERMITS_RECEIPTS_TYPE).</summary>
public sealed class AuditLookups
{
public IReadOnlyDictionary<string, string> CargoCodeByName { get; init; } = new Dictionary<string, string>();
public IReadOnlyDictionary<string, string> OperationCodeByCaption { get; init; } = new Dictionary<string, string>();
public IReadOnlyDictionary<string, long> LocationIdByShortName { get; init; } = new Dictionary<string, long>();
public IReadOnlyList<ReceiptTypeRow> Types { get; init; } = [];
}
/// <summary>Result line of the audit workbook.</summary>
public sealed record AuditLine(string Pn, string PermitStatus, string ReceiptNo, string Fees, string ReceiptStatus, string ConfirmationDate, string Result, string Remark);
/// <summary>A receipt the audit looked at: its result text and remarks (written to LOG_PERMITS_RECEIPTS; empty remarks = identical to the file).</summary>
public sealed record AuditedReceipt(long Id, string Result, string Remarks);
/// <summary>Pure port of permitsreceiptsfactory.cfc validRecordInfo and of the matching loop of permitsReceiptsAudit.</summary>
public static class ReceiptAudit
{
public const string Cancelled = "ملغى";
public const string RejectedPermit = "مرفوض";
public const string Yes = "نعم";
private static string[] Parts(string s) => s.Split('-', StringSplitOptions.RemoveEmptyEntries); // ColdFusion listToArray(x, "-") drops empty items
private static string Look(IReadOnlyDictionary<string, string> map, string name) => map.TryGetValue(name.Trim(), out var v) ? v : string.Empty;
/// <summary>The differences between the permit of the file and the stored receipt as " ، message" pieces; empty text = they match.</summary>
public static string ValidRecordInfo(AuditFileRow f, ReceiptRow db, AuditLookups lk)
{
var msg = new System.Text.StringBuilder();
void Add(string text) => msg.Append(" ، ").Append(text);
var calculable = true;
if (f.Tn.Length == 0) Add("رقم الشاحنة غير موجود"); else if (f.Tn != (db.Tn ?? string.Empty)) Add("رقم الشاحنة غير مطابق");
if (f.Trn.Length == 0) Add("رقم القاطرة غير موجود في الملف"); else if (f.Trn != (db.Trn ?? string.Empty)) Add("رقم المقطورة غير مطابق");
if (f.Nnpn.Length == 0) Add("الرقم الوطني للسائق غير موجود في الملف"); else if (f.Nnpn != (db.Nnpn ?? string.Empty)) Add("الرقم الوطني للسائق غير مطابق");
var dbCa = db.CaCode?.ToString() ?? string.Empty;
if (f.CaCode.Length > 0 && dbCa.Length > 0 && f.CaCode != dbCa) { calculable = false; Add("رقم المخلص غير مطابق"); }
var is327 = db.Scac == ReceiptRules.SupplyTenderScac;
if (is327)
{
var dbCrn = db.Crn?.ToString() ?? string.Empty;
if (f.Crn.Length > 0 && dbCrn.Length > 0 && f.Crn != dbCrn) Add("رقم إذن التحميل غير مطابق");
if (!lk.Types.Any(t => (t.Scac?.ToString() ?? string.Empty) == f.Scac.Trim())) { calculable = false; Add("رقم الشركة ليس من الشركات المسجلة على نظام الوصولات "); }
if (f.Scac.Length > 0 && f.Scac != (db.Scac?.ToString() ?? string.Empty)) { calculable = false; Add("رقم شركة النقل غير مطابق"); }
}
// cargo type: "first - second" for a double move
string[] cargo = [];
if (f.ShipmentMode.Length == 0) { calculable = false; Add("النمط غير موجود في الملف"); }
else
{
cargo = Parts(f.ShipmentMode);
var first = cargo.Length > 0 ? Look(lk.CargoCodeByName, cargo[0]) : string.Empty;
if (first.Length == 0) { calculable = false; Add("نمط الحركة الاولى غير موجود"); }
var dbFirst = cargo.Length == 1 ? db.ShipmentMode : db.FmShipmentMode;
if (first != (dbFirst ?? string.Empty)) { calculable = false; Add("نمط الحركة الاولى غير مطابق"); }
if (cargo.Length >= 2)
{
var second = Look(lk.CargoCodeByName, cargo[1]);
if (second.Length == 0) { calculable = false; Add("نمط الحركة الثانية غير موجود"); }
if (second != (db.ShipmentMode ?? string.Empty)) { calculable = false; Add("نمط الحركة الثاني غير مطابق"); }
}
}
// inbound operation
string[] inbound = [];
if (f.InboundTypeCode.Length == 0) Add("النمط غير موجود في الملف");
else
{
inbound = Parts(f.InboundTypeCode);
var first = inbound.Length > 0 ? Look(lk.OperationCodeByCaption, inbound[0]) : string.Empty;
if (first.Length == 0) { calculable = false; Add("عملية الحركة الاولى غير موجود"); }
var dbFirst = inbound.Length == 1 ? db.InboundTypeCode : db.FmInboundTypeCode;
if (first.Trim() != (dbFirst ?? string.Empty).Trim()) { calculable = false; Add("عملية الحركة الاولى غير مطابق"); }
if (inbound.Length >= 2)
{
var second = Look(lk.OperationCodeByCaption, inbound[1]);
if (second.Length == 0) { calculable = false; Add("عملية الحركة الثانية غير موجود"); }
if (second.Trim() != (db.InboundTypeCode ?? string.Empty)) { calculable = false; Add("عملية الحركة الثانية غير مطابق"); }
}
}
// entry and exit centres (company 327 only)
long? originId = null, destinationId = null;
if (is327)
{
if (f.OriginAddressId.Length == 0) Add("مركز الدخول غير موجود في الملف");
else
{
if (lk.LocationIdByShortName.TryGetValue(f.OriginAddressId.Trim(), out var id)) originId = id;
else { calculable = false; Add("مركز الدخول غير موجود"); }
if (originId != db.OriginAddressId) { calculable = false; Add("مركز الدخول غير مطابق"); }
}
if (f.DestinationAddressId.Length == 0) Add("مركز الخروج غير موجود في الملف");
else
{
if (lk.LocationIdByShortName.TryGetValue(f.DestinationAddressId.Trim(), out var id)) destinationId = id;
else { calculable = false; Add("مركز الخروج غير موجود"); }
if (destinationId != db.DestinationAddressId) { calculable = false; Add("مركز الخروج غير مطابق"); }
}
}
else
{
if (f.OriginAddressId.Length > 0 && lk.LocationIdByShortName.TryGetValue(f.OriginAddressId.Trim(), out var o)) originId = o;
if (f.DestinationAddressId.Length > 0 && lk.LocationIdByShortName.TryGetValue(f.DestinationAddressId.Trim(), out var d)) destinationId = d;
}
// fees
if (f.ShipmentMode.Length > 0 && f.InboundTypeCode.Length > 0 && f.DestinationAddressId.Length > 0 && f.OriginAddressId.Length > 0 && f.Scac.Length > 0 && calculable)
{
var fm = cargo.Length == 1 ? string.Empty : Look(lk.CargoCodeByName, cargo[0]);
var op = inbound.Length > 0 ? Look(lk.OperationCodeByCaption, inbound[^1]) : string.Empty;
long.TryParse(f.Scac.Trim(), out var scac);
var type = ReceiptRules.TypeOf(scac, fm, op, f.CaCode.Length > 0 ? f.CaCode : "0", originId, destinationId);
if (type is { } typeId)
{
var fee = lk.Types.FirstOrDefault(t => t.Id == typeId)?.Fees;
if (f.PermitStatus.Trim() == Cancelled)
{
if (f.IsEmployeeMistake.Trim() == Yes) Add("هذا التصريح ملغي بسبب خطأ موظف ولا يجب ان يكون له وصل");
else if (typeId == 7 && db.ReceiptType != 8) Add("نوع الوصل خطأ يجب انشاء وصل بدل ملغي بقيمة 6 دنانير ");
}
else if (typeId == 7) Add("لا يجب ان يتم انشاء وصل لهذا النوع من التصاريح ");
if (fee is not null && fee != db.Fees && typeId != 7) Add("القيمة المالية غير متساوية");
}
else if ((db.Fees ?? 0) != 0) Add(" القيمة المالية غير متساوية");
}
return msg.ToString();
}
/// <summary>The remark of a permit that has no receipt (legacy remark of the "لا يوجد وصل" line).</summary>
public static string NoReceiptRemark(AuditFileRow f, AuditLookups lk)
{
var cargo = Parts(f.ShipmentMode);
var fm = cargo.Length <= 1 ? string.Empty : Look(lk.CargoCodeByName, cargo[0]);
var supply = f.CaCode == ReceiptRules.SupplyClearingAgent;
if (f.PermitStatus.Trim() != Cancelled)
return fm.Length == 0 && supply ? "لا يجب ان يتم انشاء وصل لهذا النوع من التصاريح " : string.Empty;
if (f.IsEmployeeMistake.Trim() != Yes) return fm.Length == 0 && supply ? "يجب انشاء وصل بدل ملغي بقيمة 6 دنانير" : string.Empty;
return "ملغي بسبب خطأ موظف ولا يجب أن يكون له وصل‎";
}
/// <summary>Compares the permits of the file with the receipts: the result lines, the audited receipts (all written to the log) and the identical ones (moved on).</summary>
public static (List<AuditLine> Lines, List<AuditedReceipt> Audited, List<long> Identical) Compare(
IReadOnlyList<AuditFileRow> file, IReadOnlyList<ReceiptRow> receipts, AuditLookups lk, string? confirmationBy, Func<string?, string> statusName)
{
var lines = new List<AuditLine> { new("رقم التصريح", "حالة التصريح", "رقم الوصل", "الأجور", "حالة الوصل", "تاريخ الوصل", "النتيجة", "الملاحظات") };
var audited = new List<AuditedReceipt>();
var identical = new List<long>();
var pns = new List<string>();
string D(DateTime? d) => d?.ToString("dd/MM/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty;
foreach (var f in file)
{
if (f.Pn.Length == 0 || f.PermitStatus.Length == 0 || f.PermitStatus.Trim().Contains(RejectedPermit)) continue;
pns.Add(f.Pn);
var found = receipts.Where(r => r.Pn?.ToString() == f.Pn.Trim()).ToList();
if (found.Count == 0)
lines.Add(new AuditLine(f.Pn, f.PermitStatus, "-", "0", "-", "-", "لا يوجد وصل", NoReceiptRemark(f, lk)));
else if (found.Count == 1)
{
var r = found[0];
var result = r.Credit == 0 ? (r.RequestId is null ? "يوجد سند قبض" : "يوجد سند قبض دفع الكتروني") : "يوجد مطالبة مالية";
var remarks = ValidRecordInfo(f, r, lk);
if (remarks.Length == 0) identical.Add(r.Id);
audited.Add(new AuditedReceipt(r.Id, result, remarks));
lines.Add(new AuditLine(f.Pn, f.PermitStatus, r.ReceiptNo?.ToString() ?? "", r.Fees?.ToString() ?? "", statusName(r.StatusCode), D(r.ConfirmationDate), result, remarks));
}
else
foreach (var r in found)
{
audited.Add(new AuditedReceipt(r.Id, r.Credit == 0 ? "سند قبض مكرر" : "وصل مالي مكرر", string.Empty));
lines.Add(new AuditLine(f.Pn, f.PermitStatus, r.ReceiptNo?.ToString() ?? "", r.Fees?.ToString() ?? "", statusName(r.StatusCode), D(r.ConfirmationDate), "وصل مكرر", string.Empty));
}
}
if (pns.Count > 0)
foreach (var r in receipts.Where(r => !pns.Contains(r.Pn?.ToString() ?? string.Empty)
&& (string.IsNullOrEmpty(confirmationBy) || string.Equals(r.ConfirmationBy, confirmationBy, StringComparison.OrdinalIgnoreCase))))
{
var text = r.Credit == 0 ? "لا يوجد تصريح لسند القبض" : "لا يوجد تصريح للمطالبة المالية";
audited.Add(new AuditedReceipt(r.Id, text, text));
lines.Add(new AuditLine(string.Empty, "-", r.ReceiptNo?.ToString() ?? "", r.Fees?.ToString() ?? "", statusName(r.StatusCode), D(r.ConfirmationDate), "لا يوجد تصريح", string.Empty));
}
return (lines, audited, identical);
}
}

View File

@ -0,0 +1,179 @@
namespace NTP.Application.Receipts;
/// <summary>Row of PERMITS_RECEIPTS_VIEW plus the revoke columns of PERMITS_RECEIPTS. Class with settable properties (Dapper + Oracle NUMBER).</summary>
public class ReceiptRow
{
public long Id { get; set; }
public long? ReceiptNo { get; set; }
public long? Pn { get; set; }
public string? ShipmentMode { get; set; }
public string? FmShipmentMode { get; set; }
/// <summary>The cargo type names, "first - second" for a double move (view column CARGO_TYPE).</summary>
public string? CargoType { get; set; }
public long? Crn { get; set; }
public long? CaCode { get; set; }
public string? CaName { get; set; }
public string? Tn { get; set; }
public string? Trn { get; set; }
public string? Drvr { get; set; }
public string? Nnpn { get; set; }
public string? Mobile { get; set; }
public string? StatusCode { get; set; }
public DateTime? CreationDate { get; set; }
public string? CreatedBy { get; set; }
public string? Dln { get; set; }
public string? Dled { get; set; }
public long? Scac { get; set; }
public string? CompanyName { get; set; }
public string? InboundTypeCode { get; set; }
public string? FmInboundTypeCode { get; set; }
public long? OriginAddressId { get; set; }
public long? DestinationAddressId { get; set; }
public decimal? Fees { get; set; }
public long? ReceiptType { get; set; }
/// <summary>PERMITS_RECEIPTS_TYPE.CAPTION.</summary>
public string? ReceiptTypeCaption { get; set; }
public string? PermitStatus { get; set; }
public string? PermitStatusCaption { get; set; }
public string? ConfirmationBy { get; set; }
public string? ConfirmationName { get; set; }
public DateTime? ConfirmationDate { get; set; }
/// <summary>0 = cash, 1 = electronic payment (a permit request made it).</summary>
public int CreationSource { get; set; }
/// <summary>0 = سند قبض (cash receipt), 1 = مطالبة مالية (financial claim).</summary>
public int Credit { get; set; }
public long? RequestId { get; set; }
public long? RejectReason { get; set; }
public string? RejectReasonNote { get; set; }
public DateTime? RevokeDate { get; set; }
public string? RevokeBy { get; set; }
}
/// <summary>Grid filters: receipt number, permit number, truck and trailer (equal), statuses, payment way (0 / 1), credit (0 / 1), cargo code (second move) and creation dates.</summary>
public sealed record ReceiptQuery(
string? ReceiptNo, string? Pn, string? Tn, string? Trn, IReadOnlyList<string> StatusCodes, string? CreationSource, string? Credit,
string? ShipmentMode, DateTime? DateFrom, DateTime? DateTo);
/// <summary>New receipt (legacy create form of company 327). Double-move receipt types (1, 2) also carry the first-move cargo type.</summary>
public sealed class CreateReceiptRequest
{
public long Scac { get; set; } = 327;
public int Credit { get; set; }
public long ReceiptType { get; set; }
public string? Pn { get; set; }
public string? FmShipmentMode { get; set; }
public string? ShipmentMode { get; set; }
public string? Tn { get; set; }
public string? Trn { get; set; }
public string? Nnpn { get; set; }
public string? Drvr { get; set; }
public string? Mobile { get; set; }
public string? Dln { get; set; }
public string? Dled { get; set; }
public string? Crn { get; set; }
public long? CaCode { get; set; }
public string? InboundTypeCode { get; set; }
public long? OriginAddressId { get; set; }
public long? DestinationAddressId { get; set; }
}
/// <summary>Edit of a RECEIVED / UNPAID receipt (legacy update): the fields of the form of company 327.</summary>
public sealed class UpdateReceiptRequest
{
public string? Pn { get; set; }
public string? FmShipmentMode { get; set; }
public string? ShipmentMode { get; set; }
public string? Tn { get; set; }
public string? Trn { get; set; }
public string? Nnpn { get; set; }
public string? Drvr { get; set; }
public string? Mobile { get; set; }
}
public sealed record RevokeReceiptRequest(long? Reason, string? Note);
/// <summary>What the caller may do with the receipt in its status (the legacy PORTLET buttons).</summary>
public sealed record ReceiptActions(bool Update, bool Confirm, bool Paid, bool Print, bool Revoke, bool AcceptRevoke, bool RejectRevoke);
public sealed record ReceiptDetail(ReceiptRow Receipt, ReceiptActions Actions, string? RejectReasonName);
public sealed record ReceiptResult(string Message, long? Id = null);
public sealed class ReceiptLogRow
{
public long Id { get; set; }
public string? MethodName { get; set; }
public DateTime? LogDate { get; set; }
public string? Login { get; set; }
public string? OldData { get; set; }
public string? NewData { get; set; }
}
public sealed class ReceiptTypeRow
{
public long Id { get; set; }
public string? Caption { get; set; }
public decimal? Fees { get; set; }
public string? Description { get; set; }
public long? Scac { get; set; }
}
public sealed class NamedRow
{
public string? Code { get; set; }
public string? Name { get; set; }
}
public sealed record ReceiptLookups(
IReadOnlyList<ReceiptTypeRow> Types, IReadOnlyList<NamedRow> RejectReasons, IReadOnlyList<NamedRow> CargoTypes);
/// <summary>Auto-fill of the create form from a truck (legacy getGNPermit / driverAutoComplete).</summary>
public sealed class ReceiptAutoFill
{
public string? Trn { get; set; }
public string? Nnpn { get; set; }
public string? Drvr { get; set; }
public string? Mobile { get; set; }
/// <summary>The grains (GN) permit number of the truck, shown as a hint.</summary>
public string? Pn { get; set; }
public string? CargoCode { get; set; }
}
/// <summary>What the receipt slip shows (legacy printPermitsReceipts); the page lays it out.</summary>
public sealed record ReceiptPrint(ReceiptRow Receipt, string FirstMoveText, string Description, bool ShowCargo, bool ShowGnpn);
/// <summary>A permit row of the audit Excel file (legacy columns SN, SCAC, ... IS_EMPLOYEE_MISTAKE).</summary>
public sealed class AuditFileRow
{
public string Scac { get; set; } = "";
public string Nnpn { get; set; } = "";
public string InboundTypeCode { get; set; } = "";
public string ShipmentMode { get; set; } = "";
public string PermitStatus { get; set; } = "";
public string Pn { get; set; } = "";
public string Tn { get; set; } = "";
public string Trn { get; set; } = "";
public string OriginAddressId { get; set; } = "";
public string DestinationAddressId { get; set; } = "";
public string Crn { get; set; } = "";
public string CaCode { get; set; } = "";
public string IsEmployeeMistake { get; set; } = "";
}
/// <summary>Filters of the audit (which receipts are compared): who confirmed them and when.</summary>
public sealed record AuditFilter(string? ConfirmationBy, DateTime? DateFrom, DateTime? DateTo, TimeSpan? TimeFrom, TimeSpan? TimeTo);
/// <summary>The audit answer: the result workbook and how many receipts moved to the next status.</summary>
public sealed record AuditResult(byte[] Workbook, string FileName, int Compared, int Advanced);
public static class ReceiptStatus
{
public const string NotReceived = "NOT_RECEIVED";
public const string Received = "RECEIVED";
public const string Unpaid = "UNPAID";
public const string Paid = "PAID";
public const string Audited = "AUDITED";
public const string Completed = "COMPLETED";
public const string PendingRvkd = "PENDING_RVKD";
public const string Rvkd = "RVKD";
}

View File

@ -0,0 +1,120 @@
using System.Text.Json;
namespace NTP.Application.Receipts;
/// <summary>User-facing texts. Where the legacy caption exists it is verbatim (LT_CAPTION); the others are the legacy error codes in plain Arabic.</summary>
public static class ReceiptMessages
{
public const string Done = "";
public const string NoAuthority = "ليس لديك صلاحية لاتمام هذه العملية"; // ERROR.NO_AUTHORITY
public const string Required = "الرجاء ادخال جميع الحقول"; // REPORT.VALIDATION
public const string DataCheck = "بيانات الوصل غير مطابقة لبيانات التصريح"; // ERROR.PERMIT_RECEIPT_DATA_CHECK (no caption in LT_CAPTION)
public const string ZeroFees = "لا يمكن طباعة وصل قيمته صفر"; // ERROR.ZERO_FEES
public const string RejectReasonMandatory = "يجب اختيار سبب الرفض"; // REJECT_REASON_MANDATORY
public const string UserNotFound = "هذا المستخدم غير موجود على النظام"; // ERROR.THIS_USER_IS_NOT_EXIST
public const string ConfirmationRange = "لا يجوز ان يكون حقل تاريخ التقديم من اكبر من حقل تاريخ التقديم الى "; // ERROR.CONFIRMATION_FROM_NOT_GT_CONFIRMATION_TO
public const string NoReceiptsForUser = "هذا المستخدم ليس لدية وصولات خلال الفترة المحددة"; // ERROR.THERE_IS_NOT_ANY_RECEIPT_FOR_THIS_USER
public const string UploadFile = "يرجى اضافة ملف معلومات التصاريح لغاية الدقيق"; // ERROR.PLEASE_UPLOAD_FILE
public const string AuditFilter = "يجب تعبئة احد حقول الفلترة (المستخدم او التاريخ)";
public const string AuditBothDates = "يجب اختيار تاريخ البداية وتاريخ النهاية";
public const string DateRange = "تاريخ الانشاء (من) يجب ان لا يكون اكبر من تاريخ الانشاء (الى)";
public const string UnknownType = "نوع الوصل غير معروف";
}
public static class ReceiptErrors
{
public const string NoAuthority = "ERROR.NO_AUTHORITY";
public const string DataCheck = "ERROR.PERMIT_RECEIPT_DATA_CHECK";
public const string ZeroFees = "ERROR.ZERO_FEES";
public const string RejectReason = "REJECT_REASON_MANDATORY";
public const string UserNotFound = "ERROR.THIS_USER_IS_NOT_EXIST";
public const string AuditInput = "ERROR.AUDIT_INPUT";
public const string NoReceipts = "ERROR.THERE_IS_NOT_ANY_RECEIPT_FOR_THIS_USER";
}
/// <summary>Pure rules of permitsreceiptsfactory.cfc.</summary>
public static class ReceiptRules
{
/// <summary>Companies of the receipts: 327 = ادارة عطاء التموين / شركة أسوار القدس (types 1-8), 366 = the permit-request (electronic payment) types 9, 10.</summary>
public const long SupplyTenderScac = 327;
public const long RequestScac = 366;
public const string SupplyClearingAgent = "10184";
/// <summary>Double-move receipt types (a first and a second cargo type): 1, 2 and 10.</summary>
public static bool IsDoubleMove(long receiptType) => receiptType is 1 or 2 or 10;
public static bool IsStatus(string? status, string expected) => string.Equals(status, expected, StringComparison.OrdinalIgnoreCase);
/// <summary>Status of a new receipt: cash (credit 0) RECEIVED, a financial claim UNPAID.</summary>
public static string StatusForNew(int credit) => credit == 0 ? ReceiptStatus.Received : ReceiptStatus.Unpaid;
public static bool CanUpdate(string? s) => IsStatus(s, ReceiptStatus.Received) || IsStatus(s, ReceiptStatus.Unpaid);
public static bool CanConfirm(string? s) => IsStatus(s, ReceiptStatus.NotReceived);
public static bool CanPay(string? s) => IsStatus(s, ReceiptStatus.Unpaid);
public static bool CanPrint(string? s) =>
IsStatus(s, ReceiptStatus.Audited) || IsStatus(s, ReceiptStatus.Paid) || IsStatus(s, ReceiptStatus.Received) || IsStatus(s, ReceiptStatus.Unpaid);
public static bool CanRevokeOpen(string? s) => IsStatus(s, ReceiptStatus.Received) || IsStatus(s, ReceiptStatus.Unpaid);
public static bool CanRevokeAudited(string? s) => IsStatus(s, ReceiptStatus.Audited);
public static bool CanDecideRevoke(string? s) => IsStatus(s, ReceiptStatus.PendingRvkd);
/// <summary>
/// getPermitReceiptType (permitsreceiptsfactory.cfc:1124): the receipt type of a permit. Company 327 by the double move, the inbound operation, the
/// clearing agent (10184 = supply) and the entry / exit centres; company 366 by the double move only. Null when none applies.
/// </summary>
public static int? TypeOf(long scac, string? fmShipmentMode, string? inboundCode, string? clearingAgent, long? originId, long? destinationId)
{
var double_ = !string.IsNullOrEmpty(fmShipmentMode);
var inbound = (inboundCode ?? string.Empty).Trim();
var import = inbound.Equals("IMPT", StringComparison.OrdinalIgnoreCase) || inbound.Equals("FSEZ", StringComparison.OrdinalIgnoreCase);
var supply = (clearingAgent ?? string.Empty).Trim() == SupplyClearingAgent;
if (scac == SupplyTenderScac)
{
if (double_ && import && supply) return 1;
if (double_ && import && !supply) return 2;
if (!double_ && !import) return 3;
var facilities = destinationId is 20 or 30 or 40 or 50 or 60 && originId is 86 or 10007251 or 10048421 or 10151187;
if (facilities && supply) return 5;
if (facilities && !supply) return 6;
if (!double_ && import && !supply) return 4;
if (!double_ && supply) return 7;
return null;
}
if (scac == RequestScac) return double_ ? 10 : 9;
return null;
}
/// <summary>The "first - second" text stored for a double move (legacy "FM-SM" split on '-').</summary>
public static (string? Fm, string Sm) SplitModes(string? fm, string? sm) =>
(string.IsNullOrWhiteSpace(fm) ? null : fm.Trim(), (sm ?? string.Empty).Trim());
// ---------------------------------------------------------------- log (aqabaTCSBCommon.logs.saveLog)
private static readonly JsonSerializerOptions Json = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
/// <summary>Status captions of the log (LT_CAPTION PERMITSRECEIPTS.STATUSCODE.*); the legacy log keeps the translated text.</summary>
public static string StatusCaption(string? status) => status?.ToUpperInvariant() switch
{
"AUDITED" => "مدقق",
"NOT_RECEIVED" => "غير مستلم",
"PAID" => "مسدد",
"PENDING_RVKD" => "قيد الالغاء",
"RECEIVED" => "تم الاستلام",
"RVKD" => "ملغي",
"UNPAID" => "غير مسدد",
"COMPLETED" => "مكتمل",
_ => status ?? string.Empty,
};
/// <summary>OLD_DATA / NEW_DATA of a status change: {"STATUSCODE":"caption"}.</summary>
public static (string Old, string New) StatusLog(string? from, string to) =>
(JsonSerializer.Serialize(new Dictionary<string, string> { ["STATUSCODE"] = StatusCaption(from) }, Json),
JsonSerializer.Serialize(new Dictionary<string, string> { ["STATUSCODE"] = StatusCaption(to) }, Json));
/// <summary>CREATE log: only the new data (status caption and the empty NOTES of the legacy args).</summary>
public static (string Old, string New) CreateLog(string status) =>
("{}", JsonSerializer.Serialize(new Dictionary<string, string> { ["STATUSCODE"] = StatusCaption(status), ["NOTES"] = "" }, Json));
public static (string Old, string New) PrintLog() => ("{}", JsonSerializer.Serialize(new Dictionary<string, string> { ["NOTES"] = "" }, Json));
public static string AuditResultJson(string result, string remarks) => JsonSerializer.Serialize(new Dictionary<string, string> { ["result"] = result, ["remarks"] = remarks }, Json);
}

View File

@ -0,0 +1,332 @@
using System.Globalization;
using FluentValidation;
using FluentValidation.Results;
using NTP.Application.Abstractions;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Grains.Orders;
using NTP.Application.Grains.Reports;
namespace NTP.Application.Receipts;
/// <summary>
/// Port of the AqabaTCS entity permitsreceipts (factory, factoryweb, dao): cash receipts and financial claims of the permits (سندات القبض والمطالبات
/// المالية). The screen and every action are permission keys (db/receipts-permissions.sql, from the legacy STATUS_ACTION_MATRIX); the status each action
/// needs is checked here. Every status change writes LOG_PERMITS_RECEIPTS like the legacy saveLog.
/// </summary>
public sealed class ReceiptService(
IReceiptRepository repository,
IUnitOfWork unitOfWork,
IPermissionService permissions,
IReportExcelService excel,
ICurrentUser user) : IReceiptService
{
private const int ExportLimit = 50_000;
public async Task<PagedResult<ReceiptRow>> SearchAsync(ReceiptQuery query, PageRequest page, CancellationToken ct)
{
if (query.DateFrom is { } from && query.DateTo is { } to && from.Date > to.Date) throw new BusinessException("ERROR.CREATEDATEFROM_NOT_GT_CREATEDATETO", ReceiptMessages.DateRange);
return await repository.SearchAsync(query, page, ct);
}
public async Task<ReceiptDetail> GetAsync(long id, CancellationToken ct)
{
var r = await Load(id, ct);
var reasons = r.RejectReason is { } rr ? (await repository.GetRejectReasonsAsync(ct)).FirstOrDefault(x => x.Code == rr.ToString(CultureInfo.InvariantCulture))?.Name : null;
return new ReceiptDetail(r, await ActionsAsync(r, ct), reasons);
}
public async Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct)
{
_ = await Load(id, ct);
return await repository.GetLogAsync(id, page, ct);
}
public async Task<ReceiptLookups> GetLookupsAsync(CancellationToken ct) =>
new(await repository.GetTypesAsync(null, null, ct), await repository.GetRejectReasonsAsync(ct), await repository.GetCargoTypesAsync(ct));
// ---------------------------------------------------------------- create / update
public async Task<ReceiptResult> CreateAsync(CreateReceiptRequest request, CancellationToken ct)
{
await Require(PermissionKeys.ReceiptsCreate, ct);
var failures = new List<ValidationFailure>();
void Need(string field, bool ok) { if (!ok) failures.Add(new ValidationFailure(field, ReceiptMessages.Required)); }
Need("pn", long.TryParse(request.Pn?.Trim(), out _));
Need("tn", !string.IsNullOrWhiteSpace(request.Tn));
Need("trn", !string.IsNullOrWhiteSpace(request.Trn));
Need("nnpn", !string.IsNullOrWhiteSpace(request.Nnpn));
Need("drvr", !string.IsNullOrWhiteSpace(request.Drvr));
Need("dln", !string.IsNullOrWhiteSpace(request.Dln));
Need("dled", !string.IsNullOrWhiteSpace(request.Dled));
Need("shipmentMode", !string.IsNullOrWhiteSpace(request.ShipmentMode));
Need("receiptType", request.ReceiptType > 0);
Need("credit", request.Credit is 0 or 1);
if (ReceiptRules.IsDoubleMove(request.ReceiptType)) Need("fmShipmentMode", !string.IsNullOrWhiteSpace(request.FmShipmentMode));
if (failures.Count > 0) throw new ValidationException(failures);
var type = await repository.GetTypeAsync(request.ReceiptType, ct) ?? throw new BusinessException("ERROR.CREATING_RECEIPT", ReceiptMessages.UnknownType);
var pn = long.Parse(request.Pn!.Trim(), CultureInfo.InvariantCulture);
// create: the permit has to fit the type (types 8, 9, 10; legacy checkPermitType*)
if (request.ReceiptType is 8 or 9 or 10 && !await repository.PermitMatchesTypeAsync(request.ReceiptType, pn, ct))
throw new BusinessException(ReceiptErrors.DataCheck, ReceiptMessages.DataCheck);
var id = await repository.InsertAsync(request, type.Fees ?? 0, ReceiptRules.StatusForNew(request.Credit), user.UserId, ct);
return new ReceiptResult(ReceiptMessages.Done, id);
}
public async Task<ReceiptResult> UpdateAsync(long id, UpdateReceiptRequest request, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanUpdate(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsUpdate, ct)) throw NoAuthority();
if (!await repository.UpdateAsync(id, request, user.UserId, ct)) throw NoAuthority();
return new ReceiptResult(ReceiptMessages.Done, id);
}
// ---------------------------------------------------------------- status changes
public async Task<ReceiptResult> ConfirmAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanConfirm(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsConfirm, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, ReceiptStatus.Received);
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "CONFIRM", old, @new, user.Id, ip, null, c);
if (!await repository.ConfirmAsync(id, user.UserId, c)) throw NoAuthority();
return true;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, id);
}
/// <summary>factory.PAID: the claim becomes PAID and a cash receipt (credit 0, RECEIVED, new number) is created from it; both are logged.</summary>
public async Task<ReceiptResult> PaidAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanPay(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsPaid, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, ReceiptStatus.Paid);
var copyId = await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "PAID", old, @new, user.Id, ip, null, c);
if (!await repository.PayAsync(id, c)) throw NoAuthority();
var copy = await repository.InsertPaidCopyAsync(id, c);
var (o2, n2) = ReceiptRules.CreateLog(ReceiptStatus.Received);
await repository.AddLogAsync(copy, "CREATE", o2, n2, user.Id, ip, null, c);
return copy;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, copyId);
}
/// <summary>
/// factory.revokeReceipt: QUEUE_OP and SU ask for the cancellation (RECEIVED / UNPAID to PENDING_RVKD); the others cancel at once (RECEIVED / UNPAID, or AUDITED
/// for the roles that may). A reason from RECEIPT_REVOKE_REJECT_REASON is mandatory; a cancelled receipt has no fees.
/// </summary>
public async Task<ReceiptResult> RevokeAsync(long id, RevokeReceiptRequest request, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
var asksOnly = user.IsInAnyRole("SU", "QUEUE_OP");
string next;
if (ReceiptRules.CanRevokeOpen(r.StatusCode))
{
if (!await permissions.IsAllowedAsync(asksOnly ? PermissionKeys.ReceiptsRevokeRequest : PermissionKeys.ReceiptsRevoke, ct)) throw NoAuthority();
next = asksOnly ? ReceiptStatus.PendingRvkd : ReceiptStatus.Rvkd;
}
else if (ReceiptRules.CanRevokeAudited(r.StatusCode) && !asksOnly)
{
if (!await permissions.IsAllowedAsync(PermissionKeys.ReceiptsRevokeAudited, ct)) throw NoAuthority();
next = ReceiptStatus.Rvkd;
}
else throw NoAuthority();
var reasons = await repository.GetRejectReasonsAsync(ct);
if (request.Reason is not { } reason || reasons.All(x => x.Code != reason.ToString(CultureInfo.InvariantCulture)))
throw new ValidationException([new ValidationFailure("reason", ReceiptMessages.RejectReasonMandatory)]);
var note = RegistrarClean(request.Note);
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, next);
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "REVOKE", old, @new, user.Id, ip, null, c);
var ok = next == ReceiptStatus.PendingRvkd
? await repository.RequestRevokeAsync(id, reason, note, c)
: await repository.RevokeAsync(id, r.StatusCode!, reason, note, user.UserId, c);
if (!ok) throw NoAuthority();
return true;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, id);
}
public async Task<ReceiptResult> AcceptRevokeAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanDecideRevoke(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsAcceptRevoke, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, ReceiptStatus.Rvkd);
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "ACCEPT_REVOKE", old, @new, user.Id, ip, null, c);
if (!await repository.RevokeAsync(id, ReceiptStatus.PendingRvkd, null, null, user.UserId, c)) throw NoAuthority();
return true;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, id);
}
public async Task<ReceiptResult> RejectRevokeAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if (!ReceiptRules.CanDecideRevoke(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsRejectRevoke, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.StatusLog(r.StatusCode, ReceiptStatus.Received);
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
await repository.AddLogAsync(id, "REJECT_REVOKE", old, @new, user.Id, ip, null, c);
if (!await repository.RejectRevokeAsync(id, c)) throw NoAuthority();
return true;
}, ct);
return new ReceiptResult(ReceiptMessages.Done, id);
}
/// <summary>printPermitsReceipts: a zero-fee receipt cannot be printed; the print is logged. The page draws the slip.</summary>
public async Task<ReceiptPrint> PrintAsync(long id, string? ip, CancellationToken ct)
{
var r = await Load(id, ct);
if ((r.Fees ?? 0) == 0) throw new BusinessException(ReceiptErrors.ZeroFees, ReceiptMessages.ZeroFees);
if (!ReceiptRules.CanPrint(r.StatusCode) || !await permissions.IsAllowedAsync(PermissionKeys.ReceiptsPrint, ct)) throw NoAuthority();
var (old, @new) = ReceiptRules.PrintLog();
await repository.AddLogAsync(id, "PRINT", old, @new, user.Id, ip, null, ct);
var description = r.ReceiptType == 8 ? "بدل تصريح ملغي" : string.IsNullOrEmpty(r.FmShipmentMode) ? "تصريح واحد" : "تصريح مزدوج";
var showCargo = r.ReceiptType is not (1 or 5);
return new ReceiptPrint(r, r.Credit == 0 ? "سند قبض" : "مطالبة مالية", description, showCargo, ShowGnpn: false);
}
// ---------------------------------------------------------------- helpers for the create form
public async Task<ReceiptAutoFill?> GnPermitAsync(string tn, CancellationToken ct) =>
string.IsNullOrWhiteSpace(tn) ? null : await repository.GetGnPermitAsync(tn.Trim(), ct);
public async Task<ReceiptAutoFill?> DriverAsync(string nnpn, CancellationToken ct) =>
string.IsNullOrWhiteSpace(nnpn) ? null : await repository.GetDriverAsync(nnpn.Trim(), ct);
// ---------------------------------------------------------------- Excel
public async Task<ExportFile> ExportAsync(ReceiptQuery query, CancellationToken ct)
{
await Require(PermissionKeys.ReceiptsReport, ct);
var rows = new List<ReceiptRow>();
for (var p = 1; rows.Count < ExportLimit; p++)
{
var r = await SearchAsync(query, new PageRequest(p, PageRequest.MaxPageSize), ct);
rows.AddRange(r.Items);
if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break;
}
string D(DateTime? d) => d?.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture) ?? string.Empty;
var cols = new List<ReportColumn>
{
new("counter", "متسلسل", "#"), new("receiptNo", "الرقم", "Receipt no."), new("pn", "رقم التصريح", "Permit"), new("company", "اسم الشركة", "Company"),
new("cargo", "النمط", "Cargo type"), new("tn", "رقم الشاحنة", "Truck"), new("trn", "رقم المقطورة", "Trailer"), new("drvr", "اسم السائق", "Driver"),
new("nnpn", "الرقم الوطني", "National no."), new("fees", "الأجور", "Fees"), new("credit", "النوع", "Kind"), new("creationDate", "تاريخ الانشاء", "Created"),
new("createdBy", "إنشاء بواسطة", "Created by"), new("confirmationDate", "تاريخ التأكيد", "Confirmed"), new("confirmationBy", "تأكيد بواسطة", "Confirmed by"),
new("confirmationName", "اسم المؤكد", "Confirmed by (name)"), new("status", "الحالة", "Status"), new("source", "طريقة الدفع", "Payment"),
};
var data = rows.Select((r, i) => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
{
["counter"] = i + 1, ["receiptNo"] = r.ReceiptNo, ["pn"] = r.Pn, ["company"] = r.CompanyName, ["cargo"] = r.CargoType, ["tn"] = r.Tn, ["trn"] = r.Trn, ["drvr"] = r.Drvr,
["nnpn"] = r.Nnpn, ["fees"] = r.Fees, ["credit"] = r.Credit == 0 ? "سند قبض" : "مطالبة مالية", ["creationDate"] = D(r.CreationDate), ["createdBy"] = r.CreatedBy,
["confirmationDate"] = D(r.ConfirmationDate), ["confirmationBy"] = r.ConfirmationBy == "0" ? "" : r.ConfirmationBy, ["confirmationName"] = r.ConfirmationName,
["status"] = ReceiptRules.StatusCaption(r.StatusCode), ["source"] = r.CreationSource == 0 ? "نقداً" : "دفع الالكتروني",
}).ToList();
var table = new ReportTable { Key = "PERMITSRECEIPTS", TitleAr = "تقرير الوصولات", TitleEn = "Receipts report", Columns = cols, Rows = data };
return new ExportFile(excel.Build(table, user.UserId, DateTime.Now, true), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "PERMITSRECEIPTS.xlsx");
}
// ---------------------------------------------------------------- audit
/// <summary>
/// permitsReceiptsAudit: compares the receipts confirmed by a user / in a period with the permits Excel file; the receipts that match move to AUDITED
/// (TENDER_SUP, SU, SAP) or COMPLETED (AM, the financial audit). Every compared receipt gets an audit log row; the result is an Excel file.
/// </summary>
public async Task<AuditResult> AuditAsync(Stream file, string originalName, AuditFilter filter, string? ip, CancellationToken ct)
{
await Require(PermissionKeys.ReceiptsAudit, ct);
string[] statuses; string next, action;
if (user.IsInAnyRole("TENDER_SUP", "SU", "QUEUE_OP", "SAP")) { statuses = [ReceiptStatus.NotReceived, "ALL", ReceiptStatus.Received, ReceiptStatus.Audited, ReceiptStatus.Unpaid]; next = ReceiptStatus.Audited; action = "AUDIT"; }
else if (user.IsInRole("AM")) { statuses = [ReceiptStatus.Audited, ReceiptStatus.Completed]; next = ReceiptStatus.Completed; action = "FIN_AUDIT"; }
else throw NoAuthority();
var hasUser = !string.IsNullOrWhiteSpace(filter.ConfirmationBy);
if (!hasUser && filter.DateFrom is null && filter.DateTo is null) throw new BusinessException(ReceiptErrors.AuditInput, ReceiptMessages.AuditFilter);
if ((filter.DateFrom is null) != (filter.DateTo is null)) throw new BusinessException(ReceiptErrors.AuditInput, ReceiptMessages.AuditBothDates);
if (filter.DateFrom is { } f && filter.DateTo is { } t && f > t) throw new BusinessException(ReceiptErrors.AuditInput, ReceiptMessages.ConfirmationRange);
if (hasUser && !await repository.UserExistsAsync(filter.ConfirmationBy!.Trim(), ct)) throw new BusinessException(ReceiptErrors.UserNotFound, ReceiptMessages.UserNotFound);
var sheet = excel.ReadFirstSheet(file);
if (sheet.Count <= 3) throw new BusinessException(ReceiptErrors.AuditInput, ReceiptMessages.UploadFile);
string Cell(string[] r, int i) => i < r.Length ? (r[i] ?? string.Empty).Trim() : string.Empty;
// header on row 3 (legacy headerrow=3): SN, SCAC, COMPANY, NNPN, DRIVER, INBOUNDTYPECODE, SHIPMENTMODE, PERMIT_STATUS, PN, TN, TRN, ORIGINADDRESSID, DESTINATIONADDRESSID, ...
var permits = sheet.Skip(3).Select(r => new AuditFileRow
{
Scac = Cell(r, 1), Nnpn = Cell(r, 3), InboundTypeCode = Cell(r, 5), ShipmentMode = Cell(r, 6), PermitStatus = Cell(r, 7), Pn = Cell(r, 8), Tn = Cell(r, 9), Trn = Cell(r, 10),
OriginAddressId = Cell(r, 11), DestinationAddressId = Cell(r, 12), Crn = Cell(r, 14), CaCode = Cell(r, 15), IsEmployeeMistake = Cell(r, 18),
}).ToList();
var receipts = await repository.GetForAuditAsync(statuses, filter, ct);
if (receipts.Count == 0) throw new BusinessException(ReceiptErrors.NoReceipts, ReceiptMessages.NoReceiptsForUser);
var lookups = await repository.GetAuditLookupsAsync(ct);
var (lines, audited, identical) = ReceiptAudit.Compare(permits, receipts, lookups, filter.ConfirmationBy, ReceiptRules.StatusCaption);
if (audited.Count > 0)
await unitOfWork.ExecuteInTransactionAsync(async c =>
{
foreach (var a in audited)
await repository.AddLogAsync(a.Id, action, "{}", ReceiptRules.AuditResultJson(a.Result, a.Remarks), user.Id, ip, originalName, c);
if (identical.Count > 0) await repository.SetStatusAsync(identical, next, c);
return true;
}, ct);
var cols = new List<ReportColumn>
{
new("pn", "رقم التصريح", "Permit"), new("permitStatus", "حالة التصريح", "Permit status"), new("receiptNo", "رقم الوصل", "Receipt"), new("fees", "الأجور", "Fees"),
new("receiptStatus", "حالة الوصل", "Receipt status"), new("date", "تاريخ الوصل", "Receipt date"), new("result", "النتيجة", "Result"), new("remark", "الملاحظات", "Remarks"),
};
var rows = lines.Skip(1).Select(l => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
{
["pn"] = l.Pn, ["permitStatus"] = l.PermitStatus, ["receiptNo"] = l.ReceiptNo, ["fees"] = l.Fees, ["receiptStatus"] = l.ReceiptStatus, ["date"] = l.ConfirmationDate,
["result"] = l.Result, ["remark"] = l.Remark,
}).ToList();
var table = new ReportTable { Key = "PERMITSAUDIT", TitleAr = "نتيجة تدقيق الوصولات", TitleEn = "Receipts audit result", Columns = cols, Rows = rows };
var name = Path.GetFileNameWithoutExtension(originalName) + "_result.xlsx";
return new AuditResult(excel.Build(table, user.UserId, DateTime.Now, true), name, receipts.Count, identical.Count);
}
// ------------------------------------------------------------------------------------------------------------------------------------
private async Task<ReceiptRow> Load(long id, CancellationToken ct) =>
await repository.GetAsync(id, ct) ?? throw new NotFoundException("Receipt", id);
private async Task Require(string key, CancellationToken ct)
{
if (!await permissions.IsAllowedAsync(key, ct)) throw NoAuthority();
}
private async Task<ReceiptActions> ActionsAsync(ReceiptRow r, CancellationToken ct)
{
var asksOnly = user.IsInAnyRole("SU", "QUEUE_OP");
var revoke = false;
if (ReceiptRules.CanRevokeOpen(r.StatusCode))
revoke = await permissions.IsAllowedAsync(asksOnly ? PermissionKeys.ReceiptsRevokeRequest : PermissionKeys.ReceiptsRevoke, ct)
&& !(ReceiptRules.IsStatus(r.StatusCode, ReceiptStatus.Received) && r.RequestId is not null); // legacy hides cancel for a receipt made by a permit request
else if (ReceiptRules.CanRevokeAudited(r.StatusCode) && !asksOnly)
revoke = await permissions.IsAllowedAsync(PermissionKeys.ReceiptsRevokeAudited, ct);
return new ReceiptActions(
Update: ReceiptRules.CanUpdate(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsUpdate, ct),
Confirm: ReceiptRules.CanConfirm(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsConfirm, ct),
Paid: ReceiptRules.CanPay(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsPaid, ct),
Print: ReceiptRules.CanPrint(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsPrint, ct),
Revoke: revoke,
AcceptRevoke: ReceiptRules.CanDecideRevoke(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsAcceptRevoke, ct),
RejectRevoke: ReceiptRules.CanDecideRevoke(r.StatusCode) && await permissions.IsAllowedAsync(PermissionKeys.ReceiptsRejectRevoke, ct));
}
private static string? RegistrarClean(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim();
private static ForbiddenException NoAuthority() => new(ReceiptErrors.NoAuthority, ReceiptMessages.NoAuthority);
}

View File

@ -0,0 +1,144 @@
using System.Globalization;
using System.Xml.Linq;
namespace NTP.Application.Refinery.Sync;
/// <summary>
/// One trip row of the Jopetrol "QueryOnTransByStatus" answer (legacy REFINERY_OIL.cfm extractInputs): the JDE tag names are the service's,
/// the numbers are already converted the way legacy converted them (weights in kg / 1000 = tons, temperature / 100).
/// </summary>
public sealed class JopetrolTripRecord
{
public string Pn { get; set; } = "";
public DateTime? DispatchDate { get; set; }
public string LoadingNo { get; set; } = "";
public DateTime? ActualLoadingDate { get; set; }
public string ActualLoadingTime { get; set; } = "";
public string LoadingCenter { get; set; } = "";
public string ClientNo { get; set; } = "";
public string Tn { get; set; } = "";
public string Trn { get; set; } = "";
public string Nnpn { get; set; } = "";
public string MaterialNo { get; set; } = "0";
public string MenagateNo { get; set; } = "0";
public decimal EmptyWeight { get; set; }
public decimal GrossWeight { get; set; }
public decimal NetLoadingWeight { get; set; }
public decimal? StandardUnitsWeight { get; set; }
public decimal LitersWeight { get; set; }
public decimal? Density { get; set; }
public decimal? Temperature { get; set; }
public decimal? Flag { get; set; }
public string DischargeAuthorizationNo { get; set; } = "";
public decimal? DischargeAuthorizationYear { get; set; }
public DateTime? DischargeEntryDate { get; set; }
public string DischargeEntryTime { get; set; } = "";
public DateTime? DischargeExitDate { get; set; }
public string DischargeExitTime { get; set; } = "";
public decimal ActualGrossWeight { get; set; }
public decimal ActualEmptyWeight { get; set; }
public decimal NetDischargeWeight { get; set; }
public decimal WaterAmount { get; set; }
public decimal? SedimentAmount { get; set; }
/// <summary>NF55STATUS: 0 new, 1 released, 2-3 loaded, 4 arrived, 5 discharging, 6 discharged, -1 cancel requested, -2 cancelled.</summary>
public int TripStatus { get; set; }
public string UserId { get; set; } = "";
public string TripLastUpdateDate { get; set; } = "";
public decimal? DayTime { get; set; }
public string ProgramId { get; set; } = "";
public string WorkStnId { get; set; } = "";
public string ExchangeClaimNo { get; set; } = "";
public string PaidAmountWater { get; set; } = "";
/// <summary>1 when the service says there is water that is not accompanied (NFY55WFLAG = 0), else 0.</summary>
public int WaterFlag { get; set; }
/// <summary>The node as a flat name -> text map (what legacy kept as NEW_DATA of the log row).</summary>
public IReadOnlyDictionary<string, string> Raw { get; set; } = new Dictionary<string, string>();
}
public static class JopetrolTripParser
{
/// <summary>JDE julian date "CYYDDD" (century offset, year, day of the year); legacy used substr(2,5) with to_date 'YYDDD'. Empty / invalid = null.</summary>
public static DateTime? JdeDate(string? text)
{
var t = (text ?? "").Trim();
if (t.Length < 6 || !int.TryParse(t.AsSpan(0, 1), out var c) || !int.TryParse(t.AsSpan(1, 2), out var yy) || !int.TryParse(t.AsSpan(3, 3), out var doy)) return null;
var year = 1900 + c * 100 + yy;
if (doy < 1 || doy > (DateTime.IsLeapYear(year) ? 366 : 365)) return null;
return new DateTime(year, 1, 1).AddDays(doy - 1);
}
/// <summary>Parses the elements of one NewDataSet child. The tags legacy read without a default are required (a FormatException says which).</summary>
public static JopetrolTripRecord Parse(XElement node)
{
string? Opt(string name) => node.Elements().FirstOrDefault(e => e.Name.LocalName == name)?.Value;
string Req(string name) => (Opt(name) ?? throw new FormatException($"Jopetrol trip row without {name}")).Trim();
string Txt(string name) => (Opt(name) ?? "").Trim();
static decimal? Num(string? s) => decimal.TryParse((s ?? "").Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : null;
decimal Div(string name, decimal by) => (Num(Opt(name)) ?? 0m) / by;
var waterFlag = 0;
if (Opt("NFY55WFLAG") is { } wf && Num(wf) == 0m) waterFlag = 1; // legacy: eq 0 = there is water but it is not accompanying
return new JopetrolTripRecord
{
Pn = Req("NF55DOCO"),
DispatchDate = JdeDate(Req("NFTRDJ")),
LoadingNo = Txt("NFLDNM"),
ActualLoadingDate = JdeDate(Opt("NFLOAD")),
ActualLoadingTime = Txt("NFLSLT"),
LoadingCenter = Txt("NFMCU"),
ClientNo = Req("NFAN8"),
Tn = Req("NF55HEAD"),
Trn = Req("NF55TRAIL"),
Nnpn = Req("NF55DRNID"),
MaterialNo = Opt("NFLITM") is { } m ? m.Trim() : "0",
MenagateNo = Opt("NF55NITM") is { } n ? n.Trim() : "0",
EmptyWeight = Div("NFBFWT", 1000),
GrossWeight = Div("NFAFWT", 1000),
NetLoadingWeight = Div("NFWGTR", 1000),
StandardUnitsWeight = Opt("NF55STUM") is null ? 0m : Num(Opt("NF55STUM")),
LitersWeight = Div("NFAMBR", 1000),
Density = Opt("NFDNTY") is null ? 0m : Num(Opt("NFDNTY")),
Temperature = Opt("NFTEMP") is null ? null : Num(Opt("NFTEMP")) / 100m,
Flag = Num(Opt("NFEV01")),
DischargeAuthorizationNo = Txt("NFY55DISPN"),
DischargeAuthorizationYear = Num(Opt("NFY55DSYE")),
DischargeEntryDate = JdeDate(Opt("NFY55DEND")),
DischargeEntryTime = Txt("NFY55DENT"),
DischargeExitDate = JdeDate(Opt("NFY55DEXD")),
DischargeExitTime = Txt("NFY55DEXT"),
ActualGrossWeight = Div("NF55BFWT", 1000),
ActualEmptyWeight = Div("NF55AFWT", 1000),
NetDischargeWeight = Div("NFAWGT", 1000),
WaterAmount = Div("NFY55WQ", 1000),
SedimentAmount = Num(Opt("NFY55RQ")),
TripStatus = int.TryParse(Req("NF55STATUS"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var s) ? s : throw new FormatException("Jopetrol trip row with a non numeric NF55STATUS"),
UserId = Req("NFUSER"),
TripLastUpdateDate = Req("NFUPMJ"),
DayTime = Num(Opt("NFTDAY")),
ProgramId = Txt("NFPID"),
WorkStnId = Txt("NFJOBN"),
ExchangeClaimNo = Txt("NF55CREF"),
PaidAmountWater = Txt("NFY55PWQ"),
WaterFlag = waterFlag,
Raw = node.Elements().GroupBy(e => e.Name.LocalName).ToDictionary(g => g.Key, g => g.First().Value.Trim()),
};
}
/// <summary>
/// Status code of a trip row (legacy callInsertDbBulk / callUpdateDbBulk). A new row maps 0 NEW, 1 RESD, 2-3 LOADED, 4 ARRIVE_LOCATION, 5 DISCHARGING,
/// 6 DISCHARGED. An update only moves a trip forward on 2-6 and keeps <paramref name="current"/> for 0 and 1 (legacy quirk: those come through
/// the explicit "update to 1" / cancel steps).
/// </summary>
public static string StatusCodeOf(int tripStatus, string? current, bool forInsert) => tripStatus switch
{
0 when forInsert => "NEW",
1 when forInsert => "RESD",
2 or 3 => "LOADED",
4 => "ARRIVE_LOCATION",
5 => "DISCHARGING",
6 => "DISCHARGED",
_ => current ?? "NEW",
};
}

View File

@ -0,0 +1,75 @@
using System.Globalization;
using System.Net;
using NTP.Application.Abstractions;
namespace NTP.Application.Refinery.Sync;
public interface IRefineryDailyReportRepository
{
/// <summary>First: net wage of the EXCHANGED trips that have no wage claim. Second: net wage (CalculateRefinaryAmountReport) of the trips of the NEW wage claims.</summary>
Task<(decimal First, decimal Second)> GetTotalsAsync(CancellationToken ct = default);
}
public interface IRefineryDailyReportService
{
/// <summary>true when the mail was sent.</summary>
Task<bool> SendAsync(CancellationToken ct);
}
/// <summary>Port of jobs/RefineryTrip_Exchange_email.cfm: the daily refinery exchange report mail ("التقرير اليومي لعطاء الصرف").</summary>
public sealed class RefineryDailyReportService(
IRefineryDailyReportRepository repo, IMailService mail, IRefineryJobSettingsService settings) : IRefineryDailyReportService
{
public const string Subject = "التقرير اليومي لعطاء الصرف";
public async Task<bool> SendAsync(CancellationToken ct)
{
var o = settings.Value;
var (first, second) = await repo.GetTotalsAsync(ct);
var html = RefineryDailyReportHtml.Build(first, second, DateTime.Now, o.LogoEnUrl, o.LogoArUrl);
return await mail.SendHtmlAsync(o.DailyReportRecipients, Subject, html, ct);
}
}
/// <summary>The mail body of the daily report (legacy cfsavecontent), kept apart so it can be tested.</summary>
public static class RefineryDailyReportHtml
{
/// <summary>"1,234.500 دينار". Legacy numberformat switched between '000.000' and '0,000.000' on the text length; one thousands format here.</summary>
public static string Dinars(decimal v) => v.ToString("#,##0.000", CultureInfo.InvariantCulture) + " دينار";
public static string Build(decimal first, decimal second, DateTime now, string logoEnUrl, string logoArUrl)
{
static string E(string s) => WebUtility.HtmlEncode(s);
var date = now.AddDays(-1).ToString("dddd, MMMM d, yyyy", CultureInfo.InvariantCulture); // legacy dateFormat(now()-1, "full")
var year = now.Year.ToString(CultureInfo.InvariantCulture);
const string value = "font: normal 20px tahoma;text-align:center;color:#0C5383;padding:2px;color:#D16475";
const string label = "background-color:#8BAF33;color:#0C5383;font-family:tahoma;font-size:14px;font-weight:bold;padding:5px;";
static string Row(string text, string amount, string label, string value) =>
$"<tr><td><table dir=\"rtl\" width=\"100%\" border=\"0\" style=\"background:white;padding:0.5rem;border-radius:0.5rem;height:105px\"><tr>"
+ $"<td align=\"right\" style=\"{label}\">{E(text)}</td><td style=\"{value}\">{E(amount)}</td></tr><tr><td colspan=\"6\" height=\"5\"></td></tr></table></td></tr>";
return $"""
<body style="background-color:#F1F1F1;">
<table align="center" border="0" cellpadding="0" cellspacing="0" width="800" style="border:#1e9ff2 1px solid;" bgcolor="#fff">
<tr><td><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>
<td align="left" bgcolor="#0b6696" style="padding:40px 0 30px 0;"><img src="{E(logoEnUrl)}" alt="Nafith" style="display:block;" /></td>
<td align="right" bgcolor="#0b6696" style="padding:40px 0 30px 0;"><img src="{E(logoArUrl)}" alt="Nafith" style="display:block;" /></td>
</tr></table></td></tr>
<tr><td><div style="background-color:#f3f5fb;text-align:center;word-wrap:break-word;"><table width="100%"><tr><td><table width="100%" style="text-align:center;padding:.5rem;">
<tr><td><table width="100%" style="text-align:center;">
<tr><td width="100%" colspan="2" style="color:#2C98D4;font-family:tahoma;font-size:13px;font-weight:bold;">{E(date)}</td></tr>
<tr><td width="100%" colspan="2" style="color:#2C98D4;font-family:tahoma;font-size:13px;font-weight:bold;">التقرير اليومي لعطاء الصرف</td></tr>
<tr><td colspan="2"><hr style="color:#2E98D4" size="1"></td></tr></table></td></tr>
{Row("اجمالي صافي قيمة اجور النقل للارساليات التي تم صرفها ولم يتم اصدار مطالبة بها", Dinars(first), label, value)}
{Row("اجمالي صافي قيمة اجور النقل لمطالبات صرف اجور النقل التي لم يتم تسديدها", Dinars(second), label, value)}
<tr><td><h5 style="padding-top:8px;margin:0;font-family:tahoma;color:#7C8087;text-align:center">قد تكون بعض الإرساليات بحالة تم الصرف لم يتم تحويلها من قبل القسم المالي بعد</h5></td></tr>
</table></td></tr></table></div></td></tr>
<tr><td style="border:.50px solid #1e9ff2;padding:0 5px"></td></tr>
<tr><td><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr bgcolor="#1e9ff2">
<td bgcolor="#1e9ff2" width="75%" style="text-align:left;padding-top:10px;font-family:Arial,sans-serif;"><h3 style="color:white;">&reg; Nafith {year}</h3></td>
<td width="75%" style="text-align:right;padding-top:10px;font-family:Arial,sans-serif;"><h3 style="color:white;">{year} نافذ &reg;</h3></td>
</tr></table></td></tr>
</table></body>
""";
}
}

View File

@ -0,0 +1,105 @@
using System.Globalization;
using System.Net;
using System.Xml.Linq;
using NTP.Application.Abstractions;
namespace NTP.Application.Refinery.Sync;
/// <summary>
/// Port of jobs/REFINERY_OIL.cfm: for every Jopetrol trip status from -1 to 6 the trips of that status are read and
/// - a trip that is not in REFINERY_TRIPS yet is created (not for -1);
/// - status -1 (cancel requested): the trip becomes -1, Jopetrol is told UpdateStatusToMinus2 and, when it answers "To -2", the trip becomes RVKD / -2 and a mail goes out;
/// - status 0: Jopetrol is told UpdateStatusTo1 and, when it answers "To 1", the trip becomes RESD / 1;
/// - other statuses: the trip is updated when the Jopetrol status differs, unless it is already in the payment part of its life.
/// The two status-changing calls to Jopetrol only run when <see cref="RefineryJobOptions.JopetrolWriteBack"/> is on (legacy: live server only).
/// A trip that fails (bad row, database error) is counted and skipped; the run goes on.
/// </summary>
public sealed class RefineryOilSyncService(
IJopetrolTripsGateway jopetrol,
IRefineryOilSyncRepository repo,
IUnitOfWork unit,
IMailService mail,
IRefineryJobSettingsService settings) : IRefineryOilSyncService
{
/// <summary>Statuses after which Jopetrol data no longer overwrites a trip (legacy listFindNoCase).</summary>
private static readonly string[] Protected = ["PENDING_EXCHANGE", "EXCHANGED", "READY_TO_PAY", "COMPLETE"];
public async Task<RefineryOilSyncResult> RunAsync(CancellationToken ct)
{
if (!jopetrol.IsReady) return new RefineryOilSyncResult(0, 0, 0, 0, 0, "خدمة جوبترول غير مفعلة أو غير مكتملة الإعداد (Refinery:Jopetrol)");
var o = settings.Value;
int inserted = 0, updated = 0, released = 0, cancelled = 0, errors = 0;
var samples = new List<string>();
for (var status = -1; status <= 6; status++)
{
ct.ThrowIfCancellationRequested();
IReadOnlyList<XElement> nodes;
try { nodes = await jopetrol.QueryOnTransByStatusAsync(status, ct); }
catch (Exception ex) when (!ct.IsCancellationRequested)
{
errors++;
if (samples.Count < 3) samples.Add($"استعلام الحالة {status}: {ex.Message}");
continue;
}
foreach (var node in nodes)
{
try
{
var trip = JopetrolTripParser.Parse(node);
var existing = await repo.FindByPnAsync(trip.Pn, ct);
if (existing is null)
{
// a cancel request for a trip we never had has nothing to update
if (status != -1 && await InsertAsync(trip, o, ct)) inserted++;
continue;
}
if (status == -1)
{
if (!o.JopetrolWriteBack) continue;
await UpdateAsync(existing, trip, "RVKD", -1, o, ct);
var answer = await jopetrol.UpdateStatusToMinus2Async(existing.Pn, ct);
if (answer?.Contains("Status Updated successfully To -2", StringComparison.OrdinalIgnoreCase) == true)
{
var current = await repo.FindByPnAsync(trip.Pn, ct) ?? existing;
await UpdateAsync(current, trip, "RVKD", -2, o, ct);
cancelled++;
await mail.SendHtmlAsync(o.CancelledTripRecipients, $"إلغاء إرسالية نفط خام ({trip.Pn}) ",
$"تم إلغاء الارسالية ({WebUtility.HtmlEncode(trip.Pn)})", ct);
}
}
else if (status == 0)
{
if (!o.JopetrolWriteBack) continue;
var answer = await jopetrol.UpdateStatusTo1Async(existing.Pn, ct);
if (answer?.Contains("Status Updated successfully To 1", StringComparison.OrdinalIgnoreCase) == true)
{
await UpdateAsync(existing, trip, "RESD", 1, o, ct);
released++;
}
}
else if (!string.Equals(existing.TripStatus?.Trim(), trip.TripStatus.ToString(CultureInfo.InvariantCulture), StringComparison.Ordinal)
&& !Protected.Contains(existing.StatusCode ?? "", StringComparer.OrdinalIgnoreCase))
{
await UpdateAsync(existing, trip, JopetrolTripParser.StatusCodeOf(trip.TripStatus, existing.StatusCode, forInsert: false), trip.TripStatus, o, ct);
updated++;
}
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
errors++;
if (samples.Count < 3) samples.Add($"الحالة {status}: {ex.Message}");
}
}
}
return new RefineryOilSyncResult(inserted, updated, released, cancelled, errors, samples.Count == 0 ? null : string.Join(" | ", samples));
}
private Task<bool> InsertAsync(JopetrolTripRecord trip, RefineryJobOptions o, CancellationToken ct) =>
unit.ExecuteInTransactionAsync(c => repo.InsertAsync(trip, JopetrolTripParser.StatusCodeOf(trip.TripStatus, null, forInsert: true), o.SyncUser, c), ct);
private Task UpdateAsync(ExistingTrip old, JopetrolTripRecord trip, string statusCode, int tripStatus, RefineryJobOptions o, CancellationToken ct) =>
unit.ExecuteInTransactionAsync(async c => { await repo.UpdateAsync(old, trip, statusCode, tripStatus, o.SyncUser, c); return 0; }, ct);
}

View File

@ -0,0 +1,76 @@
using System.Xml.Linq;
namespace NTP.Application.Refinery.Sync;
/// <summary>Settings of the refinery jobs (section "Refinery:Jobs").</summary>
public sealed class RefineryJobOptions
{
public const string SectionName = "Refinery:Jobs";
/// <summary>
/// Legacy REFINERY_OIL.cfm only called the status-changing Jopetrol services (UpdateStatusTo1 / UpdateStatusToMinus2) on the live server
/// (cgi.SERVER_PORT 443). false (default) = read-only: trips are created and updated from Jopetrol but nothing is written back to Jopetrol.
/// </summary>
public bool JopetrolWriteBack { get; set; }
/// <summary>User written into CREATED_BY / UPDATED_BY of the trips the sync touches (legacy hard-coded 16186973).</summary>
public string SyncUser { get; set; } = "16186973";
/// <summary>Receivers of the "trip cancelled" e-mail (legacy hard-coded one address).</summary>
public string[] CancelledTripRecipients { get; set; } = [];
/// <summary>Receivers of the daily refinery exchange report (legacy application.REFINERY_EMAIL).</summary>
public string[] DailyReportRecipients { get; set; } = [];
public string LogoEnUrl { get; set; } = "https://aqtcs.nafith.net/frontend/design/images/nafithENW.png";
public string LogoArUrl { get; set; } = "https://aqtcs.nafith.net/frontend/design/images/nafithARW.png";
}
public interface IRefineryJobSettingsService
{
RefineryJobOptions Value { get; }
}
/// <summary>Jopetrol TransportPaymentWS calls of the trip sync (legacy REFINERY_OIL.cfm). Not configured (Refinery:Jopetrol) = <see cref="IsReady"/> false.</summary>
public interface IJopetrolTripsGateway
{
bool IsReady { get; }
/// <summary>QueryOnTransByStatus: the children of NewDataSet (one element per trip); empty when the answer has none.</summary>
Task<IReadOnlyList<XElement>> QueryOnTransByStatusAsync(int status, CancellationToken ct = default);
/// <summary>UpdateStatusTo1Result text ("Status Updated successfully To 1" when it worked).</summary>
Task<string?> UpdateStatusTo1Async(string pn, CancellationToken ct = default);
/// <summary>UpdateStatusToMinus2Result text ("Status Updated successfully To -2" when it worked).</summary>
Task<string?> UpdateStatusToMinus2Async(string pn, CancellationToken ct = default);
}
public sealed class ExistingTrip
{
public long Id { get; set; }
public string Pn { get; set; } = "";
public string? TripStatus { get; set; }
public string? StatusCode { get; set; }
}
public interface IRefineryOilSyncRepository
{
Task<ExistingTrip?> FindByPnAsync(string pn, CancellationToken ct = default);
/// <summary>Inserts the trip and its CREATE log row. false when the PN already exists (unique key): legacy skipped those silently.</summary>
Task<bool> InsertAsync(JopetrolTripRecord trip, string statusCode, string createdBy, CancellationToken ct = default);
/// <summary>Updates the trip from the Jopetrol row and writes one log row (method = the new status code).</summary>
Task UpdateAsync(ExistingTrip old, JopetrolTripRecord trip, string statusCode, int tripStatus, string updatedBy, CancellationToken ct = default);
}
public sealed record RefineryOilSyncResult(int Inserted, int Updated, int Released, int Cancelled, int Errors, string? Note = null)
{
public int Total => Inserted + Updated + Released + Cancelled;
}
public interface IRefineryOilSyncService
{
Task<RefineryOilSyncResult> RunAsync(CancellationToken ct);
}

View File

@ -0,0 +1,72 @@
using NTP.Application.Common;
using NTP.Application.Grains.Orders;
namespace NTP.Application.Registrar;
/// <summary>Settings of the registrar screens (section "Registrar").</summary>
public sealed class RegistrarOptions
{
public const string SectionName = "Registrar";
/// <summary>Where the mobile app stored the pictures (legacy application.aqTcsUploadedPath); a file is <c>{base}/{ENTITY}/{FILENAME}</c>. The files stay on that host.</summary>
public string AttachmentsBaseUrl { get; set; } = "https://aqtcs2.nafith.net/uploadedfiles1/AqabaTCS";
}
public interface IRegistrarSettingsService
{
RegistrarOptions Value { get; }
}
/// <summary>An ATTACHMENTS row (NTP schema).</summary>
public sealed class RegistrarAttachmentRow
{
public long Id { get; set; }
public string? FileName { get; set; }
}
/// <summary>DRIVERS_INFO / TRUCKS_INFO / TRAILERS_INFO (primary schema).</summary>
public interface IRegistrarRepository
{
/// <summary>Oldest first (legacy sort p.id ASC: a work queue).</summary>
Task<PagedResult<RegistrarRecord>> SearchAsync(RegistrarKind kind, RegistrarQuery query, PageRequest page, CancellationToken ct = default);
Task<RegistrarRecord?> GetAsync(RegistrarKind kind, long id, CancellationToken ct = default);
/// <summary>Writes the form values and stamps UPDATED_BY / LAST_UPDATE_DATE; false when the record is no longer in <paramref name="expectedStatus"/>.</summary>
Task<bool> UpdateAsync(RegistrarKind kind, long id, string expectedStatus, RegistrarUpdateRequest values, string userId, CancellationToken ct = default);
/// <summary>Status change (+ revoke reason) with UPDATED_BY / LAST_UPDATE_DATE; false when the record is no longer in <paramref name="fromStatus"/>.</summary>
Task<bool> ChangeStatusAsync(RegistrarKind kind, long id, string fromStatus, string toStatus, string userId, string? revokeReason, CancellationToken ct = default);
/// <summary>The plate of the first record of <paramref name="kind"/> (not revoked, Jordanian) that already uses this chassis number, or null.</summary>
Task<string?> FindPlateByVinAsync(RegistrarKind kind, string vin, long? excludeId, CancellationToken ct = default);
}
/// <summary>Downloads a stored picture. The files stay on the legacy upload host (<see cref="RegistrarOptions.AttachmentsBaseUrl"/>); the API proxies them so the page needs no access to that host.</summary>
public interface IRegistrarFileGatewayService
{
/// <summary>Null when the host does not have the file.</summary>
Task<RegistrarFile?> FetchAsync(string url, string fileName, CancellationToken ct = default);
}
/// <summary>Lists, captions and attachments (NTP schema).</summary>
public interface IRegistrarLookupRepository
{
Task<IReadOnlyDictionary<string, IReadOnlyList<LookupItem>>> GetListsAsync(CancellationToken ct = default);
Task<IReadOnlyList<RegistrarAttachmentRow>> GetAttachmentsAsync(string entity, long id, CancellationToken ct = default);
/// <summary>The Arabic text of a LT_CAPTION code, or null.</summary>
Task<string?> GetCaptionAsync(string code, CancellationToken ct = default);
}
public interface IRegistrarService
{
Task<PagedResult<RegistrarRecord>> SearchAsync(RegistrarKind kind, RegistrarQuery query, PageRequest page, CancellationToken ct);
Task<RegistrarDetail> GetAsync(RegistrarKind kind, long id, CancellationToken ct);
Task<RegistrarResult> UpdateAsync(RegistrarKind kind, long id, RegistrarUpdateRequest request, CancellationToken ct);
Task<RegistrarResult> CompleteAsync(RegistrarKind kind, long id, CancellationToken ct);
Task<RegistrarResult> RevokeAsync(RegistrarKind kind, long id, string? reason, CancellationToken ct);
Task<RegistrarResult> ReopenAsync(RegistrarKind kind, long id, CancellationToken ct);
Task<RegistrarLookups> GetLookupsAsync(CancellationToken ct);
Task<RegistrarFile> GetAttachmentAsync(RegistrarKind kind, long id, long attachmentId, CancellationToken ct);
Task<ExportFile> ExportAsync(RegistrarKind kind, RegistrarQuery query, CancellationToken ct);
}

View File

@ -0,0 +1,171 @@
namespace NTP.Application.Registrar;
/// <summary>The three registrations a company registers from the mobile app and the registrar reviews (legacy entities DRIVERINFO, TRUCKINFO, TRAILERINFO).</summary>
public enum RegistrarKind
{
Driver,
Truck,
Trailer,
}
/// <summary>Row of DRIVERS_INFO / TRUCKS_INFO / TRAILERS_INFO. One class for the three tables (columns a table does not have stay null). Settable properties: Dapper + Oracle NUMBER.</summary>
public class RegistrarRecord
{
public long Id { get; set; }
public string? StatusCode { get; set; }
/// <summary>TN (truck) / TRN (trailer); empty for a driver.</summary>
public string? PlateNo { get; set; }
/// <summary>TN_CODE / TRN_CODE: the code of a foreign plate.</summary>
public string? PlateCode { get; set; }
public string? Nationality { get; set; }
// driver
public string? Nnpn { get; set; }
public string? NameAr { get; set; }
public string? NameEn { get; set; }
public DateTime? DateOfBirth { get; set; }
public string? BloodGroup { get; set; }
public string? Address { get; set; }
public string? LicenseType { get; set; }
public DateTime? LicenseIssueDate { get; set; }
public string? Mobile { get; set; }
// licence (all three)
public string? LicenseNo { get; set; }
public DateTime? LicenseExpiryDate { get; set; }
// truck / trailer
public string? LicenseRegistrationNo { get; set; }
public string? Manufacturer { get; set; }
public long? ManufactureYear { get; set; }
/// <summary>TRUCK_TYPE / TRAILER_TYPE.</summary>
public string? VehicleType { get; set; }
/// <summary>TRUCK_CATEGORY / TRAILER_CATEGORY (صفة الاستعمال).</summary>
public string? Category { get; set; }
public string? Color { get; set; }
public string? SecondaryColor { get; set; }
public string? Model { get; set; }
public string? VinNumber { get; set; }
public string? EngineNumber { get; set; }
public decimal? LoadingWeight { get; set; }
public decimal? GrossWeight { get; set; }
/// <summary>GROSS_WEIGHT - LOADING_WEIGHT (the view column EMPTY_WEIGHT of TRUCK_INFO_VIEW); trucks only.</summary>
public decimal? EmptyWeight { get; set; }
public string? OwnerName { get; set; }
public string? OwnerNnpn { get; set; }
public long? OwnerPhoneNumber { get; set; }
public string? OwnerAddress { get; set; }
public string? Governate { get; set; }
public string? Notes { get; set; }
public string? RevokeReason { get; set; }
public string? CreatedBy { get; set; }
public DateTime? CreationDate { get; set; }
public string? UpdatedBy { get; set; }
public DateTime? LastUpdateDate { get; set; }
}
/// <summary>
/// Grid filters. <see cref="Number"/> is the NNPN (drivers), TN (trucks) or TRN (trailers); equal, case-insensitive. <see cref="Name"/> (drivers, Arabic name) and
/// <see cref="OwnerName"/> (trucks / trailers) are "contains". <see cref="StatusCodes"/> empty = every status.
/// </summary>
public sealed record RegistrarQuery(
string? Number, string? LicenseNo, string? Name, string? OwnerName, string? VinNumber,
DateTime? DateFrom, DateTime? DateTo, IReadOnlyList<string> StatusCodes);
/// <summary>The update form (legacy *InfoForm). Fields a kind does not have are ignored. Year and weights come as text, like the legacy digits-only check.</summary>
public sealed class RegistrarUpdateRequest
{
public string? Nationality { get; set; }
public string? PlateNo { get; set; }
public string? PlateCode { get; set; }
public string? Nnpn { get; set; }
public string? NameAr { get; set; }
public string? NameEn { get; set; }
public string? Mobile { get; set; }
public DateTime? DateOfBirth { get; set; }
public string? BloodGroup { get; set; }
public string? Governate { get; set; }
public string? Address { get; set; }
public string? LicenseNo { get; set; }
public string? LicenseType { get; set; }
public DateTime? LicenseIssueDate { get; set; }
public DateTime? LicenseExpiryDate { get; set; }
public string? LicenseRegistrationNo { get; set; }
public string? OwnerName { get; set; }
public string? OwnerAddress { get; set; }
public string? Manufacturer { get; set; }
public string? Model { get; set; }
public string? Color { get; set; }
public string? SecondaryColor { get; set; }
public string? VehicleType { get; set; }
public string? ManufactureYear { get; set; }
public string? Category { get; set; }
public string? VinNumber { get; set; }
public string? EngineNumber { get; set; }
public string? LoadingWeight { get; set; }
public string? GrossWeight { get; set; }
public string? Notes { get; set; }
}
public sealed record RegistrarRevokeRequest(string? Reason);
/// <summary>What the caller may do with one record in its current status (the legacy PORTLET buttons, decided by STATUS_ACTION_MATRIX).</summary>
public sealed record RegistrarActions(bool Update, bool Complete, bool Revoke, bool Reopen);
/// <summary>An image or file of the registration (table ATTACHMENTS, entity DRIVERINFO / TRUCKINFO / TRAILERINFO). The content is served by the API (GET {id}/attachments/{attachmentId}).</summary>
public sealed record RegistrarAttachment(long Id, string FileName);
/// <summary>The bytes of one attachment, fetched from the host where the mobile app stored it.</summary>
public sealed record RegistrarFile(byte[] Content, string ContentType, string FileName);
public sealed record RegistrarDetail(RegistrarRecord Record, IReadOnlyList<RegistrarAttachment> Attachments, RegistrarActions Actions);
public sealed record RegistrarResult(string Message);
public sealed record LookupItem(string Code, string Ar, string En);
/// <summary>The drop-down lists of the three forms, by list name (legacy LT_PUBLIC lookups and NATIONALITY).</summary>
public sealed record RegistrarLookups(IReadOnlyDictionary<string, IReadOnlyList<LookupItem>> Lists);
public static class RegistrarStatus
{
public const string Pending = "PENDING";
public const string Completed = "COMPLETED";
public const string Revoke = "REVOKE";
public const string Incomplete = "INCOMPLETE";
}
/// <summary>Per kind: URL slug, table, entity name of the attachments and the permission keys.</summary>
public sealed record RegistrarKindInfo(
RegistrarKind Kind, string Slug, string Table, string Entity, string NotificationType, string NotificationNumber,
string Screen, string Update, string? UpdateCompleted, string Complete, string Revoke, string Reopen, string Report);
public static class RegistrarKinds
{
private static readonly RegistrarKindInfo[] All =
[
new(RegistrarKind.Driver, "drivers", "DRIVERS_INFO", "DRIVERINFO", "سائق", "NNPN",
Access.PermissionKeys.RegistrarDrivers, Access.PermissionKeys.RegistrarDriversUpdate, Access.PermissionKeys.RegistrarDriversUpdateCompleted,
Access.PermissionKeys.RegistrarDriversComplete, Access.PermissionKeys.RegistrarDriversRevoke, Access.PermissionKeys.RegistrarDriversReopen,
Access.PermissionKeys.RegistrarDriversReport),
new(RegistrarKind.Truck, "trucks", "TRUCKS_INFO", "TRUCKINFO", "شاحنة", "TN",
Access.PermissionKeys.RegistrarTrucks, Access.PermissionKeys.RegistrarTrucksUpdate, null,
Access.PermissionKeys.RegistrarTrucksComplete, Access.PermissionKeys.RegistrarTrucksRevoke, Access.PermissionKeys.RegistrarTrucksReopen,
Access.PermissionKeys.RegistrarTrucksReport),
new(RegistrarKind.Trailer, "trailers", "TRAILERS_INFO", "TRAILERINFO", "مقطوره", "TRN",
Access.PermissionKeys.RegistrarTrailers, Access.PermissionKeys.RegistrarTrailersUpdate, null,
Access.PermissionKeys.RegistrarTrailersComplete, Access.PermissionKeys.RegistrarTrailersRevoke, Access.PermissionKeys.RegistrarTrailersReopen,
Access.PermissionKeys.RegistrarTrailersReport),
];
public static RegistrarKindInfo Of(RegistrarKind kind) => All[(int)kind];
public static bool TryParse(string? slug, out RegistrarKind kind)
{
var hit = All.FirstOrDefault(k => string.Equals(k.Slug, slug, StringComparison.OrdinalIgnoreCase));
kind = hit?.Kind ?? default;
return hit is not null;
}
}

View File

@ -0,0 +1,197 @@
using System.Text.RegularExpressions;
using FluentValidation;
using FluentValidation.Results;
namespace NTP.Application.Registrar;
/// <summary>User-facing texts, the legacy captions (LT_CAPTION) verbatim.</summary>
public static class RegistrarMessages
{
public const string Done = "";
public const string NoAuthority = "ليس لديك صلاحية لاتمام هذه العملية"; // ERROR.NO_AUTHORITY
public const string OneOfName = "يجب تعبئة الاسم العربي او الانجليزي"; // ERROR.DRIVERINFO_SHOULD_FILL_ONE_OF_NAME
public const string ArabicOnly = "الاسم بالعربية يجب ان يكون باحرف عربية"; // ERROR.DRIVERINFO_ONLY_ARABIC_LETTERS_FOR_NAME_AR
public const string EnglishOnly = "الاسم بالانجليزية يجب ان يكون باحرف انجليزية"; // ERROR.DRIVERINFO_ONLY_ENGLISH_LETTERS_FOR_NAME_EN
public const string IssueAfterExpiry = "تاريخ اصدار الرخصة يجب ان لا يكون اكبر من تاريخ انتهائها"; // ERROR.DRIVERINFO_LICENSE_ISSUE_DATE_NOT_MORE
public const string NumbersOnly = "الحقل لا يقبل أحرف"; // PUBLIC.NUMBERSONLY
public const string Required = "يجب إدخال جميع الحقول"; // PUBLIC.REQUIREDFIELD
public const string FillRevokeReason = "يرجى اختيار سبب الرفض من أعلى النموذج"; // ERROR.*INFO_FILL_REVOKE_REASONE
public const string FillForm = "يرجى تفعيل نمط التعديل وتعبئة النموذج بالمعلومات المطلوبة"; // ERROR.ENABLE_UPDATE_MODE_AND_FILL_FORM
public const string VinUsedForTrailer = "رقم الشاصي مستخدم للمقطورة رقم "; // ERROR.VIN_NUMBER_USED_FOR_TRAILER (the number follows)
public const string VinUsedForTruck = "رقم الشاصي مستخدم للشاحنة رقم "; // ERROR.VIN_NUMBER_USED_FOR_TRUCK
public const string DateRange = "تاريخ الانشاء (من) يجب ان لا يكون اكبر من تاريخ الانشاء (الى)";
public const string TooLong = "القيمة اطول من المسموح";
}
public static class RegistrarErrors
{
public const string NoAuthority = "ERROR.NO_AUTHORITY";
public const string VinUsedForTrailer = "ERROR.VIN_NUMBER_USED_FOR_TRAILER";
public const string VinUsedForTruck = "ERROR.VIN_NUMBER_USED_FOR_TRUCK";
public const string DateRange = "ERROR.CREATEDATEFROM_NOT_GT_CREATEDATETO";
public const string RevokeReason = "ERROR.FILL_REVOKE_REASONE";
}
/// <summary>Pure rules of the DRIVERINFO / TRUCKINFO / TRAILERINFO forms and factories (frontend entities *Form.js, backend *factory.cfc).</summary>
public static class RegistrarRules
{
/// <summary>Jordanian registrations need the complete form; for the others the legacy form skips most fields (the *_excludedVaildFieldsArr lists).</summary>
public const string Jordan = "jo";
private static readonly Regex ArabicLetters = new("^[ء-ي ]*$", RegexOptions.Compiled);
private static readonly Regex EnglishLetters = new("^[a-zA-Z ]+$", RegexOptions.Compiled);
private static readonly Regex Digits = new(@"^\d+$", RegexOptions.Compiled);
public static bool IsJordanian(string? nationality) => string.Equals(nationality?.Trim(), Jordan, StringComparison.OrdinalIgnoreCase);
private static readonly string[] DriverRequired =
["nationality", "nnpn", "dateOfBirth", "bloodGroup", "governate", "address", "licenseNo", "licenseType", "licenseIssueDate", "licenseExpiryDate"];
private static readonly string[] DriverOptionalForeign = ["bloodGroup", "address", "governate", "dateOfBirth", "licenseIssueDate", "licenseExpiryDate"];
private static readonly string[] TruckRequired =
[
"nationality", "plateNo", "ownerName", "governate", "ownerAddress", "manufacturer", "model", "color", "vehicleType", "manufactureYear",
"licenseExpiryDate", "category", "licenseNo", "licenseRegistrationNo", "vinNumber", "engineNumber", "loadingWeight", "grossWeight",
];
private static readonly string[] TruckOptionalForeign =
[
"vehicleType", "category", "loadingWeight", "grossWeight", "ownerAddress", "ownerName", "model", "governate", "manufactureYear",
"licenseExpiryDate", "licenseNo", "licenseRegistrationNo", "vinNumber", "engineNumber",
];
private static readonly string[] TrailerRequired =
[
"nationality", "plateNo", "ownerName", "governate", "ownerAddress", "manufacturer", "model", "color", "manufactureYear",
"licenseExpiryDate", "licenseNo", "licenseRegistrationNo", "vinNumber", "grossWeight",
];
private static readonly string[] TrailerOptionalForeign =
[
"category", "loadingWeight", "grossWeight", "ownerAddress", "ownerName", "governate", "color", "manufactureYear",
"licenseExpiryDate", "licenseNo", "licenseRegistrationNo", "vinNumber",
];
/// <summary>Fields that must be filled for this kind and nationality (the form's <c>required</c> class minus the foreign exclusions).</summary>
public static IReadOnlyList<string> RequiredFields(RegistrarKind kind, string? nationality)
{
var (all, foreign) = kind switch
{
RegistrarKind.Driver => (DriverRequired, DriverOptionalForeign),
RegistrarKind.Truck => (TruckRequired, TruckOptionalForeign),
_ => (TrailerRequired, TrailerOptionalForeign),
};
return IsJordanian(nationality) ? all : all.Where(f => !foreign.Contains(f)).ToArray();
}
/// <summary>Column widths (NAFITHTCS.md); a longer text would fail with ORA-12899.</summary>
public static int? MaxLength(RegistrarKind kind, string field) => field switch
{
"nationality" => 30,
"nnpn" => 20, "licenseNo" => 20, "licenseType" => 20, "mobile" => 15, "bloodGroup" => 10, "governate" => 100,
"nameAr" or "nameEn" => 300,
"address" or "ownerAddress" => 750,
"notes" => 250, // legacy textarea maxlength (the column holds 750)
"plateNo" or "plateCode" => 45,
"licenseRegistrationNo" => 20, "manufacturer" => 20, "color" => 20, "secondaryColor" => 30,
"model" => kind == RegistrarKind.Truck ? 60 : 20,
"vehicleType" => 150,
"category" => kind == RegistrarKind.Truck ? 150 : 20,
"vinNumber" or "engineNumber" => 50,
"ownerName" => 500,
_ => null,
};
private static readonly string[] Lengthy =
[
"nationality", "nnpn", "licenseNo", "licenseType", "mobile", "bloodGroup", "governate", "nameAr", "nameEn", "address", "ownerAddress", "notes",
"plateNo", "plateCode", "licenseRegistrationNo", "manufacturer", "color", "secondaryColor", "model", "vehicleType", "category", "vinNumber",
"engineNumber", "ownerName",
];
/// <summary>The form values of a registration as text by field name (camelCase), the shape the checks work on.</summary>
public static IReadOnlyDictionary<string, string?> Fields(RegistrarUpdateRequest r) => new Dictionary<string, string?>
{
["nationality"] = r.Nationality, ["plateNo"] = r.PlateNo, ["plateCode"] = r.PlateCode, ["nnpn"] = r.Nnpn, ["nameAr"] = r.NameAr, ["nameEn"] = r.NameEn,
["mobile"] = r.Mobile, ["dateOfBirth"] = r.DateOfBirth?.ToString("yyyy-MM-dd"), ["bloodGroup"] = r.BloodGroup, ["governate"] = r.Governate,
["address"] = r.Address, ["licenseNo"] = r.LicenseNo, ["licenseType"] = r.LicenseType,
["licenseIssueDate"] = r.LicenseIssueDate?.ToString("yyyy-MM-dd"), ["licenseExpiryDate"] = r.LicenseExpiryDate?.ToString("yyyy-MM-dd"),
["licenseRegistrationNo"] = r.LicenseRegistrationNo, ["ownerName"] = r.OwnerName, ["ownerAddress"] = r.OwnerAddress, ["manufacturer"] = r.Manufacturer,
["model"] = r.Model, ["color"] = r.Color, ["secondaryColor"] = r.SecondaryColor, ["vehicleType"] = r.VehicleType, ["manufactureYear"] = r.ManufactureYear,
["category"] = r.Category, ["vinNumber"] = r.VinNumber, ["engineNumber"] = r.EngineNumber, ["loadingWeight"] = r.LoadingWeight,
["grossWeight"] = r.GrossWeight, ["notes"] = r.Notes,
};
/// <summary>
/// The stored record as an update request, so one set of checks serves the update (the submitted form) and the complete action (the stored data: the
/// legacy screen validated the form before COMPLETE, which only changes the status).
/// </summary>
public static RegistrarUpdateRequest ToRequest(RegistrarRecord r) => new()
{
Nationality = r.Nationality, PlateNo = r.PlateNo, PlateCode = r.PlateCode, Nnpn = r.Nnpn, NameAr = r.NameAr, NameEn = r.NameEn, Mobile = r.Mobile,
DateOfBirth = r.DateOfBirth, BloodGroup = r.BloodGroup, Governate = r.Governate, Address = r.Address, LicenseNo = r.LicenseNo, LicenseType = r.LicenseType,
LicenseIssueDate = r.LicenseIssueDate, LicenseExpiryDate = r.LicenseExpiryDate, LicenseRegistrationNo = r.LicenseRegistrationNo, OwnerName = r.OwnerName,
OwnerAddress = r.OwnerAddress, Manufacturer = r.Manufacturer, Model = r.Model, Color = r.Color, SecondaryColor = r.SecondaryColor, VehicleType = r.VehicleType,
ManufactureYear = r.ManufactureYear?.ToString(System.Globalization.CultureInfo.InvariantCulture), Category = r.Category, VinNumber = r.VinNumber,
EngineNumber = r.EngineNumber, LoadingWeight = Num(r.LoadingWeight), GrossWeight = Num(r.GrossWeight), Notes = r.Notes,
};
private static string? Num(decimal? v) => v?.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture);
/// <summary>
/// Every problem of the form values. <paramref name="forUpdate"/> adds the lengths and the licence date order (the legacy update button);
/// complete (the legacy COMPLETE button) checks the required fields, the digits and the driver's names.
/// </summary>
public static IReadOnlyList<ValidationFailure> Check(RegistrarKind kind, RegistrarUpdateRequest request, bool forUpdate)
{
var f = Fields(request);
var failures = new List<ValidationFailure>();
string? V(string k) => f.TryGetValue(k, out var s) ? s : null;
bool Blank(string k) => string.IsNullOrWhiteSpace(V(k));
foreach (var field in RequiredFields(kind, request.Nationality))
if (Blank(field)) failures.Add(new ValidationFailure(field, RegistrarMessages.Required));
foreach (var field in new[] { "manufactureYear", "loadingWeight", "grossWeight" })
if (!Blank(field) && !Digits.IsMatch(V(field)!.Trim())) failures.Add(new ValidationFailure(field, RegistrarMessages.NumbersOnly));
if (kind == RegistrarKind.Driver)
{
var ar = V("nameAr")?.Trim() ?? string.Empty;
var en = V("nameEn")?.Trim() ?? string.Empty;
if (ar.Length == 0 && en.Length == 0) failures.Add(new ValidationFailure("nameAr", RegistrarMessages.OneOfName));
else
{
if (ar.Length > 0 && !ArabicLetters.IsMatch(ar)) failures.Add(new ValidationFailure("nameAr", RegistrarMessages.ArabicOnly));
if (en.Length > 0 && !EnglishLetters.IsMatch(en)) failures.Add(new ValidationFailure("nameEn", RegistrarMessages.EnglishOnly));
}
if (forUpdate && request.LicenseIssueDate is { } issue && request.LicenseExpiryDate is { } expiry && issue.Date > expiry.Date)
failures.Add(new ValidationFailure("licenseIssueDate", RegistrarMessages.IssueAfterExpiry));
}
if (forUpdate)
foreach (var field in Lengthy)
if (MaxLength(kind, field) is { } max && V(field) is { } text && text.Trim().Length > max)
failures.Add(new ValidationFailure(field, RegistrarMessages.TooLong));
return failures;
}
/// <summary>The 400 answer: field errors for the form and the joined texts as the message.</summary>
public static void ThrowIfAny(IReadOnlyList<ValidationFailure> failures)
{
if (failures.Count > 0) throw new ValidationException(failures);
}
/// <summary>The record's status after the legacy status change (CHSTAT rows of STATUS_ACTION_MATRIX).</summary>
public static bool CanComplete(string? status) => string.Equals(status, RegistrarStatus.Pending, StringComparison.OrdinalIgnoreCase);
public static bool CanRevoke(string? status) => CanComplete(status);
public static bool CanReopen(string? status) => string.Equals(status, RegistrarStatus.Completed, StringComparison.OrdinalIgnoreCase);
/// <summary>The permission key that lets the caller update a record in this status, or null when no one may (INCOMPLETE and REVOKE records are read only).</summary>
public static string? UpdateKey(RegistrarKindInfo info, string? status) =>
string.Equals(status, RegistrarStatus.Pending, StringComparison.OrdinalIgnoreCase) ? info.Update
: string.Equals(status, RegistrarStatus.Completed, StringComparison.OrdinalIgnoreCase) ? info.UpdateCompleted
: null;
/// <summary>Text with the surrounding blanks removed, empty as null (Oracle stores '' as NULL anyway).</summary>
public static string? Clean(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim();
}

View File

@ -0,0 +1,289 @@
using System.Globalization;
using NTP.Application.Abstractions;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Grains.Orders;
using NTP.Application.Grains.Permits;
using NTP.Application.Grains.Reports;
namespace NTP.Application.Registrar;
/// <summary>
/// Port of the AqabaTCS entities driverinfo / truckinfo / trailerinfo (factory + factoryweb + dao): the registrar reviews what companies register from the
/// mobile app. The screen is a permission key; every action is decided by role AND record status (legacy STATUS_ACTION_MATRIX), here as one permission key
/// per transition (see <see cref="PermissionKeys"/>, db/registrar-permissions.sql). The push to the registering user (legacy MobileNotification REGISTRATION)
/// goes out after an approval or a rejection.
/// </summary>
public sealed class RegistrarService(
IRegistrarRepository repository,
IRegistrarLookupRepository lookups,
IRegistrarSettingsService settings,
IRegistrarFileGatewayService files,
IPermissionService permissions,
IMobileNotificationGatewayService notifications,
IReportExcelService excel,
ICurrentUser user) : IRegistrarService
{
private const int ExportLimit = 50_000;
public async Task<PagedResult<RegistrarRecord>> SearchAsync(RegistrarKind kind, RegistrarQuery query, PageRequest page, CancellationToken ct)
{
if (query.DateFrom is { } from && query.DateTo is { } to && from.Date > to.Date)
throw new BusinessException(RegistrarErrors.DateRange, RegistrarMessages.DateRange);
return await repository.SearchAsync(kind, query, page, ct);
}
public async Task<RegistrarDetail> GetAsync(RegistrarKind kind, long id, CancellationToken ct)
{
var info = RegistrarKinds.Of(kind);
var record = await repository.GetAsync(kind, id, ct) ?? throw new NotFoundException(info.Entity, id);
var attachments = (await lookups.GetAttachmentsAsync(info.Entity, id, ct))
.Where(a => !string.IsNullOrWhiteSpace(a.FileName))
.Select(a => new RegistrarAttachment(a.Id, a.FileName!))
.ToList();
return new RegistrarDetail(record, attachments, await ActionsAsync(info, record.StatusCode, ct));
}
public async Task<RegistrarFile> GetAttachmentAsync(RegistrarKind kind, long id, long attachmentId, CancellationToken ct)
{
var info = RegistrarKinds.Of(kind);
var row = (await lookups.GetAttachmentsAsync(info.Entity, id, ct)).FirstOrDefault(a => a.Id == attachmentId && !string.IsNullOrWhiteSpace(a.FileName))
?? throw new NotFoundException("Attachment", attachmentId);
// {base}/{ENTITY}/{FILENAME} (attachments.cfc getAttachment); the name is escaped, so it cannot leave that folder
var url = $"{settings.Value.AttachmentsBaseUrl.TrimEnd('/')}/{info.Entity}/{Uri.EscapeDataString(row.FileName!)}";
return await files.FetchAsync(url, row.FileName!, ct) ?? throw new NotFoundException("Attachment file", row.FileName!);
}
public async Task<RegistrarResult> UpdateAsync(RegistrarKind kind, long id, RegistrarUpdateRequest request, CancellationToken ct)
{
var info = RegistrarKinds.Of(kind);
var record = await repository.GetAsync(kind, id, ct) ?? throw new NotFoundException(info.Entity, id);
var key = RegistrarRules.UpdateKey(info, record.StatusCode);
if (key is null || !await permissions.IsAllowedAsync(key, ct)) throw NoAuthority();
RegistrarRules.ThrowIfAny(RegistrarRules.Check(kind, request, forUpdate: true));
await EnsureVinFreeAsync(kind, id, request, ct);
if (!await repository.UpdateAsync(kind, id, record.StatusCode!, request, user.UserId, ct)) throw NoAuthority();
return new RegistrarResult(RegistrarMessages.Done);
}
public async Task<RegistrarResult> CompleteAsync(RegistrarKind kind, long id, CancellationToken ct)
{
var info = RegistrarKinds.Of(kind);
var record = await repository.GetAsync(kind, id, ct) ?? throw new NotFoundException(info.Entity, id);
if (!RegistrarRules.CanComplete(record.StatusCode) || !await permissions.IsAllowedAsync(info.Complete, ct)) throw NoAuthority();
// the legacy screen validated the filled form before COMPLETE; here the stored data is what gets approved
var failures = RegistrarRules.Check(kind, RegistrarRules.ToRequest(record), forUpdate: false);
if (failures.Count > 0) throw new FluentValidation.ValidationException(RegistrarMessages.FillForm, failures);
if (!await repository.ChangeStatusAsync(kind, id, RegistrarStatus.Pending, RegistrarStatus.Completed, user.UserId, null, ct)) throw NoAuthority();
Notify("REGISTRATION_APPROVE", info, record, reason: null);
return new RegistrarResult(RegistrarMessages.Done);
}
public async Task<RegistrarResult> RevokeAsync(RegistrarKind kind, long id, string? reason, CancellationToken ct)
{
var info = RegistrarKinds.Of(kind);
var record = await repository.GetAsync(kind, id, ct) ?? throw new NotFoundException(info.Entity, id);
if (!RegistrarRules.CanRevoke(record.StatusCode) || !await permissions.IsAllowedAsync(info.Revoke, ct)) throw NoAuthority();
reason = RegistrarRules.Clean(reason);
var list = (await lookups.GetListsAsync(ct)).GetValueOrDefault(RevokeList(kind)) ?? [];
if (reason is null || list.All(l => !string.Equals(l.Code, reason, StringComparison.Ordinal)))
throw new FluentValidation.ValidationException([new FluentValidation.Results.ValidationFailure("reason", RegistrarMessages.FillRevokeReason)]);
if (!await repository.ChangeStatusAsync(kind, id, RegistrarStatus.Pending, RegistrarStatus.Revoke, user.UserId, reason, ct)) throw NoAuthority();
var text = await lookups.GetCaptionAsync($"{info.Entity}.REVOKEREASON_{reason}", ct) ?? list.First(l => l.Code == reason).Ar;
Notify("REGISTRATION_REVOKE", info, record, text);
return new RegistrarResult(RegistrarMessages.Done);
}
public async Task<RegistrarResult> ReopenAsync(RegistrarKind kind, long id, CancellationToken ct)
{
var info = RegistrarKinds.Of(kind);
var record = await repository.GetAsync(kind, id, ct) ?? throw new NotFoundException(info.Entity, id);
if (!RegistrarRules.CanReopen(record.StatusCode) || !await permissions.IsAllowedAsync(info.Reopen, ct)) throw NoAuthority();
if (!await repository.ChangeStatusAsync(kind, id, RegistrarStatus.Completed, RegistrarStatus.Pending, user.UserId, null, ct)) throw NoAuthority();
return new RegistrarResult(RegistrarMessages.Done);
}
public async Task<RegistrarLookups> GetLookupsAsync(CancellationToken ct) => new(await lookups.GetListsAsync(ct));
public async Task<ExportFile> ExportAsync(RegistrarKind kind, RegistrarQuery query, CancellationToken ct)
{
var info = RegistrarKinds.Of(kind);
if (!await permissions.IsAllowedAsync(info.Report, ct)) throw NoAuthority();
var rows = new List<RegistrarRecord>();
for (var p = 1; rows.Count < ExportLimit; p++)
{
var r = await SearchAsync(kind, query, new PageRequest(p, PageRequest.MaxPageSize), ct);
rows.AddRange(r.Items);
if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break;
}
var all = await lookups.GetListsAsync(ct);
string Name(string list, string? code) =>
string.IsNullOrEmpty(code) ? string.Empty : all.GetValueOrDefault(list)?.FirstOrDefault(i => i.Code == code)?.Ar ?? code;
var cols = RegistrarExport.Columns(kind);
var data = rows.Select((r, i) => RegistrarExport.Row(kind, r, i + 1, Name, StatusName)).ToList();
var table = new ReportTable
{
Key = info.Entity, TitleAr = RegistrarExport.Title(kind), TitleEn = RegistrarExport.TitleEn(kind),
Columns = cols, Rows = data, FilterLines = RegistrarExport.FilterLines(query, StatusName),
};
return new ExportFile(excel.Build(table, user.UserId, DateTime.Now, true),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", info.Entity + ".xlsx");
}
// ------------------------------------------------------------------------------------------------------------------------------------
private async Task<RegistrarActions> ActionsAsync(RegistrarKindInfo info, string? status, CancellationToken ct)
{
var updateKey = RegistrarRules.UpdateKey(info, status);
return new RegistrarActions(
Update: updateKey is not null && await permissions.IsAllowedAsync(updateKey, ct),
Complete: RegistrarRules.CanComplete(status) && await permissions.IsAllowedAsync(info.Complete, ct),
Revoke: RegistrarRules.CanRevoke(status) && await permissions.IsAllowedAsync(info.Revoke, ct),
Reopen: RegistrarRules.CanReopen(status) && await permissions.IsAllowedAsync(info.Reopen, ct));
}
/// <summary>
/// truckinfofactory.cfc:78-104 / trailerinfofactory.cfc:75-100: a Jordanian chassis number (VIN) may be used by one truck or trailer only (revoked
/// ones do not count). A truck is checked against the trailers first, then against the other trucks; a trailer the other way round.
/// </summary>
private async Task EnsureVinFreeAsync(RegistrarKind kind, long id, RegistrarUpdateRequest request, CancellationToken ct)
{
if (kind == RegistrarKind.Driver) return;
var vin = RegistrarRules.Clean(request.VinNumber);
if (vin is null || !RegistrarRules.IsJordanian(request.Nationality)) return;
var order = kind == RegistrarKind.Truck
? new[] { RegistrarKind.Trailer, RegistrarKind.Truck }
: new[] { RegistrarKind.Truck, RegistrarKind.Trailer };
foreach (var other in order)
{
var plate = await repository.FindPlateByVinAsync(other, vin, other == kind ? id : null, ct);
if (plate is null) continue;
throw other == RegistrarKind.Trailer
? new BusinessException(RegistrarErrors.VinUsedForTrailer, RegistrarMessages.VinUsedForTrailer + plate)
: new BusinessException(RegistrarErrors.VinUsedForTruck, RegistrarMessages.VinUsedForTruck + plate);
}
}
/// <summary>Legacy MobileNotification REGISTRATION: tells the user who registered it (CREATED_BY). Runs in the background, never fails the action.</summary>
private void Notify(string template, RegistrarKindInfo info, RegistrarRecord record, string? reason)
{
if (string.IsNullOrWhiteSpace(record.CreatedBy)) return;
var number = info.Kind switch { RegistrarKind.Driver => record.Nnpn, _ => record.PlateNo };
var payload = new Dictionary<string, object?>
{
["LOGIN"] = record.CreatedBy, ["REGISTRATION_TYPE"] = info.NotificationType, ["REGISTRATION_NUMBER_TYPE"] = number ?? string.Empty,
};
if (reason is not null) payload["REASON"] = reason;
_ = notifications.SendAsync(template, payload, CancellationToken.None);
}
private static string RevokeList(RegistrarKind kind) => kind switch
{
RegistrarKind.Driver => "DRIVER_REVOKE_REASON",
RegistrarKind.Truck => "TRUCK_REVOKE_REASON",
_ => "TRAILER_REVOKE_REASON",
};
private static ForbiddenException NoAuthority() => new(RegistrarErrors.NoAuthority, RegistrarMessages.NoAuthority);
internal static string StatusName(string? status) => status?.ToUpperInvariant() switch
{
"PENDING" => "قيد التدقيق",
"COMPLETED" or "COMPLETE" => "مكتمل",
"INCOMPLETE" => "غير مكتمل",
"REVOKE" or "REJECT" => "مرفوض",
_ => status ?? string.Empty,
};
}
/// <summary>Layout of the legacy Excel reports (*infofactoryweb.cfc report): columns, order and captions.</summary>
internal static class RegistrarExport
{
public static string Title(RegistrarKind kind) => kind switch { RegistrarKind.Driver => "رخص السائقين", RegistrarKind.Truck => "رخص الشاحنات", _ => "رخص المقطورات" };
public static string TitleEn(RegistrarKind kind) => kind switch { RegistrarKind.Driver => "Driver licences", RegistrarKind.Truck => "Truck licences", _ => "Trailer licences" };
private static ReportColumn C(string key, string ar, string en) => new(key, ar, en);
public static IReadOnlyList<ReportColumn> Columns(RegistrarKind kind)
{
var common = new List<ReportColumn> { C("counter", "متسلسل", "#") };
switch (kind)
{
case RegistrarKind.Driver:
common.AddRange([
C("nnpn", "الرقم الوطني", "National no."), C("nameAr", "الأسم بالعربي", "Name (Arabic)"), C("nameEn", "الأسم بالأنجليزي", "Name (English)"),
C("nationality", "الجنسية", "Nationality"), C("licenseNo", "رقم الرخصة", "Licence no."), C("licenseIssueDate", "تاريخ اصدار الرخصة", "Licence issued"),
C("licenseExpiryDate", "تاريخ انتهاء الرخصة", "Licence expires"), C("licenseType", "فئة الرخصة", "Licence class"), C("status", "الحالة", "Status"),
C("revokeReason", "سبب الرفض", "Rejection reason"), C("createdBy", "انشاء بواسطة", "Created by"), C("creationDate", "تاريخ الانشاء", "Created"),
C("updatedBy", "حُدث بواسطة", "Updated by"), C("lastUpdateDate", "حدُث بتاريخ", "Updated"), C("bloodGroup", "فصيلة الدم", "Blood group"),
C("governate", "المحافظة", "Governorate"), C("notes", "ملاحظات", "Notes"),
]);
break;
case RegistrarKind.Truck:
common.AddRange([
C("plateNo", "رقم الشاحنة", "Truck"), C("licenseNo", "رقم الرخصة", "Licence no."), C("licenseRegistrationNo", "رقم التسجيل", "Registration no."),
C("licenseExpiryDate", "تاريخ انتهاء الرخصة", "Licence expires"), C("manufactureYear", "سنه الصنع", "Year"), C("vehicleType", "فئه المركبة", "Type"),
C("ownerName", "اسم المالك", "Owner"), C("status", "الحالة", "Status"), C("revokeReason", "سبب الرفض", "Rejection reason"),
C("createdBy", "انشاء بواسطة", "Created by"), C("creationDate", "تاريخ الانشاء", "Created"), C("updatedBy", "حُدث بواسطة", "Updated by"),
C("lastUpdateDate", "حدُث بتاريخ", "Updated"), C("nationality", "الجنسية", "Nationality"), C("color", "اللون", "Colour"),
C("secondaryColor", "اللون الفرعي", "Secondary colour"), C("grossWeight", "الوزن القائم", "Gross weight"), C("emptyWeight", "الوزن الفارغ", "Empty weight"),
C("category", "صفة الأستعمال", "Use"), C("manufacturer", "نوع المركبة", "Make"), C("notes", "ملاحظات", "Notes"),
]);
break;
default:
common.AddRange([
C("plateNo", "رقم المقطورة", "Trailer"), C("licenseNo", "رقم الرخصة", "Licence no."), C("licenseRegistrationNo", "رقم التسجيل", "Registration no."),
C("licenseExpiryDate", "تاريخ انتهاء الرخصة", "Licence expires"), C("manufacturer", "نوع المركبة", "Make"), C("manufactureYear", "سنه الصنع", "Year"),
C("vehicleType", "فئه المركبة", "Type"), C("ownerName", "اسم المالك", "Owner"), C("status", "الحالة", "Status"),
C("revokeReason", "سبب الرفض", "Rejection reason"), C("createdBy", "انشاء بواسطة", "Created by"), C("creationDate", "تاريخ الانشاء", "Created"),
C("updatedBy", "حُدث بواسطة", "Updated by"), C("lastUpdateDate", "حدُث بتاريخ", "Updated"), C("color", "اللون", "Colour"),
C("nationality", "الجنسية", "Nationality"), C("category", "صفة الاستعمال", "Use"), C("grossWeight", "الوزن القائم", "Gross weight"),
C("governate", "المحافظة", "Governorate"), C("notes", "ملاحظات", "Notes"),
]);
break;
}
return common;
}
private static string D(DateTime? d, bool time = false) => d is null ? string.Empty : d.Value.ToString(time ? "dd/MM/yyyy HH:mm:ss" : "dd/MM/yyyy", CultureInfo.InvariantCulture);
public static IReadOnlyDictionary<string, object?> Row(RegistrarKind kind, RegistrarRecord r, int counter, Func<string, string?, string> name, Func<string?, string> status)
{
var reasonList = kind switch { RegistrarKind.Driver => "DRIVER_REVOKE_REASON", RegistrarKind.Truck => "TRUCK_REVOKE_REASON", _ => "TRAILER_REVOKE_REASON" };
var typeList = kind == RegistrarKind.Truck ? "TRUCK_TYPE" : "TRAILER_TYPE";
var useList = kind == RegistrarKind.Truck ? "TRUCK_USAGE_TYPE" : "TRAILER_USAGE_TYPE";
return new Dictionary<string, object?>
{
["counter"] = counter, ["nnpn"] = r.Nnpn, ["nameAr"] = r.NameAr, ["nameEn"] = r.NameEn, ["plateNo"] = r.PlateNo,
["nationality"] = name("NATIONALITY", r.Nationality), ["licenseNo"] = r.LicenseNo, ["licenseRegistrationNo"] = r.LicenseRegistrationNo,
["licenseIssueDate"] = D(r.LicenseIssueDate), ["licenseExpiryDate"] = D(r.LicenseExpiryDate),
["licenseType"] = name("DRIVER_LICENSE_TYPE", r.LicenseType), ["status"] = status(r.StatusCode), ["revokeReason"] = name(reasonList, r.RevokeReason),
["createdBy"] = r.CreatedBy, ["creationDate"] = D(r.CreationDate, true), ["updatedBy"] = r.UpdatedBy, ["lastUpdateDate"] = D(r.LastUpdateDate, true),
["bloodGroup"] = name("BLOOD_GROUP", r.BloodGroup), ["governate"] = name("JORDAN_GOVERNATE", r.Governate), ["notes"] = r.Notes,
["manufactureYear"] = r.ManufactureYear, ["vehicleType"] = name(typeList, r.VehicleType), ["ownerName"] = r.OwnerName,
["color"] = name("COLOR", r.Color), ["secondaryColor"] = name("COLOR", r.SecondaryColor), ["grossWeight"] = r.GrossWeight, ["emptyWeight"] = r.EmptyWeight,
["category"] = name(useList, r.Category), ["manufacturer"] = name("VEHICLE_MANIFACTURER", r.Manufacturer),
};
}
public static IReadOnlyList<string> FilterLines(RegistrarQuery q, Func<string?, string> status)
{
var lines = new List<string>();
void Add(string label, string? v) { if (!string.IsNullOrWhiteSpace(v)) lines.Add($"{label}: {v}"); }
Add("الرقم", q.Number); Add("رقم الرخصة", q.LicenseNo); Add("الاسم", q.Name); Add("اسم المالك", q.OwnerName); Add("رقم الشاصي", q.VinNumber);
Add("من تاريخ الانشاء", q.DateFrom is { } f ? D(f) : null); Add("الى تاريخ الانشاء", q.DateTo is { } t ? D(t) : null);
if (q.StatusCodes.Count > 0) Add("الحالة", string.Join("، ", q.StatusCodes.Select(status)));
return lines;
}
}

View File

@ -63,7 +63,11 @@ public static class DependencyInjection
services.AddOptions<NTP.Infrastructure.Integrations.JopetrolOptions>() services.AddOptions<NTP.Infrastructure.Integrations.JopetrolOptions>()
.Bind(configuration.GetSection(NTP.Infrastructure.Integrations.JopetrolOptions.SectionName)); .Bind(configuration.GetSection(NTP.Infrastructure.Integrations.JopetrolOptions.SectionName));
services.AddHttpClient(NTP.Infrastructure.Integrations.JopetrolOptions.HttpClientName); services.AddHttpClient(NTP.Infrastructure.Integrations.JopetrolOptions.HttpClientName);
services.AddScoped<NTP.Application.Refinery.Integrations.IJopetrolGateway, NTP.Infrastructure.Integrations.JopetrolGateway>(); services.AddScoped<NTP.Infrastructure.Integrations.JopetrolGateway>();
services.AddScoped<NTP.Application.Refinery.Integrations.IJopetrolGateway>(sp => sp.GetRequiredService<NTP.Infrastructure.Integrations.JopetrolGateway>());
services.AddScoped<NTP.Application.Refinery.Sync.IJopetrolTripsGateway>(sp => sp.GetRequiredService<NTP.Infrastructure.Integrations.JopetrolGateway>());
// Mail (legacy cfmail): off unless Mail:Enabled; Mail:UserName / Password come from the environment
services.AddOptions<NTP.Infrastructure.Mail.MailOptions>().Bind(configuration.GetSection(NTP.Infrastructure.Mail.MailOptions.SectionName));
// Convention: every concrete *Repository / *Service in this assembly is registered against I{Name} (scoped). // Convention: every concrete *Repository / *Service in this assembly is registered against I{Name} (scoped).
// Do NOT add per-table lines here. // Do NOT add per-table lines here.

View File

@ -20,7 +20,7 @@ internal sealed class MobileNotificationGatewayService(IGrainsPermitsSettingsSer
public Task SendAsync(string template, IReadOnlyDictionary<string, object?> payload, CancellationToken ct = default) public Task SendAsync(string template, IReadOnlyDictionary<string, object?> payload, CancellationToken ct = default)
{ {
var o = settings.Value.Notifications; var o = settings.Value.Notifications;
if (!o.Enabled || string.IsNullOrWhiteSpace(o.PushUrl)) return Task.CompletedTask; if (!o.Enabled) return Task.CompletedTask;
_ = Task.Run(async () => _ = Task.Run(async () =>
{ {
@ -39,66 +39,59 @@ internal sealed class MobileNotificationGatewayService(IGrainsPermitsSettingsSer
} }
/// <summary> /// <summary>
/// Calls <c>SendFromCF9</c> of the legacy push web service with the arguments the legacy NTP application sent /// Push through the OneSignal REST API (legacy MobileNotification.cfc SendNotificationToOneSignal, which the old SendFromCF9 web service called).
/// (CF9Param = JSON of ReceiverType, FCMToken, Message, Title, UserId, OS, MSG_TEMPLATE_ID, LetterId, phoneNumber, tn). /// The request body is built by <see cref="NotificationRules.OneSignalBody"/>; a MOBILENOTIFICATIONSLOG row (SUCCESS / FAILURE) is written for
/// The service pushes to OneSignal and writes MOBILENOTIFICATIONSLOG, so V2 does not hold the push provider key. /// every push, like legacy LoggingNotification. The REST API key goes in the Authorization header only and is never logged.
/// </summary> /// </summary>
internal sealed partial class PushGatewayService(IGrainsPermitsSettingsService settings, ILogger<PushGatewayService> logger) : IPushGatewayService internal sealed class PushGatewayService(IGrainsPermitsSettingsService settings, INotificationRepository repository, ILogger<PushGatewayService> logger) : IPushGatewayService
{ {
private static readonly HttpClient Http = new(); private static readonly HttpClient Http = new();
private static string? _namespace; // targetNamespace of the service, read once from its WSDL private static bool _warnedNotConfigured;
public async Task<bool> SendAsync(PushMessage m, CancellationToken ct = default) public async Task<bool> SendAsync(PushMessage m, CancellationToken ct = default)
{ {
var o = settings.Value.Notifications; var o = settings.Value.Notifications;
if (!o.Enabled || string.IsNullOrWhiteSpace(o.PushUrl)) return false; if (!o.Enabled) return false;
if (!o.OneSignal.IsConfigured)
{
if (!_warnedNotConfigured)
{
_warnedNotConfigured = true;
logger.LogWarning("Push is enabled but Grains:Permits:Notifications:OneSignal:AppId / ApiKey are not set");
}
return false;
}
var body = NotificationRules.OneSignalBody(o.OneSignal, m.Token, m.Title, m.Message, m.Os, m.TemplateId);
string? answer = null;
var ok = false;
try try
{ {
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds))); cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds)));
var endpoint = o.PushUrl.EndsWith("?wsdl", StringComparison.OrdinalIgnoreCase) ? o.PushUrl[..^"?wsdl".Length] : o.PushUrl; using var req = new HttpRequestMessage(HttpMethod.Post, o.OneSignal.Url) { Content = new StringContent(body, Encoding.UTF8, "application/json") };
var ns = await NamespaceAsync(o.PushUrl, cts.Token); req.Headers.TryAddWithoutValidation("Authorization", "key=" + o.OneSignal.ApiKey);
var param = JsonSerializer.Serialize(new Dictionary<string, string>
{
["ReceiverType"] = "DEVICEID", ["FCMToken"] = m.Token, ["Message"] = m.Message, ["Title"] = m.Title,
["UserId"] = m.UserId.ToString(System.Globalization.CultureInfo.InvariantCulture), ["OS"] = m.Os,
["MSG_TEMPLATE_ID"] = m.TemplateId.ToString(System.Globalization.CultureInfo.InvariantCulture),
["LetterId"] = "0", ["phoneNumber"] = m.Phone, ["tn"] = m.Tn
});
var envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body>"
+ $"<ns:SendFromCF9 xmlns:ns=\"{SecurityElement.Escape(ns)}\" soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
+ $"<CF9Param xsi:type=\"xsd:string\">{SecurityElement.Escape(param)}</CF9Param></ns:SendFromCF9></soapenv:Body></soapenv:Envelope>";
using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new StringContent(envelope, Encoding.UTF8, "text/xml") };
req.Headers.TryAddWithoutValidation("SOAPAction", "\"\"");
using var res = await Http.SendAsync(req, cts.Token); using var res = await Http.SendAsync(req, cts.Token);
if (!res.IsSuccessStatusCode) answer = await res.Content.ReadAsStringAsync(cts.Token);
{ ok = res.IsSuccessStatusCode && NotificationRules.OneSignalSucceeded(answer);
logger.LogWarning("Push service answered {Status} for user {UserId}", (int)res.StatusCode, m.UserId); if (!ok) logger.LogWarning("OneSignal answered {Status} for user {UserId}: {Answer}", (int)res.StatusCode, m.UserId, Cut(answer, 300));
return false;
}
return true;
} }
catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout catch (Exception ex) when (!ct.IsCancellationRequested) // includes our own timeout
{ {
logger.LogWarning(ex, "Push service unreachable (user {UserId})", m.UserId); answer = ex.GetType().Name;
return false; logger.LogWarning("OneSignal unreachable (user {UserId}): {Reason}", m.UserId, ex.GetType().Name);
} }
try
{
await repository.InsertPushLogAsync(m.UserId.ToString(System.Globalization.CultureInfo.InvariantCulture), m.Token, ok ? "SUCCESS" : "FAILURE",
body, answer, m.Os, m.TemplateId, ct);
}
catch (Exception ex) when (!ct.IsCancellationRequested) { logger.LogWarning(ex, "Push log row could not be written"); }
return ok;
} }
private static async Task<string> NamespaceAsync(string wsdlUrl, CancellationToken ct) private static string? Cut(string? s, int max) => s is { Length: var n } && n > max ? s[..max] : s;
{
if (_namespace is { } known) return known;
var wsdl = await Http.GetStringAsync(wsdlUrl, ct);
var match = TargetNamespace().Match(wsdl);
if (!match.Success) throw new InvalidOperationException("The push service WSDL has no targetNamespace");
return _namespace = match.Groups[1].Value;
}
[GeneratedRegex("targetNamespace\\s*=\\s*\"([^\"]+)\"")]
private static partial Regex TargetNamespace();
} }
/// <summary> /// <summary>
@ -223,6 +216,28 @@ public sealed class NotificationDispatcher(
} }
break; break;
case NotificationRules.BlockedDistributedOwners:
// the driver and truck owner accounts of each truck get the fixed text (no variables)
foreach (var e in NotificationRules.Entries(payload))
{
var tn = NotificationRules.Get(e, "TN");
var phone = (await repository.GetTruckContactAsync(tn, ct))?.Phone ?? string.Empty;
await ToPhoneUsersAsync(info, phone, tn, smsFallback: false, [], ct);
}
break;
case NotificationRules.RegistrationApprove:
case NotificationRules.RegistrationRevoke:
// MobileNotification.cfc REGISTRATION: the user who registered it (CREATED_BY) gets VAR1 = type, VAR2 = number, VAR3 = reason; the title has VAR1 = type
var registrar = NotificationRules.Get(payload, "LOGIN");
if (registrar.Length == 0) break;
var regType = NotificationRules.Get(payload, "REGISTRATION_TYPE");
var regText = NotificationRules.Fill(info.Message ?? string.Empty, regType, NotificationRules.Get(payload, "REGISTRATION_NUMBER_TYPE"), NotificationRules.Get(payload, "REASON"));
var regInfo = new NotificationTemplateRow { Id = info.Id, Title = NotificationRules.Fill(info.Title ?? string.Empty, regType), Message = info.Message };
foreach (var user in await repository.FindUserIdsAsync(roleCode: null, mobile: null, login: registrar, loginContains: null, ct))
await PushToUserAsync(regInfo, user, tn: "0", phone: "0", regText, ct);
break;
default: default:
logger.LogWarning("Notification template {Template} has no flow in V2", template); logger.LogWarning("Notification template {Template} has no flow in V2", template);
break; break;

View File

@ -43,6 +43,47 @@ public static class JopetrolSoap
"""; """;
} }
private static string Soap11(string userName, string password, string body)
{
static string E(string s) => SecurityElement.Escape(s) ?? "";
return $"""
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tran="{ServiceNamespace}">
<soapenv:Header><tran:AuthHeader><tran:UserName>{E(userName)}</tran:UserName><tran:Password>{E(password)}</tran:Password></tran:AuthHeader></soapenv:Header>
<soapenv:Body>{body}</soapenv:Body>
</soapenv:Envelope>
""";
}
/// <summary>The SOAP 1.1 envelope of legacy REFINERY_OIL.cfm callRefinaryQueryOnTransByStatus.</summary>
public static string BuildQueryByStatus(string userName, string password, int status) =>
Soap11(userName, password, $"<tran:QueryOnTransByStatus><tran:StatusNo>{status}</tran:StatusNo></tran:QueryOnTransByStatus>");
/// <summary>Envelope of callRefinaryUpdateStatusTo1 (the operation element is in the default namespace of the service, as legacy sent it).</summary>
public static string BuildUpdateStatusTo1(string userName, string password, string pn) =>
Soap11(userName, password, $"<UpdateStatusTo1 xmlns=\"{ServiceNamespace}\"><TransNumber>{SecurityElement.Escape(pn)}</TransNumber></UpdateStatusTo1>");
public static string BuildUpdateStatusToMinus2(string userName, string password, string pn) =>
Soap11(userName, password, $"<tran:UpdateStatusToMinus2><tran:TransNumber>{SecurityElement.Escape(pn)}</tran:TransNumber></tran:UpdateStatusToMinus2>");
/// <summary>The children of the answer's NewDataSet element (one per trip); empty when there is none.</summary>
public static IReadOnlyList<XElement> ParseDataSetRows(string xml)
{
var doc = XDocument.Parse(xml);
var set = doc.Descendants().FirstOrDefault(e => e.Name.LocalName == "NewDataSet");
return set is null ? [] : set.Elements().ToList();
}
/// <summary>
/// Text of the first element whose name ends in "Result" and starts with <paramref name="operation"/>. Legacy searched UpdateStatusTo1Result for both
/// status calls; matching on the operation name (or any *Result as a fallback) keeps working when the service names the answer after its operation.
/// </summary>
public static string? ParseOperationResult(string xml, string operation)
{
var doc = XDocument.Parse(xml);
var results = doc.Descendants().Where(e => e.Name.LocalName.EndsWith("Result", StringComparison.Ordinal)).ToList();
return (results.FirstOrDefault(e => e.Name.LocalName == operation + "Result") ?? results.FirstOrDefault())?.Value;
}
/// <summary>Text of <c>sendClaimandUpdateStatusTo7Result</c> (legacy xmlSearch "//*[local-name()=...]"); null when the answer does not contain it.</summary> /// <summary>Text of <c>sendClaimandUpdateStatusTo7Result</c> (legacy xmlSearch "//*[local-name()=...]"); null when the answer does not contain it.</summary>
public static string? ParseResult(string xml) public static string? ParseResult(string xml)
{ {
@ -55,8 +96,52 @@ public static class JopetrolSoap
/// Jopetrol claim web service (legacy refinery_wage_claimfactory.callRefinaryUpdateStatusTo7). Returns null WITHOUT any call when /// Jopetrol claim web service (legacy refinery_wage_claimfactory.callRefinaryUpdateStatusTo7). Returns null WITHOUT any call when
/// <c>Refinery:Jopetrol:Enabled</c> is false. HTTP errors, time-outs and unreadable answers are thrown (the caller decides what to tell the user). /// <c>Refinery:Jopetrol:Enabled</c> is false. HTTP errors, time-outs and unreadable answers are thrown (the caller decides what to tell the user).
/// </summary> /// </summary>
public sealed class JopetrolGateway(IHttpClientFactory httpClients, IOptions<JopetrolOptions> options, ILogger<JopetrolGateway> logger) : IJopetrolGateway public sealed class JopetrolGateway(IHttpClientFactory httpClients, IOptions<JopetrolOptions> options, ILogger<JopetrolGateway> logger) : IJopetrolGateway, NTP.Application.Refinery.Sync.IJopetrolTripsGateway
{ {
public bool IsReady
{
get
{
var o = options.Value;
return o.Enabled && !string.IsNullOrWhiteSpace(o.Url) && !string.IsNullOrWhiteSpace(o.UserName) && !string.IsNullOrWhiteSpace(o.Password);
}
}
private async Task<string> PostAsync(string envelope, CancellationToken ct)
{
var o = options.Value;
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(o.TimeoutSeconds is > 0 and <= 600 ? o.TimeoutSeconds : 60));
// like legacy: text/xml and no SOAPAction header
using var request = new HttpRequestMessage(HttpMethod.Post, o.Url) { Content = new StringContent(envelope, Encoding.UTF8, "text/xml") };
using var response = await httpClients.CreateClient(JopetrolOptions.HttpClientName).SendAsync(request, cts.Token);
return await response.Content.ReadAsStringAsync(cts.Token);
}
public async Task<IReadOnlyList<XElement>> QueryOnTransByStatusAsync(int status, CancellationToken ct = default)
{
var o = options.Value;
var body = await PostAsync(JopetrolSoap.BuildQueryByStatus(o.UserName, o.Password, status), ct);
try { return JopetrolSoap.ParseDataSetRows(body); }
catch (XmlException) { throw new InvalidOperationException("Jopetrol answered with an unreadable body to QueryOnTransByStatus"); }
}
public async Task<string?> UpdateStatusTo1Async(string pn, CancellationToken ct = default)
{
var o = options.Value;
var body = await PostAsync(JopetrolSoap.BuildUpdateStatusTo1(o.UserName, o.Password, pn), ct);
try { return JopetrolSoap.ParseOperationResult(body, "UpdateStatusTo1"); }
catch (XmlException) { throw new InvalidOperationException("Jopetrol answered with an unreadable body to UpdateStatusTo1"); }
}
public async Task<string?> UpdateStatusToMinus2Async(string pn, CancellationToken ct = default)
{
var o = options.Value;
var body = await PostAsync(JopetrolSoap.BuildUpdateStatusToMinus2(o.UserName, o.Password, pn), ct);
try { return JopetrolSoap.ParseOperationResult(body, "UpdateStatusToMinus2"); }
catch (XmlException) { throw new InvalidOperationException("Jopetrol answered with an unreadable body to UpdateStatusToMinus2"); }
}
public async Task<string?> SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default) public async Task<string?> SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default)
{ {
var o = options.Value; var o = options.Value;

View File

@ -0,0 +1,56 @@
using System.Net;
using System.Net.Mail;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NTP.Application.Abstractions;
namespace NTP.Infrastructure.Mail;
/// <summary>
/// Section <c>Mail</c>. OFF by default. <see cref="UserName"/> and <see cref="Password"/> are secrets: environment variables
/// (<c>Mail__UserName</c>, <c>Mail__Password</c>), never a file of the repository.
/// </summary>
public sealed class MailOptions
{
public const string SectionName = "Mail";
public bool Enabled { get; set; }
public string Host { get; set; } = string.Empty;
public int Port { get; set; } = 587;
/// <summary>STARTTLS / SSL on the connection.</summary>
public bool UseSsl { get; set; } = true;
public string UserName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
/// <summary>Sender address (legacy cfmail from="notifications@nafith.com").</summary>
public string From { get; set; } = "notifications@nafith.com";
public int TimeoutSeconds { get; set; } = 30;
}
/// <summary>SMTP sender (System.Net.Mail). The password is never logged.</summary>
public sealed class MailService(IOptions<MailOptions> options, ILogger<MailService> logger) : IMailService
{
public async Task<bool> SendHtmlAsync(IReadOnlyList<string> to, string subject, string htmlBody, CancellationToken ct = default)
{
var o = options.Value;
var recipients = to.Where(a => !string.IsNullOrWhiteSpace(a)).Select(a => a.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
if (!o.Enabled) { logger.LogInformation("Mail is off (Mail:Enabled): \"{Subject}\" not sent", subject); return false; }
if (string.IsNullOrWhiteSpace(o.Host)) { logger.LogWarning("Mail is enabled but Mail:Host is not set"); return false; }
if (recipients.Count == 0) { logger.LogWarning("No recipient for the mail \"{Subject}\"", subject); return false; }
try
{
using var message = new MailMessage { From = new MailAddress(o.From), Subject = subject, Body = htmlBody, IsBodyHtml = true,
BodyEncoding = System.Text.Encoding.UTF8, SubjectEncoding = System.Text.Encoding.UTF8 };
foreach (var a in recipients) message.To.Add(a);
using var client = new SmtpClient(o.Host, o.Port) { EnableSsl = o.UseSsl, Timeout = Math.Max(5, o.TimeoutSeconds) * 1000 };
if (!string.IsNullOrWhiteSpace(o.UserName)) client.Credentials = new NetworkCredential(o.UserName, o.Password);
await client.SendMailAsync(message, ct);
return true;
}
catch (Exception ex) when (!ct.IsCancellationRequested)
{
logger.LogWarning("Mail \"{Subject}\" could not be sent: {Reason}", subject, ex.GetType().Name + ": " + ex.Message);
return false;
}
}
}

View File

@ -0,0 +1,105 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NTP.Application.ExternalIntegration;
namespace NTP.Infrastructure.Persistence.Repositories.ExternalIntegration;
/// <summary>SQL of jobs/ExternalIntegrationJoSilos.cfm and ExternalIntegrationActiveMQ.ADD_INTEGRATION_LOG / the status updates (NAFITHTCS connection).</summary>
internal sealed class JoSilosRepository(IDbSession session, ILogger<JoSilosRepository> logger)
: OracleRepositoryBase(session, logger), IJoSilosRepository
{
public async Task<IReadOnlyList<JoSilosPermitRow>> GetPermitsForSilosAsync(int max, CancellationToken ct = default) =>
await QueryAsync<JoSilosPermitRow>("""
SELECT * FROM (
SELECT p.ID AS Id, p.PN AS RequestNo, TO_CHAR(p.CREATIONDATE, 'yyyy-mm-dd') AS RequestDate,
getlocationname(p.DESTINATIONADDRESSID, 'GN') AS ToLocation, p.SHIPMENTMODE AS ItemCode,
getcargotypename(p.SHIPMENTMODE, 'GN') AS ItemName, p.TN AS FirstPlateNo, p.TRN AS SecondPlateNo,
p.DRVR AS DriverName, p.NNPN AS DriverNatId, TO_CHAR(NVL(p.DLN, 0)) AS DriverLicenseNo,
TO_CHAR(NVL(truck.PHONENUMBER, 0)) AS DriverMobileNo,
DECODE(truck.HEADTYPE, 'Tripper', :Tipper, :Trailer) AS TrailerType,
TO_CHAR(p.COMPANYCODE) AS CarrierId, getcompanynamefromscac(p.COMPANYCODE, 62) AS CarrierName,
TO_CHAR(SYSDATE, 'yyyy-mm-dd HH24:mi:ss') AS TimeStamp
FROM PERMITS p, NTP_TRUCKS truck
WHERE p.DOMAIN = 'GN'
AND truck.TN (+) = p.TN AND truck.STATUSCODE IN ('OPEN', 'ACCPT')
AND p.DESTINATIONADDRESSID IS NOT NULL
AND p.SHIPMENTSTATUSCODE = 'RESD'
AND NOT EXISTS (SELECT 1 FROM EXTERNAL_INTEGRATION_QUEUE_LOG EXT WHERE EXT.PERMIT_ID = p.ID AND EXT.TYPE = 'JOSILOS')
ORDER BY p.PN
) WHERE ROWNUM <= :Max
""", new { Tipper = "قلاب", Trailer = "تريلا", Max = max }, ct);
public async Task<IReadOnlyList<AqabaSilosPermitRow>> GetPermitsForAqabaSilosAsync(int max, CancellationToken ct = default) =>
await QueryAsync<AqabaSilosPermitRow>("""
SELECT * FROM (
SELECT p.ID AS PermitId, p.TRACKINGNO AS Pn, p.PN AS ReferenceNo, TO_CHAR(p.CREATIONDATE, 'yyyy-mm-dd') AS CreationDate,
p.TN AS Tn, p.TRN AS Trn, getlocationname(p.DESTINATIONADDRESSID, 'GN') AS Location, p.SHIPMENTMODE AS Item,
p.SHIPMENTMODE AS ItemCode, getcargotypename(p.SHIPMENTMODE, 'GN') AS ItemName,
TO_CHAR(p.CREATIONDATE, 'yyyy-mm-dd') AS ExpArrivalDate, p.DRVR AS Driver, p.NNPN AS DriverNnpn,
TO_CHAR(NVL(p.DLN, 0)) AS LicenseNo, p.DESTINATIONADDRESSID AS LocationId
FROM PERMITS p, NTP_TRUCKS truck
WHERE p.DOMAIN = 'GN'
AND truck.TN (+) = p.TN AND truck.STATUSCODE IN ('OPEN', 'ACCPT')
AND p.DESTINATIONADDRESSID IS NOT NULL
AND p.SHIPMENTSTATUSCODE = 'RESD'
AND NOT EXISTS (SELECT 1 FROM EXTERNAL_INTEGRATION_QUEUE_LOG EXT WHERE EXT.PERMIT_ID = p.ID AND EXT.TYPE = 'AQABASILOS' AND EXT.STATUS_CODE = 'PROCESSED')
ORDER BY p.PN
) WHERE ROWNUM <= :Max
""", new { Max = max }, ct);
public async Task<long> AddQueueLogAsync(string type, string operationType, long permitId, string permitStatusCode, int currentLeg, long eventId, string queueData,
CancellationToken ct = default)
{
await ExecuteAsync("""
DELETE FROM EXTERNAL_INTEGRATION_QUEUE_LOG
WHERE PERMIT_ID = :PermitId AND TYPE = :Type AND STATUS_CODE = 'PENDING' AND PERMIT_STATUS_CODE = :PermitStatus
AND PERMIT_CURRENT_LEG_ID = :Leg AND EVENT_ID = :EventId
""", new { PermitId = permitId, Type = type, PermitStatus = permitStatusCode, Leg = currentLeg, EventId = eventId }, ct);
var id = await ExecuteScalarAsync<long>("SELECT SEQ_EXT_INTEGRATION_QUEUE_LOG.NEXTVAL FROM DUAL", null, ct);
await ExecuteAsync("""
INSERT INTO EXTERNAL_INTEGRATION_QUEUE_LOG (ID, CREATION_DATE, TYPE, OPERATION_TYPE, STATUS_CODE, PERMIT_ID, PERMIT_STATUS_CODE, PERMIT_CURRENT_LEG_ID, QUEUE_DATA, EVENT_ID, RESULT_MSG)
VALUES (:Id, SYSDATE, :Type, :Operation, 'PENDING', :PermitId, :PermitStatus, :Leg, :QueueData, :EventId, 'PENDING')
""", new
{
Id = id, Type = type, Operation = operationType, PermitId = permitId, PermitStatus = permitStatusCode, Leg = currentLeg,
QueueData = Cut(queueData, 3900), EventId = eventId,
}, ct);
return id;
}
public Task MarkProcessedAsync(long logId, string result, CancellationToken ct = default) =>
ExecuteAsync("UPDATE EXTERNAL_INTEGRATION_QUEUE_LOG SET STATUS_CODE = 'PROCESSED', CREATION_DATE = SYSDATE, RESULT_MSG = :Result WHERE ID = :Id",
new { Result = Cut(result, 3900), Id = logId }, ct);
public Task SetResultAsync(long logId, string result, CancellationToken ct = default) =>
ExecuteAsync("UPDATE EXTERNAL_INTEGRATION_QUEUE_LOG SET RESULT_MSG = :Result WHERE ID = :Id", new { Result = Cut(result, 3900), Id = logId }, ct);
private static string Cut(string s, int max) => s.Length <= max ? s : s[..max];
}
/// <summary>Binds configuration section "ExternalIntegration:JoSilos".</summary>
internal sealed class JoSilosSettingsService : IJoSilosSettingsService
{
public JoSilosSettingsService(IConfiguration configuration)
{
Value = new JoSilosOptions();
configuration.GetSection(JoSilosOptions.SectionName).Bind(Value);
}
public JoSilosOptions Value { get; }
}
/// <summary>HTTP POST of the JSON bodies (legacy cfhttp).</summary>
internal sealed class JoSilosGatewayService(IJoSilosSettingsService settings) : IJoSilosGatewayService
{
private static readonly HttpClient Http = new();
public async Task<string> PostJsonAsync(string url, string json, CancellationToken ct = default)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(5, settings.Value.TimeoutSeconds)));
using var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
using var res = await Http.PostAsync(url, content, cts.Token);
return (await res.Content.ReadAsStringAsync(cts.Token)).Trim();
}
}

View File

@ -0,0 +1,87 @@
using System.Text;
using Dapper;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NTP.Application.Common;
using NTP.Application.Grains.Communication;
namespace NTP.Infrastructure.Persistence.Repositories.Grains.Communication;
/// <summary>TRUCK_DISTRIBUTION_LOG and its view (primary schema) of gn_communicationdao.cfc.</summary>
internal sealed class CommunicationRepository(IDbSession session, ILogger<CommunicationRepository> logger)
: OracleRepositoryBase(session, logger), ICommunicationRepository
{
private sealed class UnansweredRow { public long PermitId { get; set; } public string? Tn { get; set; } }
public async Task<PagedResult<CommunicationRow>> SearchAsync(CommunicationQuery q, PageRequest page, CancellationToken ct = default)
{
var where = new StringBuilder();
var p = new DynamicParameters();
if (!string.IsNullOrWhiteSpace(q.Tn)) { where.Append(" AND LOWER(p.TN) = LOWER(:Tn)"); p.Add("Tn", q.Tn.Trim()); }
if (long.TryParse(q.Pn?.Trim(), out var pn)) { where.Append(" AND p.PN = :Pn"); p.Add("Pn", pn); }
else if (!string.IsNullOrWhiteSpace(q.Pn)) where.Append(" AND 1 = 0");
if (long.TryParse(q.CargoTypeCode?.Trim(), out var cargo)) { where.Append(" AND p.CARGOTYPECODE = :Cargo"); p.Add("Cargo", cargo); }
if (!string.IsNullOrWhiteSpace(q.Shift)) { where.Append(" AND p.SHIFT = :Shift"); p.Add("Shift", q.Shift.Trim()); }
if (int.TryParse(q.IsBlocked, out var blocked)) { where.Append(" AND p.ISBLOCKED = :Blocked"); p.Add("Blocked", blocked); }
if (q.DateFrom is { } from) { where.Append(" AND TO_DATE(p.ORDERDATE, 'dd/mm/yyyy') >= :DateFrom"); p.Add("DateFrom", from.Date); }
if (q.DateTo is { } to) { where.Append(" AND TO_DATE(p.ORDERDATE, 'dd/mm/yyyy') <= :DateTo"); p.Add("DateTo", to.Date); }
// legacy factoryweb.search: DELETED = answered with a postponement (blacklisted PENDING), PENDING = no answer yet, CLOSE = confirmed
switch (q.StatusCode?.Trim().ToUpperInvariant())
{
case "CLOSE": where.Append(" AND p.STATUSCODE = 'CLOSE'"); break;
case "DELETED": where.Append(" AND p.STATUSCODE = 'PENDING' AND p.BLACKLISTID IS NOT NULL"); break;
case "PENDING": where.Append(" AND p.STATUSCODE = 'PENDING' AND p.BLACKLISTID IS NULL"); break;
case null or "": break;
default: where.Append(" AND 1 = 0"); break;
}
var baseSql = $"""
SELECT p.ID AS Id, p.PERMITID AS PermitId, p.TN AS Tn, p.PN AS Pn, p.STATUSCODE AS StatusCode, p.BLACKLISTID AS BlackListId, NVL(p.ISBLOCKED, 0) AS IsBlocked,
p.PHONENUMBER AS PhoneNumber, p.LOGDURATION AS LogDuration, p.CARGOTYPE AS CargoType, p.DIST_DATE AS DistDate, p.ORDERDATE AS OrderDate,
p.EXPIRYDATE AS ExpiryDate, p.SHIFT AS Shift
FROM TRUCK_DISTRIBUTION_LOG_VIEW p WHERE 1 = 1{where}
""";
var total = await ExecuteScalarAsync<long>(OracleSql.Count(baseSql), p, ct);
if (total == 0) return new PagedResult<CommunicationRow>([], page.SafePage, page.SafePageSize, 0);
p.Add("MinRow", page.MinRow);
p.Add("MaxRow", page.MaxRow);
var items = await QueryAsync<CommunicationRow>(OracleSql.Paginate(baseSql + " ORDER BY p.ID DESC"), p, ct);
return new PagedResult<CommunicationRow>(items, page.SafePage, page.SafePageSize, total);
}
public Task<IReadOnlyList<CargoOption>> GetCargoTypesAsync(CancellationToken ct = default) =>
QueryAsync<CargoOption>("SELECT ID AS Id, NAME AS Name FROM CARGOTYPE WHERE DOMAIN = 'GN' ORDER BY SORTORDER, NAME", null, ct);
public async Task<IReadOnlyList<(long PermitId, string Tn)>> GetUnansweredAsync(CancellationToken ct = default)
{
var rows = await QueryAsync<UnansweredRow>("""
SELECT t.PERMITID AS PermitId, t.TN AS Tn
FROM TRUCK_DISTRIBUTION_LOG_VIEW t, PERMITS p
WHERE t.BLACKLISTID IS NULL AND t.PERMITID = p.ID AND p.COMPANYCODE = '327' AND t.ISBLOCKED = 0
AND p.SHIPMENTSTATUSCODE = 'REQST' AND t.STATUSCODE = 'PENDING'
""", null, ct);
return rows.Select(r => (r.PermitId, r.Tn ?? string.Empty)).ToList();
}
public async Task BlockAsync(IReadOnlyList<long> permitIds, string userId, CancellationToken ct = default)
{
foreach (var chunk in permitIds.Chunk(500))
{
var p = new DynamicParameters(new { UserId = userId.Length <= 20 ? userId : userId[..20] });
for (var i = 0; i < chunk.Length; i++) p.Add("I" + i, chunk[i]);
await ExecuteAsync($"UPDATE TRUCK_DISTRIBUTION_LOG SET UPDATEDATE = SYSDATE, CREATEDBY = :UserId, ISBLOCKED = 1 WHERE PERMITID IN ({string.Join(",", chunk.Select((_, i) => ":I" + i))})", p, ct);
}
}
}
/// <summary>Binds configuration section "Grains:Communication".</summary>
internal sealed class CommunicationSettingsService : ICommunicationSettingsService
{
public CommunicationSettingsService(IConfiguration configuration)
{
Value = new CommunicationOptions();
configuration.GetSection(CommunicationOptions.SectionName).Bind(Value);
}
public CommunicationOptions Value { get; }
}

View File

@ -22,12 +22,12 @@ internal sealed class NotificationRepository(INtpDbSession session, IDbSession p
SELECT ID AS Id, TITLE AS Title, MESSAGE AS Message FROM NOTIFICATIONMESSAGETEMPLATE WHERE TYPE = :Type ORDER BY ID SELECT ID AS Id, TITLE AS Title, MESSAGE AS Message FROM NOTIFICATIONMESSAGETEMPLATE WHERE TYPE = :Type ORDER BY ID
""", new { Type = type }, ct); """, new { Type = type }, ct);
public async Task<IReadOnlyList<long>> FindUserIdsAsync(string roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default) public async Task<IReadOnlyList<long>> FindUserIdsAsync(string? roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default)
{ {
// legacy getLoginInfo: every given field must match, case-insensitively; an empty value matches nothing (Oracle '' is NULL) // legacy getLoginInfo: every given field must match, case-insensitively; an empty value matches nothing (Oracle '' is NULL)
var sql = "SELECT ID FROM NTPUSERS WHERE UPPER(ROLECODE) = UPPER(:Role)"; var sql = "SELECT ID FROM NTPUSERS WHERE 1 = 1";
var p = new Dapper.DynamicParameters(); var p = new Dapper.DynamicParameters();
p.Add("Role", roleCode); if (roleCode is not null) { sql += " AND UPPER(ROLECODE) = UPPER(:Role)"; p.Add("Role", roleCode); }
if (mobile is not null) { sql += " AND UPPER(MOBILE) = UPPER(:Mobile)"; p.Add("Mobile", mobile); } if (mobile is not null) { sql += " AND UPPER(MOBILE) = UPPER(:Mobile)"; p.Add("Mobile", mobile); }
if (login is not null) { sql += " AND UPPER(LOGIN) = UPPER(:Login)"; p.Add("Login", login); } if (login is not null) { sql += " AND UPPER(LOGIN) = UPPER(:Login)"; p.Add("Login", login); }
if (loginContains is not null) { sql += " AND UPPER(LOGIN) LIKE '%' || UPPER(:LoginPart) || '%'"; p.Add("LoginPart", loginContains); } if (loginContains is not null) { sql += " AND UPPER(LOGIN) LIKE '%' || UPPER(:LoginPart) || '%'"; p.Add("LoginPart", loginContains); }
@ -60,6 +60,16 @@ internal sealed class NotificationRepository(INtpDbSession session, IDbSession p
) WHERE ROWNUM = 1 ) WHERE ROWNUM = 1
""", new { Scac = scac }, ct); """, new { Scac = scac }, ct);
public Task InsertPushLogAsync(string userId, string deviceId, string status, string request, string? response, string os, long templateId,
CancellationToken ct = default) =>
ExecuteAsync("""
INSERT INTO MOBILENOTIFICATIONSLOG (ID, USERID, DEVICEID, STATUS, CREATIONDATE, SENDERID, MSG_REQUEST, MSG_RESPONSE, OS, MSG_TEMPLATE_ID, SOURCE_FROM)
VALUES (MOBILENOTIFICATIONID.NEXTVAL, :UserId, :DeviceId, :Status, SYSDATE, :UserId, :Request, :Response, :Os, :TemplateId, 'NTPV2')
""", new
{
UserId = userId, DeviceId = Cut(deviceId, 500), Status = status, Request = Cut(request, 4000), Response = Cut(response, 4000), Os = os, TemplateId = templateId
}, ct);
public Task InsertSmsLogAsync(string userLogin, string mobile, string status, string request, string? response, string provider, string serviceType, public Task InsertSmsLogAsync(string userLogin, string mobile, string status, string request, string? response, string provider, string serviceType,
CancellationToken ct = default) => CancellationToken ct = default) =>
ExecuteAsync(""" ExecuteAsync("""

View File

@ -0,0 +1,275 @@
using System.Globalization;
using System.Text;
using Dapper;
using Microsoft.Extensions.Logging;
using NTP.Application.Common;
using NTP.Application.Receipts;
namespace NTP.Infrastructure.Persistence.Repositories.Receipts;
/// <summary>
/// PERMITS_RECEIPTS, PERMITS_RECEIPTS_VIEW, PERMITS_RECEIPTS_TYPE, RECEIPT_REVOKE_REJECT_REASON and LOG_PERMITS_RECEIPTS (primary NAFITHTCS schema) of
/// permitsreceiptsdao.cfc. NTP tables (CARGOTYPE, NTPUSERS) are read as NTP.&lt;table&gt;, like the legacy queries.
/// </summary>
internal sealed class ReceiptRepository(IDbSession session, ILogger<ReceiptRepository> logger)
: OracleRepositoryBase(session, logger), IReceiptRepository
{
private const string Select = """
SELECT p.ID AS Id, p.RECEIPT_NO AS ReceiptNo, p.PN AS Pn, p.SHIPMENTMODE AS ShipmentMode, p.FMSHIPMENTMODE AS FmShipmentMode, p.CARGO_TYPE AS CargoType,
p.CRN AS Crn, p.CA_CODE AS CaCode, p.CA_NAME AS CaName, p.TN AS Tn, p.TRN AS Trn, p.DRVR AS Drvr, p.NNPN AS Nnpn, p.MOBILE AS Mobile,
p.STATUSCODE AS StatusCode, r.CREATION_DATE AS CreationDate, p.CREATED_BY AS CreatedBy, p.DLN AS Dln, p.DLED AS Dled, p.SCAC AS Scac,
p.COMPANY_NAME AS CompanyName, p.INBOUNDTYPECODE AS InboundTypeCode, p.FMINBOUNDTYPECODE AS FmInboundTypeCode,
p.ORIGINADDRESSID AS OriginAddressId, p.DESTINATIONADDRESSID AS DestinationAddressId, p.FEES AS Fees, p.RECEIPT_TYPE AS ReceiptType,
p.CAPTION AS ReceiptTypeCaption, p.PERMIT_STATUS AS PermitStatus, p.PERMIT_STATUS_CAPTION AS PermitStatusCaption,
p.CONFIRMATION_BY AS ConfirmationBy, p.CONFIRMATION_NAME AS ConfirmationName, r.CONFIRMATION_DATE AS ConfirmationDate,
p.CREATION_SOURCE AS CreationSource, p.CREDIT AS Credit, p.REQUEST_ID AS RequestId, r.REJECT_REASON AS RejectReason,
r.REJECT_REASON_NOTE AS RejectReasonNote, r.REVOKE_DATE AS RevokeDate, r.REVOKE_BY AS RevokeBy
FROM PERMITS_RECEIPTS_VIEW p, PERMITS_RECEIPTS r
WHERE r.ID = p.ID
""";
public async Task<PagedResult<ReceiptRow>> SearchAsync(ReceiptQuery q, PageRequest page, CancellationToken ct = default)
{
var where = new StringBuilder();
var p = new DynamicParameters();
if (long.TryParse(q.ReceiptNo?.Trim(), out var no)) { where.Append(" AND p.RECEIPT_NO = :ReceiptNo"); p.Add("ReceiptNo", no); }
else if (!string.IsNullOrWhiteSpace(q.ReceiptNo)) where.Append(" AND 1 = 0");
if (long.TryParse(q.Pn?.Trim(), out var pn)) { where.Append(" AND p.PN = :Pn"); p.Add("Pn", pn); }
else if (!string.IsNullOrWhiteSpace(q.Pn)) where.Append(" AND 1 = 0");
if (!string.IsNullOrWhiteSpace(q.Tn)) { where.Append(" AND LOWER(p.TN) = LOWER(:Tn)"); p.Add("Tn", q.Tn.Trim()); }
if (!string.IsNullOrWhiteSpace(q.Trn)) { where.Append(" AND LOWER(p.TRN) = LOWER(:Trn)"); p.Add("Trn", q.Trn.Trim()); }
if (int.TryParse(q.CreationSource, out var src)) { where.Append(" AND p.CREATION_SOURCE = :Src"); p.Add("Src", src); }
if (int.TryParse(q.Credit, out var credit)) { where.Append(" AND p.CREDIT = :Credit"); p.Add("Credit", credit); }
// CARGO_CODE is "first - second" (second only for a single move): the legacy filter was "ends with the code"
if (!string.IsNullOrWhiteSpace(q.ShipmentMode)) { where.Append(" AND LOWER(p.CARGO_CODE) LIKE '%' || LOWER(:Cargo)"); p.Add("Cargo", q.ShipmentMode.Trim()); }
if (q.DateFrom is { } from) { where.Append(" AND r.CREATION_DATE >= :DateFrom"); p.Add("DateFrom", from.Date); }
if (q.DateTo is { } to) { where.Append(" AND r.CREATION_DATE < :DateTo"); p.Add("DateTo", to.Date.AddDays(1)); }
var statuses = q.StatusCodes.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).Distinct().ToList();
if (statuses.Count > 0)
{
where.Append($" AND p.STATUSCODE IN ({string.Join(",", statuses.Select((_, i) => ":St" + i))})");
for (var i = 0; i < statuses.Count; i++) p.Add("St" + i, statuses[i]);
}
var baseSql = Select + where;
var total = await ExecuteScalarAsync<long>(OracleSql.Count(baseSql), p, ct);
if (total == 0) return new PagedResult<ReceiptRow>([], page.SafePage, page.SafePageSize, 0);
p.Add("MinRow", page.MinRow);
p.Add("MaxRow", page.MaxRow);
var items = await QueryAsync<ReceiptRow>(OracleSql.Paginate(baseSql + " ORDER BY p.RECEIPT_NO ASC"), p, ct);
return new PagedResult<ReceiptRow>(items, page.SafePage, page.SafePageSize, total);
}
public Task<ReceiptRow?> GetAsync(long id, CancellationToken ct = default) =>
QueryFirstAsync<ReceiptRow>(Select + " AND p.ID = :Id", new { Id = id }, ct);
public async Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct = default)
{
const string baseSql = """
SELECT t.ID AS Id, t.METHOD_NAME AS MethodName, t.LOG_DATE AS LogDate, n.LOGIN AS Login,
DBMS_LOB.SUBSTR(t.OLD_DATA, 4000, 1) AS OldData, DBMS_LOB.SUBSTR(t.NEW_DATA, 4000, 1) AS NewData
FROM LOG_PERMITS_RECEIPTS t, NTP.NTPUSERS n
WHERE t.USER_ID = n.ID AND t.ENTITIY_ID = :Id
""";
var total = await ExecuteScalarAsync<long>(OracleSql.Count(baseSql), new { Id = id }, ct);
if (total == 0) return new PagedResult<ReceiptLogRow>([], page.SafePage, page.SafePageSize, 0);
var items = await QueryAsync<ReceiptLogRow>(OracleSql.Paginate(baseSql + " ORDER BY t.ID DESC"), new { Id = id, page.MinRow, page.MaxRow }, ct);
return new PagedResult<ReceiptLogRow>(items, page.SafePage, page.SafePageSize, total);
}
public Task<IReadOnlyList<ReceiptTypeRow>> GetTypesAsync(long? scac, long? exceptId, CancellationToken ct = default)
{
var sql = "SELECT ID AS Id, CAPTION AS Caption, FEES AS Fees, DESCRIPTION AS Description, SCAC AS Scac FROM PERMITS_RECEIPTS_TYPE WHERE 1 = 1";
var p = new DynamicParameters();
if (scac is { } s) { sql += " AND SCAC = :Scac"; p.Add("Scac", s); }
if (exceptId is { } e) { sql += " AND ID <> :Except"; p.Add("Except", e); }
return QueryAsync<ReceiptTypeRow>(sql + " ORDER BY SORTORDER, ID", p, ct);
}
public Task<ReceiptTypeRow?> GetTypeAsync(long id, CancellationToken ct = default) =>
QueryFirstAsync<ReceiptTypeRow>("SELECT ID AS Id, CAPTION AS Caption, FEES AS Fees, DESCRIPTION AS Description, SCAC AS Scac FROM PERMITS_RECEIPTS_TYPE WHERE ID = :Id", new { Id = id }, ct);
public Task<IReadOnlyList<NamedRow>> GetRejectReasonsAsync(CancellationToken ct = default) =>
QueryAsync<NamedRow>("SELECT TO_CHAR(ID) AS Code, TRIM(NAME) AS Name FROM RECEIPT_REVOKE_REJECT_REASON ORDER BY ID", null, ct);
public Task<IReadOnlyList<NamedRow>> GetCargoTypesAsync(CancellationToken ct = default) =>
QueryAsync<NamedRow>("SELECT CODE AS Code, NAME AS Name FROM NTP.CARGOTYPE ORDER BY NAME", null, ct);
public async Task<bool> PermitMatchesTypeAsync(long receiptType, long pn, CancellationToken ct = default)
{
// legacy checkPermitType*: DM (10) double move, SM (9) single move, Malghi (8) a cancelled supply permit with a claim and no employee cancel reason
const string live = "t.SHIPMENTSTATUSCODE IN ('RESD','ACCPT','CLRPR','ACTWT','ACTRL','CLOSE')";
var sql = receiptType switch
{
10 => $"SELECT COUNT(*) FROM PERMITS t WHERE t.PN = :Pn AND {live} AND t.FMSHIPMENTMODE IS NOT NULL",
9 => $"SELECT COUNT(*) FROM PERMITS t WHERE t.PN = :Pn AND {live} AND t.FMSHIPMENTMODE IS NULL",
8 => "SELECT COUNT(*) FROM PERMITS t, NTP.CLAIMSAPP_DETAILS d WHERE t.PN = :Pn AND t.SHIPMENTSTATUSCODE = 'RVKD' AND t.CAN = '10184' AND d.PERMITNO = t.PN AND d.EMP_CANCEL_REASON IS NULL",
_ => null,
};
return sql is null || await ExecuteScalarAsync<long>(sql, new { Pn = pn }, ct) > 0;
}
public async Task<long> InsertAsync(CreateReceiptRequest r, decimal fees, string status, string userLogin, CancellationToken ct = default)
{
var id = await ExecuteScalarAsync<long>("SELECT SEQ_PERMITS_RECEIPTS.NEXTVAL FROM DUAL", null, ct);
var (fm, sm) = ReceiptRules.SplitModes(r.FmShipmentMode, r.ShipmentMode);
var number = r.Credit == 0 ? CashNumberSql : ClaimNumberSql;
// CREATION_DATE: the legacy insert left it to the column default; CONFIRMATION_DATE stays empty, CONFIRMATION_BY is the creator
await ExecuteAsync($"""
INSERT INTO PERMITS_RECEIPTS (ID, RECEIPT_NO, PN, SHIPMENTMODE, FMSHIPMENTMODE, CRN, CA_CODE, TN, TRN, DRVR, NNPN, MOBILE, CREATION_DATE, CREATED_BY, STATUSCODE,
DLN, DLED, SCAC, FEES, RECEIPT_TYPE, CONFIRMATION_BY, FMINBOUNDTYPECODE, DESTINATIONADDRESSID, ORIGINADDRESSID, INBOUNDTYPECODE, CREDIT)
VALUES (:Id, ({number}), :Pn, :Sm, :Fm, :Crn, :CaCode, :Tn, :Trn, :Drvr, :Nnpn, :Mobile, SYSDATE, :User, :Status,
:Dln, :Dled, :Scac, :Fees, :Type, :User, NULL, :Dest, :Origin, :Inbound, :Credit)
""", new
{
Id = id, Pn = long.Parse(r.Pn!.Trim(), CultureInfo.InvariantCulture), Sm = sm, Fm = fm, Crn = ToLong(r.Crn), CaCode = r.CaCode, Tn = Clean(r.Tn), Trn = Clean(r.Trn),
Drvr = Clean(r.Drvr), Nnpn = Clean(r.Nnpn), Mobile = Clean(r.Mobile), User = Fit(userLogin, 300), Status = status, Dln = Clean(r.Dln), Dled = Clean(r.Dled),
r.Scac, Fees = fees, Type = r.ReceiptType, Dest = r.DestinationAddressId, Origin = r.OriginAddressId, Inbound = Clean(r.InboundTypeCode), r.Credit,
}, ct);
return id;
}
// permitsreceiptsdao.cfc:111-117 (cash receipts: yyyy20001, then +1; counted from 1/3/2024; claims: 209900001, then +1)
private const string CashNumberSql = """
SELECT TO_NUMBER(DECODE(TRIM(NVL(MAX(t.RECEIPT_NO), 0)), 0, TO_CHAR(SYSDATE, 'yyyy') || '20001', TRIM(NVL(MAX(t.RECEIPT_NO), 0) + 1)))
FROM PERMITS_RECEIPTS t WHERE t.CREDIT = 0 AND t.CREATION_DATE > TO_DATE('1/3/2024', 'DD/MM/YYYY')
""";
private const string ClaimNumberSql = """
SELECT TO_NUMBER(DECODE(TRIM(NVL(MAX(t.RECEIPT_NO), 0)), 0, '209900001', TRIM(NVL(MAX(t.RECEIPT_NO), 0) + 1))) FROM PERMITS_RECEIPTS t WHERE t.CREDIT = 1
""";
public async Task<long> InsertPaidCopyAsync(long sourceId, CancellationToken ct = default)
{
var id = await ExecuteScalarAsync<long>("SELECT SEQ_PERMITS_RECEIPTS.NEXTVAL FROM DUAL", null, ct);
await ExecuteAsync($"""
INSERT INTO PERMITS_RECEIPTS (ID, RECEIPT_NO, PERMIT_ID, PN, SHIPMENTMODE, FMSHIPMENTMODE, CRN, CA_CODE, TN, TRN, DRVR, NNPN, MOBILE, CREATION_DATE, CREATED_BY, STATUSCODE,
DLN, DLED, SCAC, FEES, RECEIPT_TYPE, PERMIT_STATUS, CONFIRMATION_BY, FMINBOUNDTYPECODE, DESTINATIONADDRESSID, ORIGINADDRESSID,
INBOUNDTYPECODE, CREDIT, REQUEST_ID)
SELECT :Id, ({CashNumberSql}), s.PERMIT_ID, s.PN, s.SHIPMENTMODE, s.FMSHIPMENTMODE, s.CRN, s.CA_CODE, s.TN, s.TRN, s.DRVR, s.NNPN, s.MOBILE, SYSDATE, s.CREATED_BY, 'RECEIVED',
s.DLN, s.DLED, s.SCAC, s.FEES, s.RECEIPT_TYPE, s.PERMIT_STATUS, s.CONFIRMATION_BY, s.FMINBOUNDTYPECODE, s.DESTINATIONADDRESSID, s.ORIGINADDRESSID,
s.INBOUNDTYPECODE, 0, s.REQUEST_ID
FROM PERMITS_RECEIPTS s WHERE s.ID = :Source
""", new { Id = id, Source = sourceId }, ct);
return id;
}
public async Task<bool> ConfirmAsync(long id, string userLogin, CancellationToken ct = default) =>
await ExecuteAsync("""
UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'RECEIVED', CONFIRMATION_DATE = SYSDATE, CONFIRMATION_BY = :User WHERE ID = :Id AND STATUSCODE = 'NOT_RECEIVED'
""", new { Id = id, User = Fit(userLogin, 300) }, ct) > 0;
public async Task<bool> UpdateAsync(long id, UpdateReceiptRequest r, string userLogin, CancellationToken ct = default)
{
var (fm, sm) = ReceiptRules.SplitModes(r.FmShipmentMode, r.ShipmentMode);
return await ExecuteAsync("""
UPDATE PERMITS_RECEIPTS
SET PN = :Pn, TN = :Tn, TRN = :Trn, DRVR = :Drvr, NNPN = :Nnpn, MOBILE = :Mobile, SHIPMENTMODE = :Sm, FMSHIPMENTMODE = :Fm,
LASTUPDATEDATE = SYSDATE, LASTUPDATEBY = :User
WHERE ID = :Id AND STATUSCODE IN ('RECEIVED', 'UNPAID')
""", new
{
Id = id, Pn = ToLong(r.Pn), Tn = Clean(r.Tn), Trn = Clean(r.Trn), Drvr = Clean(r.Drvr), Nnpn = Clean(r.Nnpn), Mobile = Clean(r.Mobile), Sm = sm, Fm = fm, User = Fit(userLogin, 500),
}, ct) > 0;
}
public async Task<bool> PayAsync(long id, CancellationToken ct = default) =>
await ExecuteAsync("UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'PAID' WHERE ID = :Id AND STATUSCODE = 'UNPAID'", new { Id = id }, ct) > 0;
public async Task<bool> RequestRevokeAsync(long id, long reason, string? note, CancellationToken ct = default) =>
await ExecuteAsync("""
UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'PENDING_RVKD', REJECT_REASON = :Reason, REJECT_REASON_NOTE = :Note
WHERE ID = :Id AND STATUSCODE IN ('RECEIVED', 'UNPAID')
""", new { Id = id, Reason = reason, Note = note }, ct) > 0;
public async Task<bool> RevokeAsync(long id, string fromStatus, long? reason, string? note, string userLogin, CancellationToken ct = default)
{
var p = new DynamicParameters(new { Id = id, From = fromStatus, User = Fit(userLogin, 300) });
var set = "";
if (reason is { } r) { set = ", REJECT_REASON = :Reason, REJECT_REASON_NOTE = :Note"; p.Add("Reason", r); p.Add("Note", note); }
return await ExecuteAsync($"UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'RVKD', REVOKE_DATE = SYSDATE, REVOKE_BY = :User, FEES = 0{set} WHERE ID = :Id AND STATUSCODE = :From", p, ct) > 0;
}
public async Task<bool> RejectRevokeAsync(long id, CancellationToken ct = default) =>
await ExecuteAsync("UPDATE PERMITS_RECEIPTS SET STATUSCODE = 'RECEIVED', REJECT_REASON = NULL WHERE ID = :Id AND STATUSCODE = 'PENDING_RVKD'", new { Id = id }, ct) > 0;
public Task AddLogAsync(long receiptId, string method, string oldData, string newData, long userId, string? ip, string? fileName, CancellationToken ct = default) =>
ExecuteAsync("""
INSERT INTO LOG_PERMITS_RECEIPTS (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, USER_ID, USER_IP, OLD_DATA, NEW_DATA, FILE_NAME)
VALUES (SEQ_LOG_PERMITSRECEIPTS.NEXTVAL, :Entity, :Method, SYSDATE, :UserId, :Ip, :OldData, :NewData, :FileName)
""", new { Entity = receiptId, Method = method, UserId = userId, Ip = ip is null ? null : Fit(ip, 18), OldData = oldData, NewData = newData, FileName = fileName is null ? null : Fit(fileName, 250) }, ct);
public Task<ReceiptAutoFill?> GetGnPermitAsync(string tn, CancellationToken ct = default) =>
QueryFirstAsync<ReceiptAutoFill>("""
SELECT * FROM (
SELECT TRN AS Trn, NNPN AS Nnpn, DRVR AS Drvr, CAST(NULL AS VARCHAR2(1)) AS Mobile, TO_CHAR(PN) AS Pn, CAST(NULL AS VARCHAR2(1)) AS CargoCode
FROM PERMITS WHERE TN = :Tn AND SHIPMENTSTATUSCODE IN ('ACCPT', 'RESD', 'PLND') AND DOMAIN = 'GN' ORDER BY ID DESC
) WHERE ROWNUM = 1
""", new { Tn = tn }, ct);
public Task<ReceiptAutoFill?> GetDriverAsync(string nnpn, CancellationToken ct = default) =>
QueryFirstAsync<ReceiptAutoFill>("""
SELECT * FROM (
SELECT CAST(NULL AS VARCHAR2(1)) AS Trn, NNPN AS Nnpn, NAME_AR AS Drvr, MOBILE AS Mobile, CAST(NULL AS VARCHAR2(1)) AS Pn, CAST(NULL AS VARCHAR2(1)) AS CargoCode
FROM DRIVERS_INFO WHERE LOWER(NNPN) = LOWER(:Nnpn) AND STATUS_CODE = 'COMPLETED' ORDER BY ID DESC
) WHERE ROWNUM = 1
""", new { Nnpn = nnpn }, ct);
public async Task<bool> UserExistsAsync(string login, CancellationToken ct = default) =>
await ExecuteScalarAsync<long>("SELECT COUNT(*) FROM NTP.NTPUSERS WHERE UPPER(LOGIN) = UPPER(:Login)", new { Login = login }, ct) > 0;
private sealed class PairRow { public string? K { get; set; } public string? V { get; set; } }
public async Task<AuditLookups> GetAuditLookupsAsync(CancellationToken ct = default)
{
var cargo = await QueryAsync<PairRow>("SELECT NAME AS K, CODE AS V FROM NTP.CARGOTYPE", null, ct);
var ops = await QueryAsync<PairRow>("SELECT CAPTION AS K, CODE AS V FROM OPERATIONTYPE WHERE DOMAIN = 'ASEZA'", null, ct);
var locs = await QueryAsync<PairRow>("SELECT SHORTNAME AS K, TO_CHAR(ID) AS V FROM LOCATIONS WHERE DOMAIN = 'ASEZA' AND TYPE IN ('EN', 'EX')", null, ct);
var types = await GetTypesAsync(null, null, ct);
static Dictionary<string, string> Map(IEnumerable<PairRow> rows) =>
rows.Where(r => !string.IsNullOrWhiteSpace(r.K) && r.V is not null).GroupBy(r => r.K!.Trim()).ToDictionary(g => g.Key, g => g.First().V!.Trim());
return new AuditLookups
{
CargoCodeByName = Map(cargo), OperationCodeByCaption = Map(ops),
LocationIdByShortName = Map(locs).Where(kv => long.TryParse(kv.Value, out _)).ToDictionary(kv => kv.Key, kv => long.Parse(kv.Value, CultureInfo.InvariantCulture)),
Types = types,
};
}
public Task<IReadOnlyList<ReceiptRow>> GetForAuditAsync(IReadOnlyList<string> statuses, AuditFilter f, CancellationToken ct = default)
{
var p = new DynamicParameters();
var sql = new StringBuilder(Select);
sql.Append($" AND p.STATUSCODE IN ({string.Join(",", statuses.Select((_, i) => ":St" + i))})");
for (var i = 0; i < statuses.Count; i++) p.Add("St" + i, statuses[i]);
if (f.DateFrom is { } from && f.DateTo is { } to)
{
if (f.TimeFrom is { } tf && f.TimeTo is { } tt)
{
sql.Append(" AND r.CONFIRMATION_DATE BETWEEN :From AND :To");
p.Add("From", from.Date + tf); p.Add("To", to.Date + tt);
}
else
{
sql.Append(" AND r.CONFIRMATION_DATE >= :From AND r.CONFIRMATION_DATE < :To");
p.Add("From", from.Date); p.Add("To", to.Date.AddDays(1));
}
}
if (!string.IsNullOrWhiteSpace(f.ConfirmationBy)) { sql.Append(" AND LOWER(p.CONFIRMATION_BY) = LOWER(:By)"); p.Add("By", f.ConfirmationBy.Trim()); }
sql.Append(" ORDER BY p.RECEIPT_NO ASC");
return QueryAsync<ReceiptRow>(sql.ToString(), p, ct);
}
public async Task SetStatusAsync(IReadOnlyList<long> ids, string status, CancellationToken ct = default)
{
foreach (var chunk in ids.Chunk(500))
{
var p = new DynamicParameters(new { Status = status });
for (var i = 0; i < chunk.Length; i++) p.Add("I" + i, chunk[i]);
await ExecuteAsync($"UPDATE PERMITS_RECEIPTS SET STATUSCODE = :Status WHERE ID IN ({string.Join(",", chunk.Select((_, i) => ":I" + i))})", p, ct);
}
}
private static string? Clean(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim();
private static string Fit(string v, int max) => v.Length <= max ? v : v[..max];
private static long? ToLong(string? s) => long.TryParse(s?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? n : null;
}

View File

@ -0,0 +1,33 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NTP.Application.Refinery.Sync;
namespace NTP.Infrastructure.Persistence.Repositories.Refinery.Sync;
/// <summary>The two totals of jobs/RefineryTrip_Exchange_email.cfm (NAFITHTCS connection).</summary>
internal sealed class RefineryDailyReportRepository(IDbSession session, ILogger<RefineryDailyReportRepository> logger)
: OracleRepositoryBase(session, logger), IRefineryDailyReportRepository
{
public async Task<(decimal First, decimal Second)> GetTotalsAsync(CancellationToken ct = default)
{
var first = await ExecuteScalarAsync<decimal?>(
"SELECT NVL(SUM(T.NET_WAGE), 0) FROM REFINERY_TRIPS T WHERE T.STATUS_CODE = 'EXCHANGED' AND T.WAGE_CLAIM_ID IS NULL", null, ct);
var second = await ExecuteScalarAsync<decimal?>("""
SELECT ROUND(SUM(CalculateRefinaryAmountReport(T.ID, 0)), 3) FROM REFINERY_TRIPS T
WHERE T.WAGE_CLAIM_ID IN (SELECT ID FROM REFINERY_WAGE_CLAIM WHERE STATUS_CODE = 'NEW')
""", null, ct);
return (first ?? 0m, second ?? 0m);
}
}
/// <summary>Binds configuration section "Refinery:Jobs" (see <see cref="RefineryJobOptions"/>).</summary>
internal sealed class RefineryJobSettingsService : IRefineryJobSettingsService
{
public RefineryJobSettingsService(IConfiguration configuration)
{
Value = new RefineryJobOptions();
configuration.GetSection(RefineryJobOptions.SectionName).Bind(Value);
}
public RefineryJobOptions Value { get; }
}

View File

@ -0,0 +1,102 @@
using System.Globalization;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using Dapper;
using Microsoft.Extensions.Logging;
using NTP.Application.Refinery.Sync;
using Oracle.ManagedDataAccess.Client;
namespace NTP.Infrastructure.Persistence.Repositories.Refinery.Sync;
/// <summary>SQL of jobs/REFINERY_OIL.cfm (callInsertDbBulk, callUpdateDbBulk, getRecordByPn), NAFITHTCS connection, bind variables.</summary>
internal sealed class RefineryOilSyncRepository(IDbSession session, ILogger<RefineryOilSyncRepository> logger)
: OracleRepositoryBase(session, logger), IRefineryOilSyncRepository
{
private static readonly JsonSerializerOptions Json = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
public async Task<ExistingTrip?> FindByPnAsync(string pn, CancellationToken ct = default) =>
await QueryFirstAsync<ExistingTrip>("SELECT ID AS Id, PN AS Pn, TRIP_STATUS AS TripStatus, STATUS_CODE AS StatusCode FROM REFINERY_TRIPS WHERE PN = :Pn", new { Pn = pn }, ct);
private static decimal? LoadingNo(JopetrolTripRecord t) =>
decimal.TryParse(t.LoadingNo, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : null;
private static string RawJson(JopetrolTripRecord t)
{
var text = JsonSerializer.Serialize(t.Raw, Json);
return text.Length <= 3500 ? text : text[..3500];
}
public async Task<bool> InsertAsync(JopetrolTripRecord t, string statusCode, string createdBy, CancellationToken ct = default)
{
var id = await ExecuteScalarAsync<long>("SELECT SEQ_REFINERY_TRIPS.NEXTVAL FROM DUAL", null, ct);
try
{
await ExecuteAsync("""
INSERT INTO REFINERY_TRIPS (ID, PN, DISPATCH_DATE, ACTUAL_LOADING_DATE, ACTUAL_LOADING_TIME, LOADING_CENTER, CLIENT_NO, TN, TRN, NNPN, MATERIAL_NO, MENAGATE_NO,
EMPTY_WEIGHT, GROSS_WEIGHT, NET_LOADING_WEIGHT, STANDARD_UNITS_WEIGHT, LITERS_WEIGHT, DENSITY, TEMPERATURE, FLAG,
DISCHARGE_AUTHORIZTION_NO, DISCHARGE_AUTHORIZTION_YEAR, DISCHARGE_ENTRY_DATE, DISCHARGE_ENTRY_TIME, DISCHARGE_EXIT_DATE, DISCHARGE_EXIT_TIME,
ACTUAL_GROSS_WEIGHT, ACTUAL_EMPTY_WEIGHT, NET_DISCHARGE_WEIGHT, WATER_AMOUNT, SEDIMENT_AMOUNT, TRIP_STATUS, USER_ID, TRIP_LAST_UPDATE_DATE,
DAY_TIME, PROGRAM_ID, WORK_STN_ID, EXCHANGE_CLAIM_NO, PAID_AMOUNT_WATER, STATUS_CODE, LOADING_NO, CREATED_BY, LAST_UPDATE_DATE,
DINARAK_REFERENCE_ID, WATER_FLAG)
VALUES (:Id, :Pn, :DispatchDate, :ActualLoadingDate, :ActualLoadingTime, :LoadingCenter, :ClientNo, :Tn, :Trn, :Nnpn, :MaterialNo, :MenagateNo,
:EmptyWeight, :GrossWeight, :NetLoadingWeight, :StandardUnitsWeight, :LitersWeight, :Density, :Temperature, :Flag,
:DischargeAuthorizationNo, :DischargeAuthorizationYear, :DischargeEntryDate, :DischargeEntryTime, :DischargeExitDate, :DischargeExitTime,
:ActualGrossWeight, :ActualEmptyWeight, :NetDischargeWeight, :WaterAmount, :SedimentAmount, :TripStatus, :UserId, :TripLastUpdateDate,
:DayTime, :ProgramId, :WorkStnId, :ExchangeClaimNo, :PaidAmountWater, :StatusCode, :LoadingNo, :CreatedBy, SYSDATE,
:Id, :WaterFlag)
""", new
{
Id = id, t.Pn, t.DispatchDate, t.ActualLoadingDate, t.ActualLoadingTime, t.LoadingCenter, t.ClientNo, t.Tn, t.Trn, t.Nnpn, t.MaterialNo, t.MenagateNo,
t.EmptyWeight, t.GrossWeight, t.NetLoadingWeight, t.StandardUnitsWeight, t.LitersWeight, t.Density, t.Temperature, t.Flag,
t.DischargeAuthorizationNo, t.DischargeAuthorizationYear, t.DischargeEntryDate, t.DischargeEntryTime, t.DischargeExitDate, t.DischargeExitTime,
t.ActualGrossWeight, t.ActualEmptyWeight, t.NetDischargeWeight, t.WaterAmount, t.SedimentAmount,
TripStatus = t.TripStatus.ToString(CultureInfo.InvariantCulture), t.UserId, t.TripLastUpdateDate,
t.DayTime, t.ProgramId, t.WorkStnId, t.ExchangeClaimNo, t.PaidAmountWater, StatusCode = statusCode, LoadingNo = LoadingNo(t), CreatedBy = createdBy, t.WaterFlag,
}, ct);
}
catch (OracleException ex) when (ex.Number == 1) { return false; } // legacy: 23000 (unique key) = already there, skip
await ExecuteAsync("""
INSERT INTO REFINERY_TRIPS_LOG (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, STATUS_CODE, OLD_DATA, NEW_DATA, TRIP_STATUS, USER_ID)
VALUES (SEQ_REFINERY_TRIPS_LOG.NEXTVAL, :Id, 'CREATE', SYSDATE, 'RESD', NULL, :NewData, :TripStatus, (SELECT MIN(n.ID) FROM NTP.NTPUSERS n WHERE n.LOGIN = 'SYSTEM'))
""", new { Id = id, NewData = RawJson(t), TripStatus = t.TripStatus.ToString(CultureInfo.InvariantCulture) }, ct);
return true;
}
public async Task UpdateAsync(ExistingTrip old, JopetrolTripRecord t, string statusCode, int tripStatus, string updatedBy, CancellationToken ct = default)
{
await ExecuteAsync("""
UPDATE REFINERY_TRIPS SET
ACTUAL_LOADING_DATE = :ActualLoadingDate, LOADING_NO = :LoadingNo, ACTUAL_LOADING_TIME = :ActualLoadingTime, LOADING_CENTER = :LoadingCenter,
CLIENT_NO = :ClientNo, TRN = :Trn, NNPN = :Nnpn, MATERIAL_NO = :MaterialNo, MENAGATE_NO = :MenagateNo,
EMPTY_WEIGHT = :EmptyWeight, GROSS_WEIGHT = :GrossWeight, NET_LOADING_WEIGHT = :NetLoadingWeight, STANDARD_UNITS_WEIGHT = :StandardUnitsWeight,
LITERS_WEIGHT = :LitersWeight, DENSITY = :Density, TEMPERATURE = :Temperature, FLAG = :Flag,
DISCHARGE_AUTHORIZTION_NO = :DischargeAuthorizationNo, DISCHARGE_AUTHORIZTION_YEAR = :DischargeAuthorizationYear,
DISCHARGE_ENTRY_DATE = :DischargeEntryDate, DISCHARGE_ENTRY_TIME = :DischargeEntryTime, DISCHARGE_EXIT_DATE = :DischargeExitDate, DISCHARGE_EXIT_TIME = :DischargeExitTime,
ACTUAL_GROSS_WEIGHT = :ActualGrossWeight, ACTUAL_EMPTY_WEIGHT = :ActualEmptyWeight, NET_DISCHARGE_WEIGHT = :NetDischargeWeight,
WATER_AMOUNT = :WaterAmount, SEDIMENT_AMOUNT = :SedimentAmount, TRIP_STATUS = :TripStatus, USER_ID = :UserId,
TRIP_LAST_UPDATE_DATE = :TripLastUpdateDate, DAY_TIME = :DayTime, PROGRAM_ID = :ProgramId, WORK_STN_ID = :WorkStnId,
EXCHANGE_CLAIM_NO = :ExchangeClaimNo, PAID_AMOUNT_WATER = :PaidAmountWater, STATUS_CODE = :StatusCode,
UPDATED_BY = :UpdatedBy, LAST_UPDATE_DATE = SYSDATE
WHERE ID = :Id
""", new
{
Id = old.Id, t.ActualLoadingDate, LoadingNo = LoadingNo(t), t.ActualLoadingTime, t.LoadingCenter, t.ClientNo, t.Trn, t.Nnpn, t.MaterialNo, t.MenagateNo,
t.EmptyWeight, t.GrossWeight, t.NetLoadingWeight, t.StandardUnitsWeight, t.LitersWeight, t.Density, t.Temperature, t.Flag,
t.DischargeAuthorizationNo, t.DischargeAuthorizationYear, t.DischargeEntryDate, t.DischargeEntryTime, t.DischargeExitDate, t.DischargeExitTime,
t.ActualGrossWeight, t.ActualEmptyWeight, t.NetDischargeWeight, t.WaterAmount, t.SedimentAmount,
TripStatus = tripStatus.ToString(CultureInfo.InvariantCulture), t.UserId, t.TripLastUpdateDate, t.DayTime, t.ProgramId, t.WorkStnId,
t.ExchangeClaimNo, t.PaidAmountWater, StatusCode = statusCode, UpdatedBy = updatedBy,
}, ct);
var oldData = JsonSerializer.Serialize(new Dictionary<string, string?> { ["STATUS_CODE"] = old.StatusCode, ["TRIP_STATUS"] = old.TripStatus }, Json);
await ExecuteAsync("""
INSERT INTO REFINERY_TRIPS_LOG (ID, ENTITIY_ID, METHOD_NAME, LOG_DATE, STATUS_CODE, OLD_DATA, NEW_DATA, TRIP_STATUS, USER_ID)
VALUES (SEQ_REFINERY_TRIPS_LOG.NEXTVAL, :Id, :Method, SYSDATE, :StatusCode, :OldData, :NewData, :TripStatus, (SELECT MIN(n.ID) FROM NTP.NTPUSERS n WHERE n.LOGIN = 'SYSTEM'))
""", new
{
Id = old.Id, Method = statusCode, StatusCode = statusCode, OldData = oldData, NewData = RawJson(t), TripStatus = tripStatus.ToString(CultureInfo.InvariantCulture),
}, ct);
}
}

View File

@ -0,0 +1,70 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NTP.Application.Registrar;
namespace NTP.Infrastructure.Persistence.Repositories.Registrar;
/// <summary>
/// The lists of the registrar forms (legacy lookups.cfc: LT_PUBLIC_VIEW by LT_TYPE and the NATIONALITY table), LT_CAPTION texts and the ATTACHMENTS rows
/// (attachments.cfc getAttachment). All of them are in the NTP schema.
/// </summary>
internal sealed class RegistrarLookupRepository(INtpDbSession session, ILogger<RegistrarLookupRepository> logger)
: NtpRepositoryBase(session, logger), IRegistrarLookupRepository
{
/// <summary>The LT_TYPEs the three forms use (lookups.cfc fillLookupArray list).</summary>
private static readonly string[] Types =
[
"TRAILER_TYPE", "TRUCK_TYPE", "TRAILER_USAGE_TYPE", "TRUCK_USAGE_TYPE", "COLOR", "VEHICLE_MANIFACTURER", "DRIVER_REVOKE_REASON",
"TRUCK_REVOKE_REASON", "TRAILER_REVOKE_REASON", "JORDAN_GOVERNATE", "BLOOD_GROUP", "DRIVER_LICENSE_TYPE",
];
private sealed class ListRow
{
public string? ListName { get; set; }
public string? Code { get; set; }
public string? Ar { get; set; }
public string? En { get; set; }
}
public async Task<IReadOnlyDictionary<string, IReadOnlyList<LookupItem>>> GetListsAsync(CancellationToken ct = default)
{
var names = string.Join(",", Types.Select((_, i) => ":T" + i));
var p = new Dapper.DynamicParameters();
for (var i = 0; i < Types.Length; i++) p.Add("T" + i, Types[i]);
var rows = await QueryAsync<ListRow>(
$"SELECT p.LT_TYPE AS ListName, p.CODE AS Code, p.AR AS Ar, p.EN AS En FROM LT_PUBLIC_VIEW p WHERE p.LT_TYPE IN ({names}) ORDER BY p.LT_TYPE, p.ORDERING, p.AR", p, ct);
// the legacy shows the caption of the code, or the code itself when there is none
var lists = rows.GroupBy(r => r.ListName ?? string.Empty).ToDictionary(
g => g.Key,
g => (IReadOnlyList<LookupItem>)g.Where(r => !string.IsNullOrEmpty(r.Code))
.Select(r => new LookupItem(r.Code!, Pick(r.Ar, r.Code!), Pick(r.En, Pick(r.Ar, r.Code!)))).ToList());
var nationalities = await QueryAsync<ListRow>("SELECT CODE AS Code, NAME AS Ar FROM NATIONALITY ORDER BY ID", null, ct);
lists["NATIONALITY"] = nationalities.Where(r => !string.IsNullOrEmpty(r.Code))
.Select(r => new LookupItem(r.Code!, Pick(r.Ar, r.Code!), Pick(r.Ar, r.Code!))).ToList();
foreach (var t in Types) lists.TryAdd(t, []);
return lists;
}
public Task<IReadOnlyList<RegistrarAttachmentRow>> GetAttachmentsAsync(string entity, long id, CancellationToken ct = default) =>
QueryAsync<RegistrarAttachmentRow>(
"SELECT ID AS Id, FILENAME AS FileName FROM ATTACHMENTS WHERE ENTITYID = :Id AND ENTITYNAME = :Entity ORDER BY ID", new { Id = id, Entity = entity }, ct);
public Task<string?> GetCaptionAsync(string code, CancellationToken ct = default) =>
QueryFirstAsync<string>("SELECT AR FROM LT_CAPTION WHERE CODE = :Code AND AR IS NOT NULL", new { Code = code }, ct);
private static string Pick(string? text, string fallback) => string.IsNullOrWhiteSpace(text) ? fallback : text.Trim();
}
/// <summary>Binds configuration section "Registrar".</summary>
internal sealed class RegistrarSettingsService : IRegistrarSettingsService
{
public RegistrarSettingsService(IConfiguration configuration)
{
Value = new RegistrarOptions();
configuration.GetSection(RegistrarOptions.SectionName).Bind(Value);
}
public RegistrarOptions Value { get; }
}

View File

@ -0,0 +1,163 @@
using System.Globalization;
using System.Text;
using Dapper;
using Microsoft.Extensions.Logging;
using NTP.Application.Common;
using NTP.Application.Registrar;
namespace NTP.Infrastructure.Persistence.Repositories.Registrar;
/// <summary>
/// DRIVERS_INFO / TRUCKS_INFO / TRAILERS_INFO (primary NAFITHTCS schema) of driverinfodao.cfc, truckinfodao.cfc, trailerinfodao.cfc and the grid views
/// DRIVER_INFO_VIEW / TRUCK_INFO_VIEW / TRAILER_INFO_VIEW (the views only rename and format columns; the tables are read directly).
/// </summary>
internal sealed class RegistrarRepository(IDbSession session, ILogger<RegistrarRepository> logger)
: OracleRepositoryBase(session, logger), IRegistrarRepository
{
private const string DriverColumns = """
p.ID AS Id, p.STATUS_CODE AS StatusCode, p.NNPN AS Nnpn, p.NAME_AR AS NameAr, p.NAME_EN AS NameEn, p.NATIONALITY AS Nationality,
p.DATE_OF_BIRTH AS DateOfBirth, p.BLOOD_GROUP AS BloodGroup, p.ADDRESS AS Address, p.LICENSE_NO AS LicenseNo, p.LICENSE_TYPE AS LicenseType,
p.LICENSE_ISSUE_DATE AS LicenseIssueDate, p.LICENSE_EXPIRY_DATE AS LicenseExpiryDate, p.MOBILE AS Mobile, p.GOVERNATE AS Governate,
p.NOTES AS Notes, p.REVOKE_REASON AS RevokeReason, p.CREATED_BY AS CreatedBy, p.CREATION_DATE AS CreationDate, p.UPDATED_BY AS UpdatedBy,
p.LAST_UPDATE_DATE AS LastUpdateDate
""";
private const string TruckColumns = """
p.ID AS Id, p.STATUS_CODE AS StatusCode, p.TN AS PlateNo, p.TN_CODE AS PlateCode, p.NATIONALITY AS Nationality, p.LICENSE_NO AS LicenseNo,
p.LICENSE_REGISTRATION_NO AS LicenseRegistrationNo, p.LICENSE_EXPIRY_DATE AS LicenseExpiryDate, p.MANIFACTURER AS Manufacturer,
p.MANIFACTURE_YEAR AS ManufactureYear, p.TRUCK_TYPE AS VehicleType, p.TRUCK_CATEGORY AS Category, p.COLOR AS Color, p.SECONDARY_COLOR AS SecondaryColor,
p.MODEL AS Model, p.VIN_NUMBER AS VinNumber, p.ENGINE_NUMBER AS EngineNumber, p.LOADING_WEIGHT AS LoadingWeight, p.GROSS_WEIGHT AS GrossWeight,
(p.GROSS_WEIGHT - p.LOADING_WEIGHT) AS EmptyWeight, p.OWNER_NAME AS OwnerName, p.OWNER_NNPN AS OwnerNnpn, p.OWNER_PHONE_NUMBER AS OwnerPhoneNumber,
p.OWNER_ADDRESS AS OwnerAddress, p.GOVERNATE AS Governate, p.NOTES AS Notes, p.REVOKE_REASON AS RevokeReason, p.CREATED_BY AS CreatedBy,
p.CREATION_DATE AS CreationDate, p.UPDATED_BY AS UpdatedBy, p.LAST_UPDATE_DATE AS LastUpdateDate
""";
private const string TrailerColumns = """
p.ID AS Id, p.STATUS_CODE AS StatusCode, p.TRN AS PlateNo, p.TRN_CODE AS PlateCode, p.NATIONALITY AS Nationality, p.LICENSE_NO AS LicenseNo,
p.LICENSE_REGISTRATION_NO AS LicenseRegistrationNo, p.LICENSE_EXPIRY_DATE AS LicenseExpiryDate, p.MANIFACTURER AS Manufacturer,
p.MANIFACTURE_YEAR AS ManufactureYear, p.TRAILER_TYPE AS VehicleType, p.TRAILER_CATEGORY AS Category, p.COLOR AS Color, p.SECONDARY_COLOR AS SecondaryColor,
p.MODEL AS Model, p.VIN_NUMBER AS VinNumber, p.ENGINE_NUMBER AS EngineNumber, p.LOADING_WEIGHT AS LoadingWeight, p.GROSS_WEIGHT AS GrossWeight,
p.OWNER_NAME AS OwnerName, p.OWNER_NNPN AS OwnerNnpn, p.OWNER_PHONE_NUMBER AS OwnerPhoneNumber,
p.OWNER_ADDRESS AS OwnerAddress, p.GOVERNATE AS Governate, p.NOTES AS Notes, p.REVOKE_REASON AS RevokeReason, p.CREATED_BY AS CreatedBy,
p.CREATION_DATE AS CreationDate, p.UPDATED_BY AS UpdatedBy, p.LAST_UPDATE_DATE AS LastUpdateDate
""";
private static string Columns(RegistrarKind kind) => kind switch { RegistrarKind.Driver => DriverColumns, RegistrarKind.Truck => TruckColumns, _ => TrailerColumns };
private static string Table(RegistrarKind kind) => RegistrarKinds.Of(kind).Table;
/// <summary>Plate column of a truck / trailer, NNPN of a driver: what the "number" filter compares.</summary>
private static string NumberColumn(RegistrarKind kind) => kind switch { RegistrarKind.Driver => "p.NNPN", RegistrarKind.Truck => "p.TN", _ => "p.TRN" };
public async Task<PagedResult<RegistrarRecord>> SearchAsync(RegistrarKind kind, RegistrarQuery query, PageRequest page, CancellationToken ct = default)
{
var where = new StringBuilder(" WHERE 1 = 1");
var p = new DynamicParameters();
if (!string.IsNullOrWhiteSpace(query.Number)) { where.Append($" AND LOWER({NumberColumn(kind)}) = LOWER(:Number)"); p.Add("Number", query.Number.Trim()); }
if (!string.IsNullOrWhiteSpace(query.LicenseNo)) { where.Append(" AND LOWER(p.LICENSE_NO) = LOWER(:LicenseNo)"); p.Add("LicenseNo", query.LicenseNo.Trim()); }
if (kind == RegistrarKind.Driver)
{
if (!string.IsNullOrWhiteSpace(query.Name)) { where.Append(" AND LOWER(p.NAME_AR) LIKE '%' || LOWER(:Name) || '%'"); p.Add("Name", query.Name.Trim()); }
}
else
{
if (!string.IsNullOrWhiteSpace(query.OwnerName)) { where.Append(" AND LOWER(p.OWNER_NAME) LIKE '%' || LOWER(:OwnerName) || '%'"); p.Add("OwnerName", query.OwnerName.Trim()); }
if (!string.IsNullOrWhiteSpace(query.VinNumber)) { where.Append(" AND LOWER(p.VIN_NUMBER) = LOWER(:Vin)"); p.Add("Vin", query.VinNumber.Trim()); }
}
if (query.DateFrom is { } from) { where.Append(" AND p.CREATION_DATE >= :DateFrom"); p.Add("DateFrom", from.Date); }
if (query.DateTo is { } to) { where.Append(" AND p.CREATION_DATE < :DateTo"); p.Add("DateTo", to.Date.AddDays(1)); }
var statuses = query.StatusCodes.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim()).Distinct().ToList();
if (statuses.Count > 0)
{
where.Append($" AND p.STATUS_CODE IN ({string.Join(",", statuses.Select((_, i) => ":St" + i))})");
for (var i = 0; i < statuses.Count; i++) p.Add("St" + i, statuses[i]);
}
var baseSql = $"SELECT {Columns(kind)} FROM {Table(kind)} p{where}";
var total = await ExecuteScalarAsync<long>(OracleSql.Count(baseSql), p, ct);
if (total == 0) return new PagedResult<RegistrarRecord>([], page.SafePage, page.SafePageSize, 0);
p.Add("MinRow", page.MinRow);
p.Add("MaxRow", page.MaxRow);
var items = await QueryAsync<RegistrarRecord>(OracleSql.Paginate(baseSql + " ORDER BY p.ID ASC"), p, ct);
return new PagedResult<RegistrarRecord>(items, page.SafePage, page.SafePageSize, total);
}
public Task<RegistrarRecord?> GetAsync(RegistrarKind kind, long id, CancellationToken ct = default) =>
QueryFirstAsync<RegistrarRecord>($"SELECT {Columns(kind)} FROM {Table(kind)} p WHERE p.ID = :Id", new { Id = id }, ct);
public async Task<bool> UpdateAsync(RegistrarKind kind, long id, string expectedStatus, RegistrarUpdateRequest v, string userId, CancellationToken ct = default)
{
var p = new DynamicParameters();
p.Add("Id", id);
p.Add("Status", expectedStatus);
p.Add("UserId", Fit(userId, 50));
p.Add("Nationality", Clean(v.Nationality));
p.Add("Governate", Clean(v.Governate));
p.Add("Notes", Clean(v.Notes));
p.Add("LicenseNo", Upper(v.LicenseNo));
string sets;
if (kind == RegistrarKind.Driver)
{
p.Add("NameAr", Clean(v.NameAr)); p.Add("NameEn", Clean(v.NameEn)); p.Add("Nnpn", Clean(v.Nnpn)); p.Add("Mobile", Clean(v.Mobile));
p.Add("DateOfBirth", v.DateOfBirth?.Date); p.Add("BloodGroup", Clean(v.BloodGroup)); p.Add("Address", Clean(v.Address));
p.Add("LicenseType", Clean(v.LicenseType)); p.Add("LicenseIssueDate", v.LicenseIssueDate?.Date); p.Add("LicenseExpiryDate", v.LicenseExpiryDate?.Date);
sets = """
NATIONALITY = :Nationality, NAME_AR = :NameAr, NAME_EN = :NameEn, NNPN = :Nnpn, MOBILE = :Mobile, DATE_OF_BIRTH = :DateOfBirth,
BLOOD_GROUP = :BloodGroup, GOVERNATE = :Governate, ADDRESS = :Address, LICENSE_NO = :LicenseNo, LICENSE_TYPE = :LicenseType,
LICENSE_ISSUE_DATE = :LicenseIssueDate, LICENSE_EXPIRY_DATE = :LicenseExpiryDate, NOTES = :Notes
""";
}
else
{
p.Add("PlateNo", Clean(v.PlateNo)); p.Add("PlateCode", Clean(v.PlateCode)); p.Add("OwnerName", Clean(v.OwnerName)); p.Add("OwnerAddress", Clean(v.OwnerAddress));
p.Add("Manufacturer", Clean(v.Manufacturer)); p.Add("Model", Upper(v.Model)); p.Add("Color", Clean(v.Color)); p.Add("SecondaryColor", Clean(v.SecondaryColor));
p.Add("ManufactureYear", ToLong(v.ManufactureYear)); p.Add("LicenseExpiryDate", v.LicenseExpiryDate?.Date); p.Add("Category", Clean(v.Category));
p.Add("LicenseRegistrationNo", Upper(v.LicenseRegistrationNo)); p.Add("VinNumber", Upper(v.VinNumber)); p.Add("EngineNumber", Upper(v.EngineNumber));
p.Add("LoadingWeight", ToDecimal(v.LoadingWeight)); p.Add("GrossWeight", ToDecimal(v.GrossWeight));
var plate = kind == RegistrarKind.Truck ? "TN" : "TRN";
var category = kind == RegistrarKind.Truck ? "TRUCK_CATEGORY" : "TRAILER_CATEGORY";
sets = $"""
NATIONALITY = :Nationality, {plate} = :PlateNo, {plate}_CODE = :PlateCode, OWNER_NAME = :OwnerName, GOVERNATE = :Governate,
OWNER_ADDRESS = :OwnerAddress, MANIFACTURER = :Manufacturer, MODEL = :Model, COLOR = :Color, SECONDARY_COLOR = :SecondaryColor,
MANIFACTURE_YEAR = :ManufactureYear, LICENSE_EXPIRY_DATE = :LicenseExpiryDate, {category} = :Category, LICENSE_NO = :LicenseNo,
LICENSE_REGISTRATION_NO = :LicenseRegistrationNo, VIN_NUMBER = :VinNumber, ENGINE_NUMBER = :EngineNumber,
LOADING_WEIGHT = :LoadingWeight, GROSS_WEIGHT = :GrossWeight, NOTES = :Notes
""";
if (kind == RegistrarKind.Truck) { p.Add("VehicleType", Clean(v.VehicleType)); sets += ", TRUCK_TYPE = :VehicleType"; }
}
var rows = await ExecuteAsync($"UPDATE {Table(kind)} SET {sets}, UPDATED_BY = :UserId, LAST_UPDATE_DATE = SYSDATE WHERE ID = :Id AND STATUS_CODE = :Status", p, ct);
return rows > 0;
}
public async Task<bool> ChangeStatusAsync(RegistrarKind kind, long id, string fromStatus, string toStatus, string userId, string? revokeReason, CancellationToken ct = default)
{
var p = new DynamicParameters(new { Id = id, From = fromStatus, To = toStatus, UserId = Fit(userId, 50) });
var reason = "";
if (revokeReason is not null) { reason = ", REVOKE_REASON = :Reason"; p.Add("Reason", Fit(revokeReason, 100)); }
var rows = await ExecuteAsync(
$"UPDATE {Table(kind)} SET STATUS_CODE = :To, UPDATED_BY = :UserId, LAST_UPDATE_DATE = SYSDATE{reason} WHERE ID = :Id AND STATUS_CODE = :From", p, ct);
return rows > 0;
}
public Task<string?> FindPlateByVinAsync(RegistrarKind kind, string vin, long? excludeId, CancellationToken ct = default)
{
var plate = kind == RegistrarKind.Truck ? "TN" : "TRN";
var p = new DynamicParameters(new { Vin = vin });
var exclude = "";
if (excludeId is { } id) { exclude = " AND p.ID <> :ExcludeId"; p.Add("ExcludeId", id); }
return QueryFirstAsync<string>($"""
SELECT * FROM (
SELECT p.{plate} FROM {Table(kind)} p
WHERE LOWER(p.VIN_NUMBER) = LOWER(:Vin) AND p.STATUS_CODE <> 'REVOKE' AND LOWER(p.NATIONALITY) = 'jo'{exclude}
ORDER BY p.ID
) WHERE ROWNUM = 1
""", p, ct);
}
private static string? Clean(string? s) => RegistrarRules.Clean(s);
private static string? Upper(string? s) => RegistrarRules.Clean(s)?.ToUpperInvariant();
private static string Fit(string value, int max) => value.Length <= max ? value : value[..max];
private static long? ToLong(string? s) => long.TryParse(s?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? n : null;
private static decimal? ToDecimal(string? s) => decimal.TryParse(s?.Trim(), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var n) ? n : null;
}

View File

@ -0,0 +1,50 @@
using Microsoft.Extensions.Logging;
using NTP.Application.Registrar;
namespace NTP.Infrastructure.Registrar;
/// <summary>
/// Fetches a registration picture from the legacy upload host (the mobile app stored it there, see <see cref="RegistrarOptions.AttachmentsBaseUrl"/>).
/// The page never talks to that host (its content security policy only allows own images); the API streams the file after the screen permission check.
/// </summary>
internal sealed class RegistrarFileGatewayService(ILogger<RegistrarFileGatewayService> logger) : IRegistrarFileGatewayService
{
private const long MaxBytes = 20L * 1024 * 1024;
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(30) };
public async Task<RegistrarFile?> FetchAsync(string url, string fileName, CancellationToken ct = default)
{
try
{
using var res = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct);
if (!res.IsSuccessStatusCode)
{
logger.LogWarning("Registrar picture {File}: the upload host answered {Status}", fileName, (int)res.StatusCode);
return null;
}
if (res.Content.Headers.ContentLength is > MaxBytes) return null;
var bytes = await res.Content.ReadAsByteArrayAsync(ct);
return bytes.Length > MaxBytes ? null : new RegistrarFile(bytes, ContentType(res.Content.Headers.ContentType?.MediaType, fileName), fileName);
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException && !ct.IsCancellationRequested)
{
logger.LogWarning("Registrar picture {File}: the upload host is not reachable ({Reason})", fileName, ex.GetType().Name);
return null;
}
}
/// <summary>The host's type when it is a picture or a PDF, else from the extension (the old host answers some files as text/html).</summary>
internal static string ContentType(string? served, string fileName)
{
if (served is not null && (served.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || served.Equals("application/pdf", StringComparison.OrdinalIgnoreCase)))
return served;
return Path.GetExtension(fileName).ToLowerInvariant() switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".pdf" => "application/pdf",
_ => "application/octet-stream",
};
}
}

View File

@ -0,0 +1,100 @@
using NTP.Application.Abstractions;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Grains.Communication;
using NTP.Application.Grains.Permits;
using NTP.Application.Grains.Reports;
namespace NTP.Tests;
public class CommunicationServiceTests
{
private sealed class FakeUnit : IUnitOfWork
{
public Task BeginAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task CommitAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task RollbackAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task<T> ExecuteInTransactionAsync<T>(Func<CancellationToken, Task<T>> work, CancellationToken ct = default) => work(ct);
}
private sealed class FakeUser : ICurrentUser
{
public bool IsAuthenticated => true; public long Id => 1; public string UserId => "GTO1"; public string Name => "t"; public string RoleCode => "GTO"; public string RoleName => "GTO";
public string Domain => "ASEZA"; public long? LocationId => null; public string LocationName => ""; public long? StkId => null; public long? CompId => null; public long? CompanyId => null;
public string CompanyName => ""; public string CompanyCode => ""; public string EmpNo => ""; public string Lang => "AR"; public bool IsStaff => false;
public bool IsInRole(string roleCode) => true; public bool IsInAnyRole(params string[] roleCodes) => true;
}
private sealed class FakePermissions(params string[] keys) : IPermissionService
{
public Task<PermissionsDto> GetForCurrentUserAsync(CancellationToken ct = default) => throw new NotSupportedException();
public Task<bool> IsAllowedAsync(string resourceKey, CancellationToken ct = default) => Task.FromResult(keys.Contains(resourceKey));
}
private sealed class FakeSettings : ICommunicationSettingsService { public CommunicationOptions Value { get; } = new() { AutoPostponeMinutes = 30 }; }
private sealed class FakeNotifications : IMobileNotificationGatewayService
{
public readonly List<(string Template, IReadOnlyDictionary<string, object?> Payload)> Sent = [];
public Task SendAsync(string template, IReadOnlyDictionary<string, object?> payload, CancellationToken ct = default) { Sent.Add((template, payload)); return Task.CompletedTask; }
}
private sealed class FakeExcel : IReportExcelService
{
public byte[] Build(ReportTable table, string printedBy, DateTime printedAt, bool arabic) => [1];
public List<string[]> ReadFirstSheet(Stream stream) => [];
}
private sealed class FakeRepo : ICommunicationRepository
{
public List<(long PermitId, string Tn)> Unanswered = [];
public List<long> Blocked = [];
public Task<PagedResult<CommunicationRow>> SearchAsync(CommunicationQuery query, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException();
public Task<IReadOnlyList<CargoOption>> GetCargoTypesAsync(CancellationToken ct = default) => Task.FromResult<IReadOnlyList<CargoOption>>([]);
public Task<IReadOnlyList<(long PermitId, string Tn)>> GetUnansweredAsync(CancellationToken ct = default) => Task.FromResult<IReadOnlyList<(long, string)>>(Unanswered);
public Task BlockAsync(IReadOnlyList<long> permitIds, string userId, CancellationToken ct = default) { Blocked.AddRange(permitIds); return Task.CompletedTask; }
}
private static (CommunicationService svc, FakeRepo repo, FakeNotifications push) Make(params string[] keys)
{
var repo = new FakeRepo(); var push = new FakeNotifications();
return (new CommunicationService(repo, new FakeUnit(), push, new FakeExcel(), new FakePermissions(keys), new FakeSettings(), new FakeUser()), repo, push);
}
[Fact]
public void Answers_are_read_from_status_and_blacklist()
{
var (svc, _, _) = Make();
var closed = svc.Item(new CommunicationRow { StatusCode = "CLOSE" });
Assert.Equal("CLOSE", closed.Answer); Assert.Equal("تم الإجابة - موافق", closed.Notes); Assert.Null(closed.RemainingMinutes);
var postponed = svc.Item(new CommunicationRow { StatusCode = "PENDING", BlackListId = 5, ExpiryDate = "20/11/2026" });
Assert.Equal("DELETED", postponed.Answer); Assert.Equal("تم الإجابة - تأجيل ، سيتم فك التأجيل بتاريخ 20/11/2026", postponed.Notes);
var waiting = svc.Item(new CommunicationRow { StatusCode = "PENDING", LogDuration = 12 });
Assert.Equal("PENDING", waiting.Answer); Assert.Equal("لم يتم الرد", waiting.Notes); Assert.Equal(18, waiting.RemainingMinutes);
Assert.Equal(0, svc.Item(new CommunicationRow { StatusCode = "PENDING", LogDuration = 99 }).RemainingMinutes);
}
[Fact]
public async Task Blacklist_blocks_the_permits_once_and_tells_every_truck_owner()
{
var (svc, repo, push) = Make(PermissionKeys.CommunicationBlacklist);
repo.Unanswered = [(1, "T1"), (1, "T1"), (2, "T2")];
var r = await svc.AddToBlacklistAsync(default);
Assert.Equal(3, r.Count);
Assert.Equal("تم ايقاف خاصية التثبيت والتأجيل عن ( 3 ) ارسالية", r.Message);
Assert.Equal([1L, 2L], repo.Blocked);
var (template, payload) = Assert.Single(push.Sent);
Assert.Equal(NotificationRules.BlockedDistributedOwners, template);
Assert.Equal(3, NotificationRules.Entries(payload).Count);
}
[Fact]
public async Task Nothing_to_block_is_a_quiet_zero_and_the_key_is_required()
{
var (svc, repo, push) = Make(PermissionKeys.CommunicationBlacklist);
Assert.Equal(0, (await svc.AddToBlacklistAsync(default)).Count);
Assert.Empty(repo.Blocked); Assert.Empty(push.Sent);
await Assert.ThrowsAsync<ForbiddenException>(() => Make().svc.AddToBlacklistAsync(default));
await Assert.ThrowsAsync<ForbiddenException>(() => Make(PermissionKeys.Communication).svc.ExportAsync(new CommunicationQuery(null, null, null, null, null, null, null, null), default));
}
}

View File

@ -104,10 +104,11 @@ public class JobScheduleRulesTests
} }
[Fact] [Fact]
public void The_catalog_has_the_three_legacy_jobs_with_unique_keys() public void The_catalog_has_the_legacy_jobs_with_unique_keys()
{ {
Assert.Equal(3, JobCatalog.All.Count); Assert.Equal(6, JobCatalog.All.Count);
Assert.Equal(JobCatalog.All.Count, JobCatalog.All.Select(j => j.Key).Distinct().Count()); Assert.Equal(JobCatalog.All.Count, JobCatalog.All.Select(j => j.Key).Distinct().Count());
Assert.NotNull(JobCatalog.Find("CLOSE-OLD-PERMITS")); Assert.NotNull(JobCatalog.Find("CLOSE-OLD-PERMITS"));
foreach (var key in new[] { "refinery-oil-sync", "refinery-daily-exchange-report", "josilos-integration" }) Assert.NotNull(JobCatalog.Find(key));
} }
} }

View File

@ -49,7 +49,7 @@ public class NotificationDispatcherTests
{ {
private sealed class FakeRepo : INotificationRepository private sealed class FakeRepo : INotificationRepository
{ {
public Dictionary<(string Role, string? Mobile, string? Login, string? Part), long[]> Users = new(); public Dictionary<(string? Role, string? Mobile, string? Login, string? Part), long[]> Users = new();
public Dictionary<long, DeviceRow[]> Devices = new(); public Dictionary<long, DeviceRow[]> Devices = new();
public string Phone = "0791234567"; public string Phone = "0791234567";
public long? Scac = 45; public long? Scac = 45;
@ -62,7 +62,7 @@ public class NotificationDispatcherTests
return Task.FromResult<NotificationTemplateRow?>(new NotificationTemplateRow { Id = 7, Title = "عنوان", Message = type == NotificationRules.SmsWithoutApp ? "الشاحنة VAR1" : "VAR1 / VAR2 / VAR3 / VAR4 / VAR5" }); return Task.FromResult<NotificationTemplateRow?>(new NotificationTemplateRow { Id = 7, Title = "عنوان", Message = type == NotificationRules.SmsWithoutApp ? "الشاحنة VAR1" : "VAR1 / VAR2 / VAR3 / VAR4 / VAR5" });
} }
public Task<IReadOnlyList<long>> FindUserIdsAsync(string roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default) => public Task<IReadOnlyList<long>> FindUserIdsAsync(string? roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<long>>(Users.GetValueOrDefault((roleCode, mobile, login, loginContains), [])); Task.FromResult<IReadOnlyList<long>>(Users.GetValueOrDefault((roleCode, mobile, login, loginContains), []));
public Task<IReadOnlyList<DeviceRow>> GetActiveDevicesAsync(long userId, CancellationToken ct = default) => public Task<IReadOnlyList<DeviceRow>> GetActiveDevicesAsync(long userId, CancellationToken ct = default) =>
@ -72,6 +72,7 @@ public class NotificationDispatcherTests
Task.FromResult<TruckContactRow?>(new TruckContactRow { Phone = Phone, Scac = Scac }); Task.FromResult<TruckContactRow?>(new TruckContactRow { Phone = Phone, Scac = Scac });
public Task<string?> GetCompanyDispatcherLoginAsync(long scac, CancellationToken ct = default) => Task.FromResult(DispatcherLogin); public Task<string?> GetCompanyDispatcherLoginAsync(long scac, CancellationToken ct = default) => Task.FromResult(DispatcherLogin);
public Task InsertPushLogAsync(string userId, string deviceId, string status, string request, string? response, string os, long templateId, CancellationToken ct = default) => Task.CompletedTask;
public Task InsertSmsLogAsync(string userLogin, string mobile, string status, string request, string? response, string provider, string serviceType, CancellationToken ct = default) => Task.CompletedTask; public Task InsertSmsLogAsync(string userLogin, string mobile, string status, string request, string? response, string provider, string serviceType, CancellationToken ct = default) => Task.CompletedTask;
} }
@ -91,7 +92,7 @@ public class NotificationDispatcherTests
{ {
public GrainsPermitsOptions Value { get; } = new() public GrainsPermitsOptions Value { get; } = new()
{ {
Notifications = new NotificationOptions { Enabled = true, PushUrl = "x", SendSmsToOwnersWithoutApp = sms, AppLink = "http://link" } Notifications = new NotificationOptions { Enabled = true, OneSignal = new OneSignalOptions { AppId = "app", ApiKey = "key" }, SendSmsToOwnersWithoutApp = sms, AppLink = "http://link" }
}; };
} }
@ -156,6 +157,31 @@ public class NotificationDispatcherTests
Assert.Empty(sms.Sent); Assert.Empty(sms.Sent);
} }
[Fact]
public async Task Registration_result_goes_to_the_user_who_registered_it_by_login_whatever_the_role()
{
var (d, repo, push, _) = Make(smsFlag: false);
repo.Users[(null, null, "COMP1", null)] = [31];
repo.Devices[31] = [new DeviceRow { FcmToken = "tok-r", Os = "ANDROID" }];
var payload = new Dictionary<string, object?> { ["LOGIN"] = "COMP1", ["REGISTRATION_TYPE"] = "شاحنة", ["REGISTRATION_NUMBER_TYPE"] = "12345", ["REASON"] = "سبب" };
await d.RunAsync(NotificationRules.RegistrationRevoke, payload, CancellationToken.None);
var m = Assert.Single(push.Sent);
Assert.Equal("شاحنة / 12345 / سبب / VAR4 / VAR5", m.Message); // VAR1 type, VAR2 number, VAR3 reason
Assert.Equal(31, m.UserId);
Assert.Equal("عنوان", m.Title);
}
[Fact]
public async Task Registration_result_without_a_login_or_a_user_sends_nothing()
{
var (d, _, push, _) = Make(smsFlag: false);
await d.RunAsync(NotificationRules.RegistrationApprove, new Dictionary<string, object?> { ["LOGIN"] = "" }, CancellationToken.None);
await d.RunAsync(NotificationRules.RegistrationApprove, new Dictionary<string, object?> { ["LOGIN"] = "NOBODY" }, CancellationToken.None);
Assert.Empty(push.Sent);
}
[Fact] [Fact]
public async Task Company_distribution_goes_to_the_dispatchers_whose_login_contains_the_company_code() public async Task Company_distribution_goes_to_the_dispatchers_whose_login_contains_the_company_code()
{ {

View File

@ -0,0 +1,52 @@
using System.Text.Json;
using NTP.Application.Grains.Permits;
namespace NTP.Tests;
public class OneSignalPushTests
{
private static readonly OneSignalOptions Options = new() { AppId = "app-1", ApiKey = "secret", AndroidChannelId = "chan-1" };
[Fact]
public void Android_body_has_the_channel_and_the_template_id()
{
using var doc = JsonDocument.Parse(NotificationRules.OneSignalBody(Options, "player-1", " عنوان ", " نص ", "ANDROID", 7));
var r = doc.RootElement;
Assert.Equal("app-1", r.GetProperty("app_id").GetString());
Assert.Equal("player-1", r.GetProperty("include_player_ids")[0].GetString());
Assert.Equal("chan-1", r.GetProperty("android_channel_id").GetString());
Assert.Equal("عنوان", r.GetProperty("headings").GetProperty("en").GetString()); // trimmed, real Arabic (not \u escapes)
Assert.Equal("نص", r.GetProperty("contents").GetProperty("en").GetString());
Assert.Equal("7", r.GetProperty("data").GetProperty("MSG_TEMPLATE_ID").GetString());
Assert.False(r.TryGetProperty("isIos", out _));
Assert.DoesNotContain("secret", r.GetRawText()); // the API key is never in the body
}
[Theory]
[InlineData("IOS")]
[InlineData("darwin")]
public void Every_other_os_is_sent_as_ios_with_the_app_sound(string os)
{
using var doc = JsonDocument.Parse(NotificationRules.OneSignalBody(Options, "p", "t", "m", os, 1));
Assert.True(doc.RootElement.GetProperty("isIos").GetBoolean());
Assert.Equal("nafith_notification_sound.caf", doc.RootElement.GetProperty("ios_sound").GetString());
Assert.False(doc.RootElement.TryGetProperty("android_channel_id", out _));
}
[Theory]
[InlineData("{\"id\":\"abc\",\"recipients\":1}", true)]
[InlineData("{\"errors\":[\"All included players are not subscribed\"]}", false)]
[InlineData("{\"id\":\"\",\"errors\":[\"x\"]}", false)]
[InlineData("", false)]
[InlineData("<html>bad gateway</html>", false)]
public void Answer_with_an_errors_key_or_not_json_is_a_failure(string answer, bool ok) =>
Assert.Equal(ok, NotificationRules.OneSignalSucceeded(answer));
[Fact]
public void Push_needs_both_app_id_and_api_key()
{
Assert.True(Options.IsConfigured);
Assert.False(new OneSignalOptions { AppId = "a" }.IsConfigured);
Assert.False(new OneSignalOptions { ApiKey = "k" }.IsConfigured);
}
}

View File

@ -0,0 +1,453 @@
using FluentValidation;
using NTP.Application.Abstractions;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Grains.Reports;
using NTP.Application.Receipts;
namespace NTP.Tests.Receipts;
public class ReceiptRulesTests
{
[Theory]
[InlineData(327, "CRG", "IMPT", "10184", 1L, 1L, 1)] // double move, import, supply agent
[InlineData(327, "CRG", "FSEZ", "555", 1L, 1L, 2)] // double move, import, other agent
[InlineData(327, "", "EXPT", "555", 1L, 1L, 3)] // single unloading
[InlineData(327, "", "IMPT", "555", 1L, 1L, 4)] // single loading, not supply
[InlineData(327, "", "IMPT", "10184", 86L, 20L, 5)] // facilities, supply
[InlineData(327, "", "IMPT", "555", 86L, 20L, 6)] // facilities, not supply
[InlineData(327, "", "IMPT", "10184", 1L, 1L, 7)] // single loading, supply
[InlineData(366, "CRG", "IMPT", "0", 1L, 1L, 10)]
[InlineData(366, "", "IMPT", "0", 1L, 1L, 9)]
public void Receipt_type_follows_the_legacy_decision_order(long scac, string fm, string inbound, string agent, long origin, long dest, int expected) =>
Assert.Equal(expected, ReceiptRules.TypeOf(scac, fm, inbound, agent, origin, dest));
[Fact]
public void Unknown_company_has_no_type() => Assert.Null(ReceiptRules.TypeOf(999, "", "IMPT", "0", 1, 1));
[Fact]
public void Status_rules()
{
Assert.True(ReceiptRules.CanConfirm("NOT_RECEIVED"));
Assert.False(ReceiptRules.CanConfirm("RECEIVED"));
Assert.True(ReceiptRules.CanPay("UNPAID"));
Assert.True(ReceiptRules.CanUpdate("RECEIVED") && ReceiptRules.CanUpdate("UNPAID"));
Assert.False(ReceiptRules.CanUpdate("AUDITED"));
Assert.True(ReceiptRules.CanPrint("AUDITED") && ReceiptRules.CanPrint("PAID"));
Assert.False(ReceiptRules.CanPrint("RVKD"));
Assert.True(ReceiptRules.CanRevokeAudited("AUDITED"));
Assert.True(ReceiptRules.CanDecideRevoke("PENDING_RVKD"));
Assert.Equal("RECEIVED", ReceiptRules.StatusForNew(0));
Assert.Equal("UNPAID", ReceiptRules.StatusForNew(1));
Assert.True(ReceiptRules.IsDoubleMove(1) && ReceiptRules.IsDoubleMove(2) && ReceiptRules.IsDoubleMove(10));
Assert.False(ReceiptRules.IsDoubleMove(3));
}
[Fact]
public void Log_json_keeps_the_translated_status()
{
var (o, n) = ReceiptRules.StatusLog("NOT_RECEIVED", "RECEIVED");
Assert.Equal("{\"STATUSCODE\":\"غير مستلم\"}", o);
Assert.Equal("{\"STATUSCODE\":\"تم الاستلام\"}", n);
Assert.Equal("{\"STATUSCODE\":\"تم الاستلام\",\"NOTES\":\"\"}", ReceiptRules.CreateLog("RECEIVED").New);
}
}
public class ReceiptAuditTests
{
private static AuditLookups Lookups() => new()
{
CargoCodeByName = new Dictionary<string, string> { ["بضائع عامة"] = "CRG", ["تموين"] = "FUEL" },
OperationCodeByCaption = new Dictionary<string, string> { ["استيراد"] = "IMPT", ["تصدير"] = "EXPT" },
LocationIdByShortName = new Dictionary<string, long> { ["AQ"] = 1, ["GATE"] = 20 },
Types = [new ReceiptTypeRow { Id = 3, Fees = 6, Scac = 327 }, new ReceiptTypeRow { Id = 7, Fees = 0, Scac = 327 }],
};
private static AuditFileRow File_() => new()
{
Scac = "327", Nnpn = "9801", InboundTypeCode = "تصدير", ShipmentMode = "بضائع عامة", PermitStatus = "مكتمل", Pn = "1001", Tn = "123", Trn = "456",
OriginAddressId = "AQ", DestinationAddressId = "GATE", CaCode = "555",
};
private static ReceiptRow Receipt() => new()
{
Id = 1, ReceiptNo = 202000001, Pn = 1001, Scac = 327, Tn = "123", Trn = "456", Nnpn = "9801", ShipmentMode = "CRG", InboundTypeCode = "EXPT", OriginAddressId = 1,
DestinationAddressId = 20, CaCode = 555, Fees = 6, ReceiptType = 3, StatusCode = "RECEIVED",
};
[Fact]
public void A_receipt_equal_to_the_file_has_no_remarks() => Assert.Equal(string.Empty, ReceiptAudit.ValidRecordInfo(File_(), Receipt(), Lookups()));
[Fact]
public void Differences_are_listed_in_arabic()
{
var f = File_();
f.Tn = "999";
var r = Receipt();
r.Fees = 10;
var text = ReceiptAudit.ValidRecordInfo(f, r, Lookups());
Assert.Contains("رقم الشاحنة غير مطابق", text);
Assert.Contains("القيمة المالية غير متساوية", text);
Assert.DoesNotContain("رقم المقطورة", text);
}
[Fact]
public void A_cargo_type_that_is_not_in_the_system_stops_the_fee_check()
{
var f = File_();
f.ShipmentMode = "غير معروف";
var r = Receipt();
r.Fees = 99;
var text = ReceiptAudit.ValidRecordInfo(f, r, Lookups());
Assert.Contains("نمط الحركة الاولى غير موجود", text);
Assert.DoesNotContain("القيمة المالية", text);
}
[Fact]
public void A_cancelled_permit_with_an_employee_mistake_should_have_no_receipt()
{
var f = File_();
f.PermitStatus = ReceiptAudit.Cancelled;
f.IsEmployeeMistake = ReceiptAudit.Yes;
Assert.Contains("ملغي بسبب خطأ موظف", ReceiptAudit.ValidRecordInfo(f, Receipt(), Lookups()));
}
[Fact]
public void Compare_classifies_missing_single_duplicate_and_orphan_receipts()
{
var file = new List<AuditFileRow>
{
File_(), // 1001: one matching receipt
new() { Pn = "2002", PermitStatus = "مكتمل", Scac = "327", ShipmentMode = "بضائع عامة" }, // 2002: no receipt
new() { Pn = "3003", PermitStatus = "مكتمل" }, // 3003: two receipts
new() { Pn = "4004", PermitStatus = "مرفوض" }, // rejected permit: skipped
};
var dup1 = Receipt(); dup1.Id = 11; dup1.Pn = 3003;
var dup2 = Receipt(); dup2.Id = 12; dup2.Pn = 3003;
var orphan = Receipt(); orphan.Id = 13; orphan.Pn = 9999; orphan.Credit = 1; orphan.ConfirmationBy = "USER1";
var receipts = new List<ReceiptRow> { Receipt(), dup1, dup2, orphan };
var (lines, audited, identical) = ReceiptAudit.Compare(file, receipts, Lookups(), "user1", ReceiptRules.StatusCaption);
Assert.Equal(1, identical.Count); // only 1001 is identical
Assert.Equal(1L, identical[0]);
Assert.Contains(audited, a => a.Id == 1 && a.Result == "يوجد سند قبض" && a.Remarks == "");
Assert.Contains(audited, a => a.Id == 11 && a.Result == "سند قبض مكرر");
Assert.Contains(audited, a => a.Id == 12 && a.Result == "سند قبض مكرر");
Assert.Contains(audited, a => a.Id == 13 && a.Result == "لا يوجد تصريح للمطالبة المالية");
Assert.Contains(lines, l => l.Pn == "2002" && l.Result == "لا يوجد وصل");
Assert.DoesNotContain(lines, l => l.Pn == "4004");
Assert.Equal(1 + 1 + 1 + 2 + 1, lines.Count); // header + 1001 + 2002 + 2 duplicates + orphan
}
[Fact]
public void A_receipt_confirmed_by_another_user_is_not_an_orphan_of_this_audit()
{
var orphan = Receipt(); orphan.Id = 13; orphan.Pn = 9999; orphan.ConfirmationBy = "OTHER";
var (_, audited, _) = ReceiptAudit.Compare([File_()], [Receipt(), orphan], Lookups(), "user1", ReceiptRules.StatusCaption);
Assert.DoesNotContain(audited, a => a.Id == 13);
}
}
public class ReceiptServiceTests
{
private sealed class FakeUnit : IUnitOfWork
{
public Task BeginAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task CommitAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task RollbackAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task<T> ExecuteInTransactionAsync<T>(Func<CancellationToken, Task<T>> work, CancellationToken ct = default) => work(ct);
}
private sealed class FakeUser(string role) : ICurrentUser
{
public bool IsAuthenticated => true;
public long Id => 5;
public string UserId => "TS1";
public string Name => "t";
public string RoleCode => role;
public string RoleName => role;
public string Domain => "ASEZA";
public long? LocationId => null;
public string LocationName => "";
public long? StkId => null;
public long? CompId => null;
public long? CompanyId => null;
public string CompanyName => "";
public string CompanyCode => "";
public string EmpNo => "";
public string Lang => "AR";
public bool IsStaff => false;
public bool IsInRole(string roleCode) => string.Equals(role, roleCode, StringComparison.OrdinalIgnoreCase);
public bool IsInAnyRole(params string[] roleCodes) => roleCodes.Any(IsInRole);
}
private sealed class FakePermissions(params string[] keys) : IPermissionService
{
public Task<PermissionsDto> GetForCurrentUserAsync(CancellationToken ct = default) => throw new NotSupportedException();
public Task<bool> IsAllowedAsync(string resourceKey, CancellationToken ct = default) => Task.FromResult(keys.Contains(resourceKey));
}
private sealed class FakeExcel : IReportExcelService
{
public List<string[]> Sheet = [];
public ReportTable? Last;
public byte[] Build(ReportTable table, string printedBy, DateTime printedAt, bool arabic) { Last = table; return [1]; }
public List<string[]> ReadFirstSheet(Stream stream) => Sheet;
}
private sealed class FakeRepo : IReceiptRepository
{
public ReceiptRow? Row;
public List<ReceiptRow> AuditRows = [];
public readonly List<string> Writes = [];
public bool Stale;
public bool UserExists = true;
public bool PermitOk = true;
public Task<PagedResult<ReceiptRow>> SearchAsync(ReceiptQuery query, PageRequest page, CancellationToken ct = default) =>
Task.FromResult(new PagedResult<ReceiptRow>(Row is null ? [] : [Row], 1, 16, Row is null ? 0 : 1));
public Task<ReceiptRow?> GetAsync(long id, CancellationToken ct = default) => Task.FromResult(Row);
public Task<PagedResult<ReceiptLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct = default) => throw new NotSupportedException();
public Task<IReadOnlyList<ReceiptTypeRow>> GetTypesAsync(long? scac, long? exceptId, CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<ReceiptTypeRow>>([new ReceiptTypeRow { Id = 3, Fees = 6, Scac = 327 }]);
public Task<ReceiptTypeRow?> GetTypeAsync(long id, CancellationToken ct = default) =>
Task.FromResult<ReceiptTypeRow?>(id == 3 ? new ReceiptTypeRow { Id = 3, Fees = 6, Scac = 327 } : id == 10 ? new ReceiptTypeRow { Id = 10, Fees = 15, Scac = 366 } : null);
public Task<IReadOnlyList<NamedRow>> GetRejectReasonsAsync(CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<NamedRow>>([new NamedRow { Code = "1", Name = "خطا في رقم التصريح" }]);
public Task<IReadOnlyList<NamedRow>> GetCargoTypesAsync(CancellationToken ct = default) => Task.FromResult<IReadOnlyList<NamedRow>>([]);
public Task<bool> PermitMatchesTypeAsync(long receiptType, long pn, CancellationToken ct = default) => Task.FromResult(PermitOk);
public Task<long> InsertAsync(CreateReceiptRequest request, decimal fees, string status, string userLogin, CancellationToken ct = default)
{ Writes.Add($"insert:{status}:{fees}:{userLogin}"); return Task.FromResult(77L); }
public Task<long> InsertPaidCopyAsync(long sourceId, CancellationToken ct = default) { Writes.Add($"copy:{sourceId}"); return Task.FromResult(78L); }
public Task<bool> ConfirmAsync(long id, string userLogin, CancellationToken ct = default) { Writes.Add("confirm"); return Task.FromResult(!Stale); }
public Task<bool> UpdateAsync(long id, UpdateReceiptRequest request, string userLogin, CancellationToken ct = default) { Writes.Add("update"); return Task.FromResult(!Stale); }
public Task<bool> PayAsync(long id, CancellationToken ct = default) { Writes.Add("pay"); return Task.FromResult(!Stale); }
public Task<bool> RequestRevokeAsync(long id, long reason, string? note, CancellationToken ct = default) { Writes.Add($"pending:{reason}:{note}"); return Task.FromResult(!Stale); }
public Task<bool> RevokeAsync(long id, string fromStatus, long? reason, string? note, string userLogin, CancellationToken ct = default)
{ Writes.Add($"revoke:{fromStatus}:{reason}"); return Task.FromResult(!Stale); }
public Task<bool> RejectRevokeAsync(long id, CancellationToken ct = default) { Writes.Add("rejectRevoke"); return Task.FromResult(!Stale); }
public Task AddLogAsync(long receiptId, string method, string oldData, string newData, long userId, string? ip, string? fileName, CancellationToken ct = default)
{ Writes.Add($"log:{receiptId}:{method}:{newData}"); return Task.CompletedTask; }
public Task<ReceiptAutoFill?> GetGnPermitAsync(string tn, CancellationToken ct = default) => Task.FromResult<ReceiptAutoFill?>(null);
public Task<ReceiptAutoFill?> GetDriverAsync(string nnpn, CancellationToken ct = default) => Task.FromResult<ReceiptAutoFill?>(null);
public Task<bool> UserExistsAsync(string login, CancellationToken ct = default) => Task.FromResult(UserExists);
public Task<AuditLookups> GetAuditLookupsAsync(CancellationToken ct = default) => Task.FromResult(new AuditLookups
{
CargoCodeByName = new Dictionary<string, string> { ["بضائع عامة"] = "CRG" },
OperationCodeByCaption = new Dictionary<string, string> { ["تصدير"] = "EXPT" },
LocationIdByShortName = new Dictionary<string, long> { ["AQ"] = 1, ["GATE"] = 20 },
Types = [new ReceiptTypeRow { Id = 3, Fees = 6, Scac = 327 }],
});
public Task<IReadOnlyList<ReceiptRow>> GetForAuditAsync(IReadOnlyList<string> statuses, AuditFilter filter, CancellationToken ct = default)
{ Writes.Add("audit:" + string.Join('+', statuses)); return Task.FromResult<IReadOnlyList<ReceiptRow>>(AuditRows); }
public Task SetStatusAsync(IReadOnlyList<long> ids, string status, CancellationToken ct = default) { Writes.Add($"set:{string.Join(',', ids)}:{status}"); return Task.CompletedTask; }
}
private static ReceiptRow Row(string status = "RECEIVED") => new()
{
Id = 5, ReceiptNo = 202000001, Pn = 1001, Scac = 327, StatusCode = status, Fees = 6, ReceiptType = 3, Credit = 0,
};
private static (ReceiptService svc, FakeRepo repo, FakeExcel excel) Make(string role, ReceiptRow? row, params string[] keys)
{
var repo = new FakeRepo { Row = row };
var excel = new FakeExcel();
return (new ReceiptService(repo, new FakeUnit(), new FakePermissions(keys), excel, new FakeUser(role)), repo, excel);
}
private static CreateReceiptRequest NewReceipt() => new()
{
Scac = 327, Credit = 0, ReceiptType = 3, Pn = "1001", ShipmentMode = "CRG", Tn = "1", Trn = "2", Nnpn = "3", Drvr = "d", Dln = "9", Dled = "2030-01-01",
};
[Fact]
public async Task Create_takes_the_fees_of_the_type_and_the_status_of_the_kind()
{
var (svc, repo, _) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsCreate);
var r = await svc.CreateAsync(NewReceipt(), default);
Assert.Equal(77, r.Id);
Assert.Equal(["insert:RECEIVED:6:TS1"], repo.Writes);
var claim = NewReceipt(); claim.Credit = 1;
await svc.CreateAsync(claim, default);
Assert.Equal("insert:UNPAID:6:TS1", repo.Writes[1]);
}
[Fact]
public async Task Create_needs_its_key_and_every_required_field()
{
await Assert.ThrowsAsync<ForbiddenException>(() => Make("X", null).svc.CreateAsync(NewReceipt(), default));
var (svc, repo, _) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsCreate);
var bad = NewReceipt(); bad.Drvr = " "; bad.Pn = "abc";
var ex = await Assert.ThrowsAsync<ValidationException>(() => svc.CreateAsync(bad, default));
Assert.Contains(ex.Errors, e => e.PropertyName == "drvr");
Assert.Contains(ex.Errors, e => e.PropertyName == "pn");
Assert.Empty(repo.Writes);
}
[Fact]
public async Task A_double_move_type_needs_the_first_cargo_type_and_unknown_types_are_refused()
{
var (svc, _, _) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsCreate);
var dm = NewReceipt(); dm.ReceiptType = 10; dm.Scac = 366;
var ex = await Assert.ThrowsAsync<ValidationException>(() => svc.CreateAsync(dm, default));
Assert.Contains(ex.Errors, e => e.PropertyName == "fmShipmentMode");
var unknown = NewReceipt(); unknown.ReceiptType = 99;
await Assert.ThrowsAsync<BusinessException>(() => svc.CreateAsync(unknown, default));
}
[Fact]
public async Task A_type_10_receipt_needs_a_permit_that_fits()
{
var (svc, repo, _) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsCreate);
repo.PermitOk = false;
var dm = NewReceipt(); dm.ReceiptType = 10; dm.FmShipmentMode = "CRG";
var ex = await Assert.ThrowsAsync<BusinessException>(() => svc.CreateAsync(dm, default));
Assert.Equal(ReceiptErrors.DataCheck, ex.Code);
}
[Fact]
public async Task Confirm_logs_then_changes_a_not_received_receipt()
{
var (svc, repo, _) = Make("QUEUE_OP", Row("NOT_RECEIVED"), PermissionKeys.ReceiptsConfirm);
await svc.ConfirmAsync(5, "1.2.3.4", default);
Assert.Equal(["log:5:CONFIRM:{\"STATUSCODE\":\"تم الاستلام\"}", "confirm"], repo.Writes);
await Assert.ThrowsAsync<ForbiddenException>(() => Make("QUEUE_OP", Row("RECEIVED"), PermissionKeys.ReceiptsConfirm).svc.ConfirmAsync(5, null, default));
}
[Fact]
public async Task Paid_marks_the_claim_and_creates_a_cash_receipt_with_both_logs()
{
var (svc, repo, _) = Make("TENDER_SUP", Row("UNPAID"), PermissionKeys.ReceiptsPaid);
var r = await svc.PaidAsync(5, null, default);
Assert.Equal(78, r.Id);
Assert.Equal(["log:5:PAID:{\"STATUSCODE\":\"مسدد\"}", "pay", "copy:5", "log:78:CREATE:{\"STATUSCODE\":\"تم الاستلام\",\"NOTES\":\"\"}"], repo.Writes);
}
[Fact]
public async Task Queue_operator_asks_for_the_cancellation_and_tender_supervisor_cancels_at_once()
{
var req = new RevokeReceiptRequest(1, " خطأ ");
var (queue, qrepo, _) = Make("QUEUE_OP", Row(), PermissionKeys.ReceiptsRevokeRequest, PermissionKeys.ReceiptsRevoke);
await queue.RevokeAsync(5, req, null, default);
Assert.Contains("pending:1:خطأ", qrepo.Writes);
var (sup, srepo, _) = Make("TENDER_SUP", Row(), PermissionKeys.ReceiptsRevokeRequest, PermissionKeys.ReceiptsRevoke);
await sup.RevokeAsync(5, req, null, default);
Assert.Contains("revoke:RECEIVED:1", srepo.Writes);
}
[Fact]
public async Task Revoke_needs_a_known_reason_and_the_key_of_the_path()
{
var (svc, repo, _) = Make("TENDER_SUP", Row(), PermissionKeys.ReceiptsRevoke);
await Assert.ThrowsAsync<ValidationException>(() => svc.RevokeAsync(5, new RevokeReceiptRequest(null, null), null, default));
await Assert.ThrowsAsync<ValidationException>(() => svc.RevokeAsync(5, new RevokeReceiptRequest(42, null), null, default));
Assert.Empty(repo.Writes);
await Assert.ThrowsAsync<ForbiddenException>(() => Make("QUEUE_OP", Row(), PermissionKeys.ReceiptsRevoke).svc.RevokeAsync(5, new RevokeReceiptRequest(1, null), null, default));
}
[Fact]
public async Task An_audited_receipt_is_cancelled_by_the_roles_with_that_key_only()
{
var (svc, repo, _) = Make("SAP", Row("AUDITED"), PermissionKeys.ReceiptsRevokeAudited);
await svc.RevokeAsync(5, new RevokeReceiptRequest(1, null), null, default);
Assert.Contains("revoke:AUDITED:1", repo.Writes);
await Assert.ThrowsAsync<ForbiddenException>(() => Make("SU", Row("AUDITED"), PermissionKeys.ReceiptsRevokeAudited).svc.RevokeAsync(5, new RevokeReceiptRequest(1, null), null, default));
}
[Fact]
public async Task Accept_and_reject_decide_a_pending_cancellation()
{
var (svc, repo, _) = Make("TENDER_SUP", Row("PENDING_RVKD"), PermissionKeys.ReceiptsAcceptRevoke, PermissionKeys.ReceiptsRejectRevoke);
await svc.AcceptRevokeAsync(5, null, default);
await svc.RejectRevokeAsync(5, null, default);
Assert.Equal(["log:5:ACCEPT_REVOKE:{\"STATUSCODE\":\"ملغي\"}", "revoke:PENDING_RVKD:", "log:5:REJECT_REVOKE:{\"STATUSCODE\":\"تم الاستلام\"}", "rejectRevoke"], repo.Writes);
}
[Fact]
public async Task Print_refuses_zero_fees_and_logs_a_real_print()
{
var zero = Row(); zero.Fees = 0;
var ex = await Assert.ThrowsAsync<BusinessException>(() => Make("QUEUE_OP", zero, PermissionKeys.ReceiptsPrint).svc.PrintAsync(5, null, default));
Assert.Equal(ReceiptErrors.ZeroFees, ex.Code);
var (svc, repo, _) = Make("QUEUE_OP", Row(), PermissionKeys.ReceiptsPrint);
var p = await svc.PrintAsync(5, null, default);
Assert.Equal("تصريح واحد", p.Description);
Assert.True(p.ShowCargo);
Assert.Equal(["log:5:PRINT:{\"NOTES\":\"\"}"], repo.Writes);
}
[Fact]
public async Task Detail_flags_follow_status_key_and_the_request_rule()
{
var byRequest = Row(); byRequest.RequestId = 9;
var (svc, _, _) = Make("TENDER_SUP", byRequest, PermissionKeys.ReceiptsUpdate, PermissionKeys.ReceiptsRevoke, PermissionKeys.ReceiptsPrint);
var a = (await svc.GetAsync(5, default)).Actions;
Assert.True(a.Update);
Assert.True(a.Print);
Assert.False(a.Revoke); // a receipt made by a permit request cannot be cancelled here
Assert.False(a.Confirm);
}
[Fact]
public async Task Audit_checks_its_inputs()
{
var (svc, repo, _) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsAudit);
var empty = new AuditFilter(null, null, null, null, null);
await Assert.ThrowsAsync<BusinessException>(() => svc.AuditAsync(Stream.Null, "a.xlsx", empty, null, default));
await Assert.ThrowsAsync<BusinessException>(() => svc.AuditAsync(Stream.Null, "a.xlsx", new AuditFilter(null, new DateTime(2026, 1, 1), null, null, null), null, default));
await Assert.ThrowsAsync<BusinessException>(() => svc.AuditAsync(Stream.Null, "a.xlsx", new AuditFilter(null, new DateTime(2026, 2, 1), new DateTime(2026, 1, 1), null, null), null, default));
repo.UserExists = false;
await Assert.ThrowsAsync<BusinessException>(() => svc.AuditAsync(Stream.Null, "a.xlsx", new AuditFilter("ghost", null, null, null, null), null, default));
await Assert.ThrowsAsync<ForbiddenException>(() => Make("TENDER_SUP", null).svc.AuditAsync(Stream.Null, "a.xlsx", empty, null, default));
}
private static string[] FileRow() =>
["1", "327", "co", "9801", "drv", "تصدير", "بضائع عامة", "مكتمل", "1001", "123", "456", "AQ", "GATE", "2026-01-01", "", "555", "", "", ""];
[Fact]
public async Task Audit_moves_the_identical_receipts_on_and_logs_every_compared_one()
{
var (svc, repo, excel) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsAudit);
excel.Sheet = [["t"], ["t"], ["h"], FileRow()];
repo.AuditRows = [new ReceiptRow
{
Id = 5, ReceiptNo = 202000001, Pn = 1001, Scac = 327, Tn = "123", Trn = "456", Nnpn = "9801", ShipmentMode = "CRG", InboundTypeCode = "EXPT", OriginAddressId = 1,
DestinationAddressId = 20, CaCode = 555, Fees = 6, ReceiptType = 3, StatusCode = "RECEIVED",
}];
var r = await svc.AuditAsync(Stream.Null, "permits.xlsx", new AuditFilter("ts1", null, null, null, null), "10.0.0.1", default);
Assert.Equal("permits_result.xlsx", r.FileName);
Assert.Equal(1, r.Compared);
Assert.Equal(1, r.Advanced);
Assert.Equal("audit:NOT_RECEIVED+ALL+RECEIVED+AUDITED+UNPAID", repo.Writes[0]);
Assert.Contains(repo.Writes, w => w.StartsWith("log:5:AUDIT:") && w.Contains("يوجد سند قبض"));
Assert.Contains("set:5:AUDITED", repo.Writes);
Assert.Single(excel.Last!.Rows);
}
[Fact]
public async Task The_financial_audit_of_AM_completes_audited_receipts()
{
var (svc, repo, excel) = Make("AM", null, PermissionKeys.ReceiptsAudit);
excel.Sheet = [["t"], ["t"], ["h"], FileRow()];
repo.AuditRows = [new ReceiptRow { Id = 5, Pn = 1001, Scac = 327, Tn = "123", Trn = "456", Nnpn = "9801", ShipmentMode = "CRG", InboundTypeCode = "EXPT", OriginAddressId = 1, DestinationAddressId = 20, CaCode = 555, Fees = 6, ReceiptType = 3, StatusCode = "AUDITED" }];
await svc.AuditAsync(Stream.Null, "p.xlsx", new AuditFilter("x", null, null, null, null), null, default);
Assert.Equal("audit:AUDITED+COMPLETED", repo.Writes[0]);
Assert.Contains("set:5:COMPLETED", repo.Writes);
Assert.Contains(repo.Writes, w => w.StartsWith("log:5:FIN_AUDIT:"));
}
[Fact]
public async Task Audit_without_receipts_for_the_user_is_an_error()
{
var (svc, repo, excel) = Make("TENDER_SUP", null, PermissionKeys.ReceiptsAudit);
excel.Sheet = [["t"], ["t"], ["h"], FileRow()];
var ex = await Assert.ThrowsAsync<BusinessException>(() => svc.AuditAsync(Stream.Null, "p.xlsx", new AuditFilter("x", null, null, null, null), null, default));
Assert.Equal(ReceiptErrors.NoReceipts, ex.Code);
Assert.DoesNotContain(repo.Writes, w => w.StartsWith("set"));
}
}

View File

@ -0,0 +1,416 @@
using System.Text.Json;
using System.Xml.Linq;
using NTP.Application.Abstractions;
using NTP.Application.ExternalIntegration;
using NTP.Application.Refinery.Sync;
using NTP.Infrastructure.Integrations;
namespace NTP.Tests.Refinery;
public class JopetrolTripParserTests
{
private static XElement Node(string status = "2", string extra = "") => XElement.Parse($"""
<Table>
<NF55DOCO> 1234567 </NF55DOCO><NFTRDJ>121012</NFTRDJ><NFAN8>5001</NFAN8><NF55HEAD>12345</NF55HEAD><NF55TRAIL>6789</NF55TRAIL>
<NF55DRNID>9871234567</NF55DRNID><NF55STATUS>{status}</NF55STATUS><NFUSER>JDE</NFUSER><NFUPMJ>121013</NFUPMJ>
<NFLOAD>121012</NFLOAD><NFWGTR>39980</NFWGTR><NFBFWT>15000</NFBFWT><NFAFWT>54980</NFAFWT><NFTEMP>2550</NFTEMP><NFY55WQ>500</NFY55WQ>
<NFY55WFLAG>0</NFY55WFLAG>{extra}
</Table>
""");
[Theory]
[InlineData("121012", 2021, 1, 12)]
[InlineData("121365", 2021, 12, 31)]
[InlineData("120060", 2020, 2, 29)] // leap year
public void Jde_date_is_century_year_day_of_year(string text, int y, int m, int d) =>
Assert.Equal(new DateTime(y, m, d), JopetrolTripParser.JdeDate(text));
[Theory]
[InlineData("")]
[InlineData("12101")]
[InlineData("121400")]
[InlineData("abcdef")]
public void Bad_jde_dates_are_null(string text) => Assert.Null(JopetrolTripParser.JdeDate(text));
[Fact]
public void Values_are_converted_the_way_legacy_did()
{
var t = JopetrolTripParser.Parse(Node());
Assert.Equal("1234567", t.Pn);
Assert.Equal(new DateTime(2021, 1, 12), t.DispatchDate);
Assert.Equal(39.98m, t.NetLoadingWeight); // kg / 1000
Assert.Equal(15m, t.EmptyWeight);
Assert.Equal(25.5m, t.Temperature); // / 100
Assert.Equal(0.5m, t.WaterAmount);
Assert.Equal(1, t.WaterFlag); // NFY55WFLAG = 0: water that does not accompany the load
Assert.Equal(2, t.TripStatus);
Assert.Equal("0", t.MaterialNo); // missing optional tags
Assert.Null(t.SedimentAmount);
}
[Fact]
public void Water_flag_is_zero_when_the_tag_is_missing_or_not_zero()
{
Assert.Equal(0, JopetrolTripParser.Parse(XElement.Parse(Node().ToString().Replace("<NFY55WFLAG>0</NFY55WFLAG>", ""))).WaterFlag);
Assert.Equal(0, JopetrolTripParser.Parse(XElement.Parse(Node().ToString().Replace("<NFY55WFLAG>0</NFY55WFLAG>", "<NFY55WFLAG>1</NFY55WFLAG>"))).WaterFlag);
}
[Fact]
public void A_row_without_a_required_tag_is_refused()
{
var ex = Assert.Throws<FormatException>(() => JopetrolTripParser.Parse(XElement.Parse("<Table><NF55DOCO>1</NF55DOCO></Table>")));
Assert.Contains("NFTRDJ", ex.Message);
}
[Theory]
[InlineData(0, true, "NEW")]
[InlineData(1, true, "RESD")]
[InlineData(3, true, "LOADED")]
[InlineData(6, true, "DISCHARGED")]
[InlineData(0, false, "KEEP")] // an update does not move a trip to NEW / RESD by itself
[InlineData(1, false, "KEEP")]
[InlineData(4, false, "ARRIVE_LOCATION")]
[InlineData(5, false, "DISCHARGING")]
public void Status_code_follows_the_service_status(int status, bool insert, string expected) =>
Assert.Equal(expected, JopetrolTripParser.StatusCodeOf(status, "KEEP", insert));
}
public class JopetrolSoapTests
{
[Fact]
public void Query_answer_rows_are_the_children_of_NewDataSet()
{
const string xml = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><QueryOnTransByStatusResponse><QueryOnTransByStatusResult><NewDataSet xmlns=\"x\"><Table><NF55DOCO>1</NF55DOCO></Table><Table><NF55DOCO>2</NF55DOCO></Table></NewDataSet></QueryOnTransByStatusResult></QueryOnTransByStatusResponse></soap:Body></soap:Envelope>";
Assert.Equal(2, JopetrolSoap.ParseDataSetRows(xml).Count);
Assert.Empty(JopetrolSoap.ParseDataSetRows("<a><b/></a>"));
}
[Fact]
public void Update_answers_are_read_by_operation_name_or_any_result()
{
Assert.Equal("Status Updated successfully To -2", JopetrolSoap.ParseOperationResult("<r><UpdateStatusToMinus2Result>Status Updated successfully To -2</UpdateStatusToMinus2Result></r>", "UpdateStatusToMinus2"));
Assert.Equal("ok", JopetrolSoap.ParseOperationResult("<r><UpdateStatusTo1Result>ok</UpdateStatusTo1Result></r>", "UpdateStatusToMinus2")); // legacy read UpdateStatusTo1Result for both
Assert.Null(JopetrolSoap.ParseOperationResult("<r><x/></r>", "UpdateStatusTo1"));
}
[Fact]
public void Envelopes_escape_what_they_carry()
{
var e = JopetrolSoap.BuildUpdateStatusToMinus2("u", "p<&>", "12<3");
Assert.Contains("p&lt;&amp;&gt;", e);
Assert.Contains("12&lt;3", e);
Assert.Contains("<tran:StatusNo>4</tran:StatusNo>", JopetrolSoap.BuildQueryByStatus("u", "p", 4));
}
}
public class RefineryOilSyncServiceTests
{
private sealed class FakeUnit : IUnitOfWork
{
public Task BeginAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task CommitAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task RollbackAsync(CancellationToken ct = default) => Task.CompletedTask;
public Task<T> ExecuteInTransactionAsync<T>(Func<CancellationToken, Task<T>> work, CancellationToken ct = default) => work(ct);
}
private sealed class FakeMail : IMailService
{
public List<(string[] To, string Subject)> Sent = [];
public Task<bool> SendHtmlAsync(IReadOnlyList<string> to, string subject, string htmlBody, CancellationToken ct = default) { Sent.Add((to.ToArray(), subject)); return Task.FromResult(true); }
}
private sealed class FakeSettings(bool writeBack) : IRefineryJobSettingsService
{
public RefineryJobOptions Value { get; } = new() { JopetrolWriteBack = writeBack, CancelledTripRecipients = ["a@x.com"] };
}
private sealed class FakeGateway : IJopetrolTripsGateway
{
public bool IsReady { get; set; } = true;
public Dictionary<int, List<XElement>> Rows = [];
public string? To1Answer = "Status Updated successfully To 1";
public string? ToMinus2Answer = "Status Updated successfully To -2";
public List<string> Calls = [];
public Task<IReadOnlyList<XElement>> QueryOnTransByStatusAsync(int status, CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<XElement>>(Rows.TryGetValue(status, out var r) ? r : []);
public Task<string?> UpdateStatusTo1Async(string pn, CancellationToken ct = default) { Calls.Add("to1:" + pn); return Task.FromResult(To1Answer); }
public Task<string?> UpdateStatusToMinus2Async(string pn, CancellationToken ct = default) { Calls.Add("m2:" + pn); return Task.FromResult(ToMinus2Answer); }
}
private sealed class FakeRepo : IRefineryOilSyncRepository
{
public Dictionary<string, ExistingTrip> Trips = [];
public List<string> Writes = [];
public Task<ExistingTrip?> FindByPnAsync(string pn, CancellationToken ct = default) => Task.FromResult(Trips.GetValueOrDefault(pn));
public Task<bool> InsertAsync(JopetrolTripRecord t, string statusCode, string createdBy, CancellationToken ct = default)
{
Writes.Add($"insert:{t.Pn}:{statusCode}:{createdBy}");
Trips[t.Pn] = new ExistingTrip { Id = Trips.Count + 1, Pn = t.Pn, StatusCode = statusCode, TripStatus = t.TripStatus.ToString() };
return Task.FromResult(true);
}
public Task UpdateAsync(ExistingTrip old, JopetrolTripRecord t, string statusCode, int tripStatus, string updatedBy, CancellationToken ct = default)
{
Writes.Add($"update:{old.Pn}:{statusCode}:{tripStatus}");
old.StatusCode = statusCode; old.TripStatus = tripStatus.ToString();
return Task.CompletedTask;
}
}
private static XElement Node(string pn, int status) => XElement.Parse($"""
<Table><NF55DOCO>{pn}</NF55DOCO><NFTRDJ>121012</NFTRDJ><NFAN8>5</NFAN8><NF55HEAD>1</NF55HEAD><NF55TRAIL>2</NF55TRAIL><NF55DRNID>3</NF55DRNID>
<NF55STATUS>{status}</NF55STATUS><NFUSER>U</NFUSER><NFUPMJ>121013</NFUPMJ></Table>
""");
private static (RefineryOilSyncService Service, FakeRepo Repo, FakeGateway Gateway, FakeMail Mail) Make(bool writeBack = true)
{
var repo = new FakeRepo(); var gw = new FakeGateway(); var mail = new FakeMail();
return (new RefineryOilSyncService(gw, repo, new FakeUnit(), mail, new FakeSettings(writeBack)), repo, gw, mail);
}
[Fact]
public async Task Does_nothing_when_jopetrol_is_not_ready()
{
var (s, repo, gw, _) = Make();
gw.IsReady = false;
var r = await s.RunAsync(default);
Assert.Equal(0, r.Total);
Assert.Contains("جوبترول", r.Note);
Assert.Empty(repo.Writes);
}
[Fact]
public async Task New_trips_are_created_with_the_status_of_their_service_status()
{
var (s, repo, gw, _) = Make();
gw.Rows[3] = [Node("111", 3)];
gw.Rows[6] = [Node("222", 6)];
var r = await s.RunAsync(default);
Assert.Equal(2, r.Inserted);
Assert.Equal(["insert:111:LOADED:16186973", "insert:222:DISCHARGED:16186973"], repo.Writes);
}
[Fact]
public async Task A_trip_that_moved_on_is_updated_unless_it_is_in_the_payment_phase()
{
var (s, repo, gw, _) = Make();
repo.Trips["1"] = new ExistingTrip { Id = 1, Pn = "1", StatusCode = "LOADED", TripStatus = "3" };
repo.Trips["2"] = new ExistingTrip { Id = 2, Pn = "2", StatusCode = "EXCHANGED", TripStatus = "5" };
repo.Trips["3"] = new ExistingTrip { Id = 3, Pn = "3", StatusCode = "LOADED", TripStatus = "3" };
gw.Rows[4] = [Node("1", 4)];
gw.Rows[6] = [Node("2", 6)];
gw.Rows[3] = [Node("3", 3)]; // same status: nothing to do
var r = await s.RunAsync(default);
Assert.Equal(1, r.Updated);
Assert.Equal(["update:1:ARRIVE_LOCATION:4"], repo.Writes);
}
[Fact]
public async Task Status_0_is_released_at_jopetrol_and_then_here_only_when_jopetrol_confirms()
{
var (s, repo, gw, _) = Make();
repo.Trips["9"] = new ExistingTrip { Id = 9, Pn = "9", StatusCode = "NEW", TripStatus = "0" };
gw.Rows[0] = [Node("9", 0)];
var r = await s.RunAsync(default);
Assert.Equal(1, r.Released);
Assert.Equal(["update:9:RESD:1"], repo.Writes);
Assert.Equal(["to1:9"], gw.Calls);
var (s2, repo2, gw2, _) = Make();
repo2.Trips["9"] = new ExistingTrip { Id = 9, Pn = "9", StatusCode = "NEW", TripStatus = "0" };
gw2.Rows[0] = [Node("9", 0)];
gw2.To1Answer = "Error";
Assert.Equal(0, (await s2.RunAsync(default)).Released);
Assert.Empty(repo2.Writes);
}
[Fact]
public async Task Cancel_request_marks_the_trip_asks_jopetrol_and_mails_on_success()
{
var (s, repo, gw, mail) = Make();
repo.Trips["7"] = new ExistingTrip { Id = 7, Pn = "7", StatusCode = "RESD", TripStatus = "1" };
gw.Rows[-1] = [Node("7", -1)];
var r = await s.RunAsync(default);
Assert.Equal(1, r.Cancelled);
Assert.Equal(["update:7:RVKD:-1", "update:7:RVKD:-2"], repo.Writes);
Assert.Equal(["m2:7"], gw.Calls);
Assert.Contains("7", mail.Sent.Single().Subject);
Assert.Equal(["a@x.com"], mail.Sent.Single().To);
}
[Fact]
public async Task Without_write_back_nothing_is_changed_at_jopetrol_and_status_0_and_minus_1_are_left_alone()
{
var (s, repo, gw, mail) = Make(writeBack: false);
repo.Trips["7"] = new ExistingTrip { Id = 7, Pn = "7", StatusCode = "RESD", TripStatus = "1" };
repo.Trips["8"] = new ExistingTrip { Id = 8, Pn = "8", StatusCode = "NEW", TripStatus = "0" };
gw.Rows[-1] = [Node("7", -1)];
gw.Rows[0] = [Node("8", 0)];
await s.RunAsync(default);
Assert.Empty(gw.Calls);
Assert.Empty(repo.Writes);
Assert.Empty(mail.Sent);
}
[Fact]
public async Task A_cancel_request_for_an_unknown_trip_is_ignored_and_a_bad_row_is_counted_not_fatal()
{
var (s, repo, gw, _) = Make();
gw.Rows[-1] = [Node("404", -1)];
gw.Rows[5] = [XElement.Parse("<Table><NF55DOCO>1</NF55DOCO></Table>"), Node("5", 5)];
var r = await s.RunAsync(default);
Assert.Equal(1, r.Errors);
Assert.Equal(1, r.Inserted);
Assert.Equal(["insert:5:DISCHARGING:16186973"], repo.Writes);
Assert.Contains("NFTRDJ", r.Note);
}
}
public class RefineryDailyReportTests
{
[Fact]
public void Body_has_both_totals_in_dinars_the_title_and_the_year()
{
var html = RefineryDailyReportHtml.Build(1234.5m, 0m, new DateTime(2026, 11, 24), "https://x/en.png", "https://x/ar.png");
Assert.Contains("1,234.500 دينار", html);
Assert.Contains("0.000 دينار", html);
Assert.Contains("التقرير اليومي لعطاء الصرف", html);
Assert.Contains("Monday, November 23, 2026", html); // yesterday, as legacy now()-1
Assert.Contains("2026", html);
Assert.Contains("https://x/ar.png", html);
}
private sealed class Repo : IRefineryDailyReportRepository
{
public Task<(decimal First, decimal Second)> GetTotalsAsync(CancellationToken ct = default) => Task.FromResult((5m, 6m));
}
private sealed class Mail : IMailService
{
public string[] To = []; public string Subject = ""; public string Body = "";
public Task<bool> SendHtmlAsync(IReadOnlyList<string> to, string subject, string htmlBody, CancellationToken ct = default) { To = to.ToArray(); Subject = subject; Body = htmlBody; return Task.FromResult(true); }
}
private sealed class Settings : IRefineryJobSettingsService
{
public RefineryJobOptions Value { get; } = new() { DailyReportRecipients = ["fin@x.com", "ops@x.com"] };
}
[Fact]
public async Task Service_mails_the_report_to_the_configured_receivers()
{
var mail = new Mail();
Assert.True(await new RefineryDailyReportService(new Repo(), mail, new Settings()).SendAsync(default));
Assert.Equal("التقرير اليومي لعطاء الصرف", mail.Subject);
Assert.Equal(["fin@x.com", "ops@x.com"], mail.To);
Assert.Contains("5.000 دينار", mail.Body);
Assert.Contains("6.000 دينار", mail.Body);
}
}
public class JoSilosTests
{
private sealed class Settings(bool enabled) : IJoSilosSettingsService
{
public JoSilosOptions Value { get; } = new() { Enabled = enabled, SilosUrl = "http://old", AqabaSilosUrl = "http://new" };
}
private sealed class Repo : IJoSilosRepository
{
public List<JoSilosPermitRow> Old = [];
public List<AqabaSilosPermitRow> New = [];
public List<string> Log = [];
public Task<IReadOnlyList<JoSilosPermitRow>> GetPermitsForSilosAsync(int max, CancellationToken ct = default) => Task.FromResult<IReadOnlyList<JoSilosPermitRow>>(Old);
public Task<IReadOnlyList<AqabaSilosPermitRow>> GetPermitsForAqabaSilosAsync(int max, CancellationToken ct = default) => Task.FromResult<IReadOnlyList<AqabaSilosPermitRow>>(New);
public Task<long> AddQueueLogAsync(string type, string operationType, long permitId, string permitStatusCode, int currentLeg, long eventId, string queueData, CancellationToken ct = default)
{ Log.Add($"add:{type}:{permitId}:{permitStatusCode}"); return Task.FromResult(100L + Log.Count); }
public Task MarkProcessedAsync(long logId, string result, CancellationToken ct = default) { Log.Add($"ok:{logId}:{result}"); return Task.CompletedTask; }
public Task SetResultAsync(long logId, string result, CancellationToken ct = default) { Log.Add($"fail:{logId}:{result}"); return Task.CompletedTask; }
}
private sealed class Gateway(Func<string, string> answer) : IJoSilosGatewayService
{
public List<(string Url, string Json)> Posts = [];
public Task<string> PostJsonAsync(string url, string json, CancellationToken ct = default) { Posts.Add((url, json)); return Task.FromResult(answer(url)); }
}
[Fact]
public void Old_service_body_keeps_the_legacy_fields_and_escapes_text()
{
using var doc = JsonDocument.Parse(JoSilosPayloads.Silos(new JoSilosPermitRow
{
RequestNo = "P1", RequestDate = "2026-11-24", ToLocation = "عمّان \"الشمال\"", ItemCode = "10", ItemName = "قمح", FirstPlateNo = "12345", SecondPlateNo = "678",
DriverName = "سائق", DriverNatId = "9871234567", DriverLicenseNo = "0", DriverMobileNo = "0791234567", TrailerType = "تريلا", CarrierId = "55", CarrierName = "شركة", TimeStamp = "2026-11-24 10:00:00",
}));
var r = doc.RootElement;
Assert.Equal(" Aqaba", r.GetProperty("fromLocation").GetString());
Assert.Equal("عمّان \"الشمال\"", r.GetProperty("toLocation").GetString());
Assert.Equal("2026-11-24", r.GetProperty("versionDate").GetString());
Assert.True(r.GetProperty("isEnsured").GetBoolean());
Assert.Equal(JsonValueKind.Null, r.GetProperty("driverLicenseExpiryDate").ValueKind);
Assert.Equal("nafith", r.GetProperty("createdBy").GetString());
}
[Fact]
public void New_service_body_has_upper_case_keys_numbers_and_the_log_id_last()
{
var json = JoSilosPayloads.AqabaSilos(new AqabaSilosPermitRow { PermitId = 5, Pn = "T1", ReferenceNo = "R1", LocationId = 77 }, 123);
using var doc = JsonDocument.Parse(json);
var r = doc.RootElement;
Assert.Equal("AQABASILOS", r.GetProperty("TYPE").GetString());
Assert.Equal(5, r.GetProperty("PERMIT_ID").GetInt64());
Assert.Equal(10184, r.GetProperty("DESTINATION").GetInt32());
Assert.Equal("RESD", r.GetProperty("PERMIT_STATUS_CODE").GetString());
Assert.Equal(123, r.GetProperty("LOGID").GetInt64());
Assert.EndsWith("\"LOGID\":123}", json);
Assert.DoesNotContain("LOGID", JoSilosPayloads.AqabaSilos(new AqabaSilosPermitRow(), null));
}
[Fact]
public async Task Off_by_default_nothing_is_sent()
{
var repo = new Repo { Old = [new() { Id = 1 }] };
var gw = new Gateway(_ => "RECEIVED");
var r = await new JoSilosService(repo, gw, new Settings(false)).RunAsync(default);
Assert.Equal(0, r.Total);
Assert.Empty(gw.Posts);
Assert.Empty(repo.Log);
}
[Fact]
public async Task Each_service_has_its_own_success_answer_and_failures_stay_pending_with_the_answer()
{
gwCalls = 0;
var repo = new Repo
{
Old = [new() { Id = 1, RequestNo = "A" }, new() { Id = 2, RequestNo = "B" }],
New = [new() { PermitId = 3, Pn = "C" }, new() { PermitId = 4, Pn = "D" }],
};
var gw = new Gateway(url => url == "http://old" ? (gwCalls++ == 0 ? "RECEIVED" : "ERR") : (gwCalls++ == 2 ? "\"RECEIVED\"" : "boom"));
var r = await new JoSilosService(repo, gw, new Settings(true)).RunAsync(default);
Assert.Equal(1, r.SilosSent);
Assert.Equal(1, r.SilosFailed);
Assert.Equal(1, r.AqabaSent);
Assert.Equal(1, r.AqabaFailed);
Assert.Contains("ok:101:RECEIVED", repo.Log);
Assert.Contains(repo.Log, l => l.StartsWith("fail:") && l.EndsWith(":ERR"));
Assert.Contains(repo.Log, l => l.EndsWith(":\"RECEIVED\"") && l.StartsWith("ok:"));
Assert.Contains("add:JOSILOS:1:CLOSE", repo.Log);
Assert.Contains("add:AQABASILOS:3:RESD", repo.Log);
Assert.Contains("\"LOGID\":", gw.Posts[2].Json);
}
private static int gwCalls;
[Fact]
public async Task A_network_failure_on_one_permit_does_not_stop_the_others()
{
gwCalls = 0;
var repo = new Repo { Old = [new() { Id = 1, RequestNo = "A" }, new() { Id = 2, RequestNo = "B" }] };
var n = 0;
var gw = new Gateway(_ => ++n == 1 ? throw new HttpRequestException("down") : "RECEIVED");
var r = await new JoSilosService(repo, gw, new Settings(true)).RunAsync(default);
Assert.Equal(1, r.SilosSent);
Assert.Equal(1, r.SilosFailed);
Assert.Contains("down", r.Note);
}
}

View File

@ -0,0 +1,556 @@
using FluentValidation;
using NTP.Application.Abstractions;
using NTP.Application.Access;
using NTP.Application.Common;
using NTP.Application.Grains.Permits;
using NTP.Application.Grains.Reports;
using NTP.Application.Registrar;
using LookupItem = NTP.Application.Registrar.LookupItem;
namespace NTP.Tests.Registrar;
public class RegistrarRulesTests
{
private static RegistrarUpdateRequest FullDriver() => new()
{
Nationality = "jo", Nnpn = "9801012345", NameAr = "احمد علي", NameEn = "Ahmad Ali", DateOfBirth = new DateTime(1990, 1, 1), BloodGroup = "A+", Governate = "AQABA",
Address = "العقبة", LicenseNo = "123", LicenseType = "61", LicenseIssueDate = new DateTime(2020, 1, 1), LicenseExpiryDate = new DateTime(2030, 1, 1),
};
private static RegistrarUpdateRequest FullTruck() => new()
{
Nationality = "jo", PlateNo = "12345", OwnerName = "owner", Governate = "AQABA", OwnerAddress = "addr", Manufacturer = "VOLVO", Model = "FH", Color = "WHITE",
VehicleType = "SHIPMENT", ManufactureYear = "2015", LicenseExpiryDate = new DateTime(2030, 1, 1), Category = "TRUCK", LicenseNo = "1", LicenseRegistrationNo = "2",
VinNumber = "VIN1", EngineNumber = "ENG1", LoadingWeight = "20000", GrossWeight = "40000",
};
private static string[] Fields(RegistrarKind kind, RegistrarUpdateRequest r, bool update = true) =>
RegistrarRules.Check(kind, r, update).Select(f => f.PropertyName).Distinct().OrderBy(x => x).ToArray();
[Fact]
public void A_complete_jordanian_driver_has_no_problem() => Assert.Empty(Fields(RegistrarKind.Driver, FullDriver()));
[Fact]
public void A_complete_jordanian_truck_has_no_problem() => Assert.Empty(Fields(RegistrarKind.Truck, FullTruck()));
[Fact]
public void Jordanian_driver_needs_every_form_field()
{
var failed = Fields(RegistrarKind.Driver, new RegistrarUpdateRequest { Nationality = "jo", NameAr = "احمد" });
Assert.Equal(["address", "bloodGroup", "dateOfBirth", "governate", "licenseExpiryDate", "licenseIssueDate", "licenseNo", "licenseType", "nnpn"], failed);
}
[Fact]
public void Foreign_driver_only_needs_nationality_number_and_licence()
{
var failed = Fields(RegistrarKind.Driver, new RegistrarUpdateRequest { Nationality = "sy", NameEn = "Ali" });
Assert.Equal(["licenseNo", "licenseType", "nnpn"], failed);
}
[Fact]
public void Foreign_truck_only_needs_plate_make_and_colour()
{
var failed = Fields(RegistrarKind.Truck, new RegistrarUpdateRequest { Nationality = "sy" });
Assert.Equal(["color", "manufacturer", "plateNo"], failed);
}
[Fact]
public void Foreign_trailer_needs_plate_make_and_model()
{
var failed = Fields(RegistrarKind.Trailer, new RegistrarUpdateRequest { Nationality = "sy" });
Assert.Equal(["manufacturer", "model", "plateNo"], failed);
}
[Fact]
public void Jordanian_trailer_does_not_need_engine_number_or_loading_weight()
{
var trailer = FullTruck();
trailer.EngineNumber = null;
trailer.LoadingWeight = null;
trailer.VehicleType = null;
trailer.Category = null;
Assert.Empty(Fields(RegistrarKind.Trailer, trailer));
Assert.Equal(["engineNumber", "loadingWeight"], Fields(RegistrarKind.Truck, trailer).Where(f => f is "engineNumber" or "loadingWeight").ToArray()); // a truck does
}
[Fact]
public void A_driver_needs_an_arabic_or_an_english_name()
{
var d = FullDriver();
d.NameAr = " ";
d.NameEn = null;
var f = RegistrarRules.Check(RegistrarKind.Driver, d, true);
Assert.Contains(f, x => x.ErrorMessage == RegistrarMessages.OneOfName);
}
[Theory]
[InlineData("Ahmad", true)] // latin letters in the Arabic name
[InlineData("احمد 2", true)] // digit
[InlineData("احمد علي", false)]
public void Arabic_name_takes_arabic_letters_only(string name, bool bad)
{
var d = FullDriver();
d.NameAr = name;
Assert.Equal(bad, RegistrarRules.Check(RegistrarKind.Driver, d, true).Any(x => x.ErrorMessage == RegistrarMessages.ArabicOnly));
}
[Theory]
[InlineData("احمد", true)]
[InlineData("Ahmad 1", true)]
[InlineData("Ahmad Ali", false)]
public void English_name_takes_english_letters_only(string name, bool bad)
{
var d = FullDriver();
d.NameEn = name;
Assert.Equal(bad, RegistrarRules.Check(RegistrarKind.Driver, d, true).Any(x => x.ErrorMessage == RegistrarMessages.EnglishOnly));
}
[Fact]
public void Licence_issue_date_may_not_be_after_the_expiry_when_updating()
{
var d = FullDriver();
d.LicenseIssueDate = new DateTime(2031, 1, 1);
Assert.Contains(RegistrarRules.Check(RegistrarKind.Driver, d, true), x => x.ErrorMessage == RegistrarMessages.IssueAfterExpiry);
Assert.DoesNotContain(RegistrarRules.Check(RegistrarKind.Driver, d, false), x => x.ErrorMessage == RegistrarMessages.IssueAfterExpiry); // the complete button never checked it
}
[Theory]
[InlineData("manufactureYear")]
[InlineData("loadingWeight")]
[InlineData("grossWeight")]
public void Year_and_weights_take_digits_only(string field)
{
var t = FullTruck();
switch (field)
{
case "manufactureYear": t.ManufactureYear = "20x5"; break;
case "loadingWeight": t.LoadingWeight = "12.5"; break;
default: t.GrossWeight = "-3"; break;
}
var f = RegistrarRules.Check(RegistrarKind.Truck, t, true);
Assert.Contains(f, x => x.PropertyName == field && x.ErrorMessage == RegistrarMessages.NumbersOnly);
}
[Fact]
public void Text_longer_than_the_column_is_refused_on_update()
{
var d = FullDriver();
d.Nnpn = new string('1', 21);
Assert.Contains(RegistrarRules.Check(RegistrarKind.Driver, d, true), x => x.PropertyName == "nnpn" && x.ErrorMessage == RegistrarMessages.TooLong);
Assert.Equal(60, RegistrarRules.MaxLength(RegistrarKind.Truck, "model"));
Assert.Equal(20, RegistrarRules.MaxLength(RegistrarKind.Trailer, "model"));
}
[Fact]
public void Status_changes_follow_the_legacy_matrix()
{
Assert.True(RegistrarRules.CanComplete("PENDING"));
Assert.True(RegistrarRules.CanRevoke("pending"));
Assert.False(RegistrarRules.CanComplete("COMPLETED"));
Assert.False(RegistrarRules.CanRevoke("REVOKE"));
Assert.True(RegistrarRules.CanReopen("COMPLETED"));
Assert.False(RegistrarRules.CanReopen("PENDING"));
Assert.False(RegistrarRules.CanReopen("INCOMPLETE"));
}
[Fact]
public void Update_key_depends_on_the_status_and_only_drivers_can_be_updated_when_completed()
{
var driver = RegistrarKinds.Of(RegistrarKind.Driver);
var truck = RegistrarKinds.Of(RegistrarKind.Truck);
Assert.Equal(PermissionKeys.RegistrarDriversUpdate, RegistrarRules.UpdateKey(driver, "PENDING"));
Assert.Equal(PermissionKeys.RegistrarDriversUpdateCompleted, RegistrarRules.UpdateKey(driver, "COMPLETED"));
Assert.Null(RegistrarRules.UpdateKey(truck, "COMPLETED"));
Assert.Null(RegistrarRules.UpdateKey(driver, "REVOKE"));
Assert.Null(RegistrarRules.UpdateKey(driver, "INCOMPLETE"));
}
[Fact]
public void The_stored_record_round_trips_to_a_valid_form()
{
var r = new RegistrarRecord
{
Nationality = "jo", PlateNo = "1", OwnerName = "o", Governate = "g", OwnerAddress = "a", Manufacturer = "m", Model = "x", Color = "c", VehicleType = "t",
ManufactureYear = 2015, LicenseExpiryDate = new DateTime(2030, 1, 1), Category = "k", LicenseNo = "1", LicenseRegistrationNo = "2", VinNumber = "v", EngineNumber = "e",
LoadingWeight = 20000m, GrossWeight = 40000.5m,
};
var req = RegistrarRules.ToRequest(r);
Assert.Equal("2015", req.ManufactureYear);
Assert.Equal("20000", req.LoadingWeight);
Assert.Equal("40000.5", req.GrossWeight);
}
[Fact]
public void Kind_slugs_resolve()
{
Assert.True(RegistrarKinds.TryParse("Trucks", out var k));
Assert.Equal(RegistrarKind.Truck, k);
Assert.False(RegistrarKinds.TryParse("cars", out _));
Assert.Equal("DRIVERS_INFO", RegistrarKinds.Of(RegistrarKind.Driver).Table);
}
}
public class RegistrarServiceTests
{
private sealed class FakeUser : ICurrentUser
{
public bool IsAuthenticated => true;
public long Id => 5;
public string UserId => "REGISTRAR1";
public string Name => "t";
public string RoleCode => "TEMP";
public string RoleName => "TEMP";
public string Domain => "ASEZA";
public long? LocationId => null;
public string LocationName => "";
public long? StkId => null;
public long? CompId => null;
public long? CompanyId => null;
public string CompanyName => "";
public string CompanyCode => "";
public string EmpNo => "";
public string Lang => "AR";
public bool IsStaff => false;
public bool IsInRole(string roleCode) => true;
public bool IsInAnyRole(params string[] roleCodes) => true;
}
private sealed class FakePermissions(params string[] keys) : IPermissionService
{
public Task<PermissionsDto> GetForCurrentUserAsync(CancellationToken ct = default) => throw new NotSupportedException();
public Task<bool> IsAllowedAsync(string resourceKey, CancellationToken ct = default) => Task.FromResult(keys.Contains(resourceKey));
}
private sealed class FakeRepo : IRegistrarRepository
{
public RegistrarRecord? Record;
public Dictionary<(RegistrarKind Kind, long? Exclude), string> VinHolders = [];
public readonly List<string> Writes = [];
public bool Stale;
public Task<PagedResult<RegistrarRecord>> SearchAsync(RegistrarKind kind, RegistrarQuery query, PageRequest page, CancellationToken ct = default) =>
Task.FromResult(new PagedResult<RegistrarRecord>(Record is null ? [] : [Record], 1, 16, Record is null ? 0 : 1));
public Task<RegistrarRecord?> GetAsync(RegistrarKind kind, long id, CancellationToken ct = default) => Task.FromResult(Record);
public Task<bool> UpdateAsync(RegistrarKind kind, long id, string expectedStatus, RegistrarUpdateRequest values, string userId, CancellationToken ct = default)
{
Writes.Add($"update:{kind}:{id}:{expectedStatus}:{userId}");
return Task.FromResult(!Stale);
}
public Task<bool> ChangeStatusAsync(RegistrarKind kind, long id, string fromStatus, string toStatus, string userId, string? revokeReason, CancellationToken ct = default)
{
Writes.Add($"status:{kind}:{id}:{fromStatus}>{toStatus}:{revokeReason}");
return Task.FromResult(!Stale);
}
public Task<string?> FindPlateByVinAsync(RegistrarKind kind, string vin, long? excludeId, CancellationToken ct = default)
{
Writes.Add($"vin:{kind}:{excludeId}");
return Task.FromResult(VinHolders.TryGetValue((kind, excludeId), out var p) ? p : null);
}
}
private sealed class FakeLookups : IRegistrarLookupRepository
{
public Task<IReadOnlyDictionary<string, IReadOnlyList<LookupItem>>> GetListsAsync(CancellationToken ct = default) =>
Task.FromResult<IReadOnlyDictionary<string, IReadOnlyList<LookupItem>>>(new Dictionary<string, IReadOnlyList<LookupItem>>
{
["DRIVER_REVOKE_REASON"] = [new LookupItem("DRIVER_WRONG_NNPN", "خطأ بالرقم الوطني", "DRIVER_WRONG_NNPN")],
["TRUCK_REVOKE_REASON"] = [new LookupItem("TRUCK_WRONG_TN", "ادخال رقم الشاحنة بشكل خاطى", "TRUCK_WRONG_TN")],
["TRAILER_REVOKE_REASON"] = [],
});
public Task<IReadOnlyList<RegistrarAttachmentRow>> GetAttachmentsAsync(string entity, long id, CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<RegistrarAttachmentRow>>([new RegistrarAttachmentRow { Id = 1, FileName = "8018_FRONT.jpeg" }, new RegistrarAttachmentRow { Id = 2, FileName = null }]);
public Task<string?> GetCaptionAsync(string code, CancellationToken ct = default) =>
Task.FromResult<string?>(code == "DRIVERINFO.REVOKEREASON_DRIVER_WRONG_NNPN" ? "خطأ بالرقم الوطني (caption)" : null);
}
private sealed class FakeSettings : IRegistrarSettingsService
{
public RegistrarOptions Value { get; } = new() { AttachmentsBaseUrl = "https://files.example/up/" };
}
private sealed class FakeFiles : IRegistrarFileGatewayService
{
public readonly List<string> Urls = [];
public bool Missing;
public Task<RegistrarFile?> FetchAsync(string url, string fileName, CancellationToken ct = default)
{
Urls.Add(url);
return Task.FromResult<RegistrarFile?>(Missing ? null : new RegistrarFile([1, 2], "image/jpeg", fileName));
}
}
private sealed class FakeNotifications : IMobileNotificationGatewayService
{
public readonly List<(string Template, IReadOnlyDictionary<string, object?> Payload)> Sent = [];
public Task SendAsync(string template, IReadOnlyDictionary<string, object?> payload, CancellationToken ct = default) { Sent.Add((template, payload)); return Task.CompletedTask; }
}
private sealed class FakeExcel : IReportExcelService
{
public ReportTable? Last;
public byte[] Build(ReportTable table, string printedBy, DateTime printedAt, bool arabic) { Last = table; return [1, 2, 3]; }
public List<string[]> ReadFirstSheet(Stream stream) => [];
}
private static RegistrarRecord PendingTruck() => new()
{
Id = 9, StatusCode = "PENDING", CreatedBy = "COMP1", Nationality = "jo", PlateNo = "12345", OwnerName = "o", Governate = "g", OwnerAddress = "a", Manufacturer = "m",
Model = "x", Color = "c", VehicleType = "t", ManufactureYear = 2015, LicenseExpiryDate = new DateTime(2030, 1, 1), Category = "k", LicenseNo = "1",
LicenseRegistrationNo = "2", VinNumber = "v", EngineNumber = "e", LoadingWeight = 1, GrossWeight = 2,
};
private static RegistrarUpdateRequest TruckForm() => RegistrarRules.ToRequest(PendingTruck());
private static (RegistrarService svc, FakeRepo repo, FakeNotifications push, FakeExcel excel) Make(RegistrarRecord? record, params string[] keys) => Make(record, null, keys);
private static (RegistrarService svc, FakeRepo repo, FakeNotifications push, FakeExcel excel) Make(RegistrarRecord? record, FakeFiles? files, string[] keys)
{
var repo = new FakeRepo { Record = record };
var push = new FakeNotifications();
var excel = new FakeExcel();
return (new RegistrarService(repo, new FakeLookups(), new FakeSettings(), files ?? new FakeFiles(), new FakePermissions(keys), push, excel, new FakeUser()), repo, push, excel);
}
[Fact]
public async Task Get_returns_the_pictures_and_the_actions_the_role_has()
{
var (svc, _, _, _) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksUpdate, PermissionKeys.RegistrarTrucksComplete);
var d = await svc.GetAsync(RegistrarKind.Truck, 9, default);
var file = Assert.Single(d.Attachments); // the row without a file name is dropped
Assert.Equal(new RegistrarAttachment(1, "8018_FRONT.jpeg"), file);
Assert.Equal(new RegistrarActions(Update: true, Complete: true, Revoke: false, Reopen: false), d.Actions);
}
[Fact]
public async Task A_picture_is_fetched_from_the_upload_host_by_entity_and_escaped_name()
{
var files = new FakeFiles();
var (svc, _, _, _) = Make(PendingTruck(), files, [PermissionKeys.RegistrarTrucks]);
var f = await svc.GetAttachmentAsync(RegistrarKind.Truck, 9, 1, default);
Assert.Equal(["https://files.example/up/TRUCKINFO/8018_FRONT.jpeg"], files.Urls);
Assert.Equal("image/jpeg", f.ContentType);
}
[Fact]
public async Task An_unknown_attachment_or_a_missing_file_is_not_found()
{
var files = new FakeFiles();
var (svc, _, _, _) = Make(PendingTruck(), files, [PermissionKeys.RegistrarTrucks]);
await Assert.ThrowsAsync<NotFoundException>(() => svc.GetAttachmentAsync(RegistrarKind.Truck, 9, 2, default)); // no file name
await Assert.ThrowsAsync<NotFoundException>(() => svc.GetAttachmentAsync(RegistrarKind.Truck, 9, 99, default)); // not of this record
Assert.Empty(files.Urls);
files.Missing = true;
await Assert.ThrowsAsync<NotFoundException>(() => svc.GetAttachmentAsync(RegistrarKind.Truck, 9, 1, default));
}
[Fact]
public async Task A_missing_record_is_not_found()
{
var (svc, _, _, _) = Make(null, PermissionKeys.RegistrarTrucksUpdate);
await Assert.ThrowsAsync<NotFoundException>(() => svc.GetAsync(RegistrarKind.Truck, 1, default));
}
[Fact]
public async Task Update_needs_the_key_of_the_records_status()
{
var (svc, repo, _, _) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksComplete); // may complete, may not update
var ex = await Assert.ThrowsAsync<ForbiddenException>(() => svc.UpdateAsync(RegistrarKind.Truck, 9, TruckForm(), default));
Assert.Equal(RegistrarMessages.NoAuthority, ex.Message);
Assert.Empty(repo.Writes);
}
[Fact]
public async Task A_completed_truck_cannot_be_updated_even_with_the_update_key()
{
var truck = PendingTruck();
truck.StatusCode = "COMPLETED";
var (svc, _, _, _) = Make(truck, PermissionKeys.RegistrarTrucksUpdate);
await Assert.ThrowsAsync<ForbiddenException>(() => svc.UpdateAsync(RegistrarKind.Truck, 9, TruckForm(), default));
}
[Fact]
public async Task A_completed_driver_is_updated_with_the_completed_key()
{
var driver = new RegistrarRecord { Id = 3, StatusCode = "COMPLETED" };
var (svc, repo, _, _) = Make(driver, PermissionKeys.RegistrarDriversUpdateCompleted);
var form = new RegistrarUpdateRequest
{
Nationality = "jo", Nnpn = "1", NameAr = "احمد", DateOfBirth = new DateTime(1990, 1, 1), BloodGroup = "A+", Governate = "g", Address = "a", LicenseNo = "1",
LicenseType = "61", LicenseIssueDate = new DateTime(2020, 1, 1), LicenseExpiryDate = new DateTime(2030, 1, 1),
};
await svc.UpdateAsync(RegistrarKind.Driver, 3, form, default);
Assert.Equal(["update:Driver:3:COMPLETED:REGISTRAR1"], repo.Writes);
}
[Fact]
public async Task Update_with_missing_fields_is_a_validation_error_and_writes_nothing()
{
var (svc, repo, _, _) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksUpdate);
var form = TruckForm();
form.OwnerName = null;
var ex = await Assert.ThrowsAsync<ValidationException>(() => svc.UpdateAsync(RegistrarKind.Truck, 9, form, default));
Assert.Contains(ex.Errors, e => e.PropertyName == "ownerName");
Assert.Empty(repo.Writes);
}
[Fact]
public async Task A_truck_VIN_used_by_a_trailer_is_refused_with_the_trailer_number()
{
var (svc, repo, _, _) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksUpdate);
repo.VinHolders[(RegistrarKind.Trailer, null)] = "T-77";
var ex = await Assert.ThrowsAsync<BusinessException>(() => svc.UpdateAsync(RegistrarKind.Truck, 9, TruckForm(), default));
Assert.Equal(RegistrarErrors.VinUsedForTrailer, ex.Code);
Assert.Equal(RegistrarMessages.VinUsedForTrailer + "T-77", ex.Message);
Assert.DoesNotContain(repo.Writes, w => w.StartsWith("update"));
}
[Fact]
public async Task A_truck_VIN_used_by_another_truck_is_refused_and_the_own_record_is_excluded()
{
var (svc, repo, _, _) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksUpdate);
repo.VinHolders[(RegistrarKind.Truck, 9)] = "55555";
var ex = await Assert.ThrowsAsync<BusinessException>(() => svc.UpdateAsync(RegistrarKind.Truck, 9, TruckForm(), default));
Assert.Equal(RegistrarMessages.VinUsedForTruck + "55555", ex.Message);
Assert.Equal(["vin:Trailer:", "vin:Truck:9"], repo.Writes); // trailers first, then the other trucks
}
[Fact]
public async Task A_foreign_truck_skips_the_VIN_check()
{
var (svc, repo, _, _) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksUpdate);
repo.VinHolders[(RegistrarKind.Trailer, null)] = "T-77";
var form = TruckForm();
form.Nationality = "sy";
await svc.UpdateAsync(RegistrarKind.Truck, 9, form, default);
Assert.Equal(["update:Truck:9:PENDING:REGISTRAR1"], repo.Writes);
}
[Fact]
public async Task A_trailer_is_checked_against_trucks_first()
{
var trailer = PendingTruck();
var (svc, repo, _, _) = Make(trailer, PermissionKeys.RegistrarTrailersUpdate);
repo.VinHolders[(RegistrarKind.Truck, null)] = "12345";
var ex = await Assert.ThrowsAsync<BusinessException>(() => svc.UpdateAsync(RegistrarKind.Trailer, 9, TruckForm(), default));
Assert.Equal(RegistrarErrors.VinUsedForTruck, ex.Code);
Assert.Equal(["vin:Truck:"], repo.Writes);
}
[Fact]
public async Task A_record_changed_meanwhile_is_not_overwritten()
{
var (svc, repo, _, _) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksUpdate);
repo.Stale = true;
await Assert.ThrowsAsync<ForbiddenException>(() => svc.UpdateAsync(RegistrarKind.Truck, 9, TruckForm(), default));
}
[Fact]
public async Task Complete_changes_the_status_and_tells_the_user_who_registered_it()
{
var (svc, repo, push, _) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksComplete);
await svc.CompleteAsync(RegistrarKind.Truck, 9, default);
Assert.Equal(["status:Truck:9:PENDING>COMPLETED:"], repo.Writes);
var (template, payload) = Assert.Single(push.Sent);
Assert.Equal(NotificationRules.RegistrationApprove, template);
Assert.Equal("COMP1", payload["LOGIN"]);
Assert.Equal("شاحنة", payload["REGISTRATION_TYPE"]);
Assert.Equal("12345", payload["REGISTRATION_NUMBER_TYPE"]);
Assert.False(payload.ContainsKey("REASON"));
}
[Fact]
public async Task Complete_of_incomplete_data_is_refused()
{
var truck = PendingTruck();
truck.VinNumber = null;
var (svc, repo, push, _) = Make(truck, PermissionKeys.RegistrarTrucksComplete);
var ex = await Assert.ThrowsAsync<ValidationException>(() => svc.CompleteAsync(RegistrarKind.Truck, 9, default));
Assert.Contains(ex.Errors, e => e.PropertyName == "vinNumber");
Assert.Empty(repo.Writes);
Assert.Empty(push.Sent);
}
[Fact]
public async Task Complete_needs_a_pending_record_and_the_key()
{
var done = PendingTruck();
done.StatusCode = "COMPLETED";
await Assert.ThrowsAsync<ForbiddenException>(() => Make(done, PermissionKeys.RegistrarTrucksComplete).svc.CompleteAsync(RegistrarKind.Truck, 9, default));
await Assert.ThrowsAsync<ForbiddenException>(() => Make(PendingTruck(), PermissionKeys.RegistrarTrucksRevoke).svc.CompleteAsync(RegistrarKind.Truck, 9, default));
}
[Fact]
public async Task Revoke_stores_the_reason_and_pushes_its_caption()
{
var driver = new RegistrarRecord { Id = 3, StatusCode = "PENDING", CreatedBy = "DRV1", Nnpn = "9801" };
var (svc, repo, push, _) = Make(driver, PermissionKeys.RegistrarDriversRevoke);
await svc.RevokeAsync(RegistrarKind.Driver, 3, " DRIVER_WRONG_NNPN ", default);
Assert.Equal(["status:Driver:3:PENDING>REVOKE:DRIVER_WRONG_NNPN"], repo.Writes);
var (template, payload) = Assert.Single(push.Sent);
Assert.Equal(NotificationRules.RegistrationRevoke, template);
Assert.Equal("سائق", payload["REGISTRATION_TYPE"]);
Assert.Equal("9801", payload["REGISTRATION_NUMBER_TYPE"]);
Assert.Equal("خطأ بالرقم الوطني (caption)", payload["REASON"]);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("NOT_IN_THE_LIST")]
public async Task Revoke_needs_a_reason_from_the_list(string? reason)
{
var (svc, repo, push, _) = Make(new RegistrarRecord { Id = 3, StatusCode = "PENDING", CreatedBy = "x" }, PermissionKeys.RegistrarDriversRevoke);
var ex = await Assert.ThrowsAsync<ValidationException>(() => svc.RevokeAsync(RegistrarKind.Driver, 3, reason, default));
Assert.Contains(ex.Errors, e => e.ErrorMessage == RegistrarMessages.FillRevokeReason);
Assert.Empty(repo.Writes);
Assert.Empty(push.Sent);
}
[Fact]
public async Task A_reason_of_another_kind_does_not_count()
{
var (svc, _, _, _) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksRevoke);
await Assert.ThrowsAsync<ValidationException>(() => svc.RevokeAsync(RegistrarKind.Truck, 9, "DRIVER_WRONG_NNPN", default));
await svc.RevokeAsync(RegistrarKind.Truck, 9, "TRUCK_WRONG_TN", default); // falls back to the list name: no caption in the fake
}
[Fact]
public async Task Reopen_moves_a_completed_record_back_to_pending_without_a_push()
{
var truck = PendingTruck();
truck.StatusCode = "COMPLETED";
var (svc, repo, push, _) = Make(truck, PermissionKeys.RegistrarTrucksReopen);
await svc.ReopenAsync(RegistrarKind.Truck, 9, default);
Assert.Equal(["status:Truck:9:COMPLETED>PENDING:"], repo.Writes);
Assert.Empty(push.Sent);
await Assert.ThrowsAsync<ForbiddenException>(() => Make(PendingTruck(), PermissionKeys.RegistrarTrucksReopen).svc.ReopenAsync(RegistrarKind.Truck, 9, default));
}
[Fact]
public async Task Search_refuses_a_reversed_date_range()
{
var (svc, _, _, _) = Make(null);
var q = new RegistrarQuery(null, null, null, null, null, new DateTime(2026, 2, 1), new DateTime(2026, 1, 1), []);
var ex = await Assert.ThrowsAsync<BusinessException>(() => svc.SearchAsync(RegistrarKind.Truck, q, new PageRequest(1, 16), default));
Assert.Equal(RegistrarErrors.DateRange, ex.Code);
}
[Fact]
public async Task Export_needs_the_report_key_and_uses_the_legacy_layout()
{
var q = new RegistrarQuery(null, null, null, null, null, null, null, ["PENDING"]);
await Assert.ThrowsAsync<ForbiddenException>(() => Make(PendingTruck(), PermissionKeys.RegistrarTrucks).svc.ExportAsync(RegistrarKind.Truck, q, default));
var (svc, _, _, excel) = Make(PendingTruck(), PermissionKeys.RegistrarTrucksReport);
var f = await svc.ExportAsync(RegistrarKind.Truck, q, default);
Assert.Equal("TRUCKINFO.xlsx", f.FileName);
Assert.NotNull(excel.Last);
Assert.Equal("رخص الشاحنات", excel.Last!.TitleAr);
Assert.Equal("counter", excel.Last.Columns[0].Key);
Assert.Equal("plateNo", excel.Last.Columns[1].Key);
Assert.Single(excel.Last.Rows);
Assert.Equal("12345", excel.Last.Rows[0]["plateNo"]);
Assert.Equal("قيد التدقيق", excel.Last.Rows[0]["status"]);
Assert.Contains(excel.Last.FilterLines, l => l == "الحالة: قيد التدقيق");
}
}

View File

@ -1,8 +1,8 @@
import { useSyncExternalStore } from 'react'; import { useSyncExternalStore } from 'react';
/** Global in-flight request counters: reads drive the slim progress bar, writes drive the blocking overlay. */ /** Global in-flight request counters: reads drive the slim progress bar, writes drive the blocking overlay. */
interface Snapshot { reads: number; writes: number } interface Snapshot { reads: number; writes: number; reports: number }
let state: Snapshot = { reads: 0, writes: 0 }; let state: Snapshot = { reads: 0, writes: 0, reports: 0 };
const listeners = new Set<() => void>(); const listeners = new Set<() => void>();
function emit(next: Snapshot) { function emit(next: Snapshot) {
@ -10,13 +10,14 @@ function emit(next: Snapshot) {
listeners.forEach((l) => l()); listeners.forEach((l) => l());
} }
export function trackStart(kind: 'read' | 'write'): () => void { export function trackStart(kind: 'read' | 'write' | 'report'): () => void {
emit(kind === 'read' ? { ...state, reads: state.reads + 1 } : { ...state, writes: state.writes + 1 }); const key = kind === 'read' ? 'reads' : kind === 'write' ? 'writes' : 'reports';
emit({ ...state, [key]: state[key] + 1 });
let done = false; let done = false;
return () => { return () => {
if (done) return; if (done) return;
done = true; done = true;
emit(kind === 'read' ? { ...state, reads: state.reads - 1 } : { ...state, writes: state.writes - 1 }); emit({ ...state, [key]: state[key] - 1 });
}; };
} }

View File

@ -29,15 +29,16 @@ export function GlobalProgress() {
/** Blocking "Saving..." card for writes; also prevents double submits. */ /** Blocking "Saving..." card for writes; also prevents double submits. */
export function SavingOverlay() { export function SavingOverlay() {
const { writes } = useActivity(); const { writes, reports } = useActivity();
const { t } = useUi(); const { t } = useUi();
const report = writes === 0 && reports > 0;
return ( return (
<Backdrop open={writes > 0} sx={{ zIndex: (th) => th.zIndex.modal + 20, color: 'text.primary', backgroundColor: 'rgba(0,0,0,0.35)' }}> <Backdrop open={writes + reports > 0} sx={{ zIndex: (th) => th.zIndex.modal + 20, color: 'text.primary', backgroundColor: 'rgba(0,0,0,0.35)' }}>
<Paper role="status" aria-live="polite" sx={{ p: 3, display: 'flex', gap: 2, alignItems: 'center', minWidth: 260 }}> <Paper role="status" aria-live="polite" sx={{ p: 3, display: 'flex', gap: 2, alignItems: 'center', minWidth: 260 }}>
<CircularProgress size={28} /> <CircularProgress size={28} />
<Box> <Box>
<Typography sx={{ fontWeight: 700 }}>{t('busy.saving')}</Typography> <Typography sx={{ fontWeight: 700 }}>{t(report ? 'busy.report' : 'busy.saving')}</Typography>
<Typography variant="body2" color="text.secondary">{t('busy.savingHint')}</Typography> <Typography variant="body2" color="text.secondary">{t(report ? 'busy.reportHint' : 'busy.savingHint')}</Typography>
</Box> </Box>
</Paper> </Paper>
</Backdrop> </Backdrop>

View File

@ -26,6 +26,8 @@ export interface MetaFormProps {
confirmMessage?: string | false; confirmMessage?: string | false;
/** Field-level errors from the backend (ApiError.fieldErrors); the first one is focused. */ /** Field-level errors from the backend (ApiError.fieldErrors); the first one is focused. */
serverErrors?: Record<string, string>; serverErrors?: Record<string, string>;
/** Called after the user changes a field; `patch` fills other fields (e.g. auto-fill from a lookup). */
onFieldChange?: (name: string, value: unknown, patch: (values: FormValues) => void) => void;
/** Extra buttons next to Save/Cancel. */ /** Extra buttons next to Save/Cancel. */
extraActions?: ReactNode; extraActions?: ReactNode;
/** Extra sections drawn after the form sections and before the buttons (e.g. a documents section). */ /** Extra sections drawn after the form sections and before the buttons (e.g. a documents section). */
@ -84,6 +86,9 @@ export function MetaForm(props: MetaFormProps) {
if (first) focusField(first.name); if (first) focusField(first.name);
}, [props.serverErrors, fields, focusField]); }, [props.serverErrors, fields, focusField]);
const onFieldChangeRef = useRef(props.onFieldChange);
onFieldChangeRef.current = props.onFieldChange;
const setValue = useCallback( const setValue = useCallback(
(name: string, v: unknown) => { (name: string, v: unknown) => {
setValues((cur) => { setValues((cur) => {
@ -92,6 +97,7 @@ export function MetaForm(props: MetaFormProps) {
return next; return next;
}); });
setErrors((e) => (e[name] ? { ...e, [name]: '' } : e)); setErrors((e) => (e[name] ? { ...e, [name]: '' } : e));
onFieldChangeRef.current?.(name, v, (patch) => setValues((cur) => ({ ...cur, ...patch })));
}, },
[fields], [fields],
); );

View File

@ -0,0 +1,117 @@
import { useMemo, useState } from 'react';
import type { RouteObject } from 'react-router-dom';
import { Button } from '@mui/material';
import BlockIcon from '@mui/icons-material/Block';
import DownloadIcon from '@mui/icons-material/Download';
import PhoneInTalkIcon from '@mui/icons-material/PhoneInTalk';
import { useSearchParams } from 'react-router-dom';
import { api } from '@/api/client';
import { useWrite } from '@/api/hooks';
import { DataGrid, gridKey } from '@/components/DataGrid';
import { PageHeader } from '@/components/PageHeader';
import type { GridMeta, OptionItem, OptionsLoader, StatusMeta } from '@/components/meta/types';
import { useFeatureUi } from '@/i18n/useUi';
import { useAuth } from '@/providers/AuthProvider';
import { useConfirm } from '@/providers/ConfirmProvider';
import { useToast } from '@/providers/ToastProvider';
import type { MenuItem } from '@/shell/types';
import { downloadFile } from '../grains-orders/api';
import strings from './strings';
const BASE = '/grains/communication';
const GRID = 'grains.communication';
interface Row {
id: number; tn: string | null; pn: number | null; cargoType: string | null; phoneNumber: string | null; distDate: string | null; orderDate: string | null;
shift: string | null; answer: string; notes: string; remainingMinutes: number | null; isBlocked: boolean;
}
const statuses: StatusMeta[] = [
{ value: 'PENDING', label: strings['gc.status.PENDING'], color: 'warning' },
{ value: 'CLOSE', label: strings['gc.status.CLOSE'], color: 'success' },
{ value: 'DELETED', label: strings['gc.status.DELETED'], color: 'error' },
];
const cargo: OptionsLoader = {
key: 'grains.communication.cargo',
load: async () => (await api.get<{ id: number; name: string | null }[]>(`${BASE}/cargo-types`)).map((c): OptionItem => ({ value: c.id, label: c.name ?? String(c.id) })),
};
/** Legacy GN_COMMUNICATIONGRID: opens on the permits without an answer; the reply column carries the answer and the minutes left. */
function gridMeta(): GridMeta<Row> {
return {
key: GRID,
endpoint: BASE,
rowKey: (r) => r.id,
pageSize: 16,
emptyAsGrid: true,
defaultFilters: { statusCode: 'PENDING' },
status: { param: 'statusCode', options: statuses },
filters: [
{ name: 'tn', type: 'text', label: strings['gc.f.tn'], ltr: true },
{ name: 'pn', type: 'text', label: strings['gc.f.pn'], ltr: true },
{ name: 'cargoTypeCode', type: 'select', label: strings['gc.f.cargoOrder'], options: cargo },
{ name: 'isBlocked', type: 'select', label: strings['gc.f.blocked'], options: [{ value: '1', label: strings['gc.yes'] }, { value: '0', label: strings['gc.no'] }] },
{ name: 'shift', type: 'select', label: strings['gc.f.shift'], options: [{ value: '1', label: strings['gc.shift.1'] }, { value: '2', label: strings['gc.shift.2'] }] },
{ name: 'orderDateFrom', type: 'date', label: strings['gc.f.from'] },
{ name: 'orderDateTo', type: 'date', label: strings['gc.f.to'] },
],
columns: [
{ key: 'tn', header: strings['gc.f.tn'], ltr: true },
{ key: 'pn', header: strings['gc.f.pn'], ltr: true },
{ key: 'cargoType', header: strings['gc.f.cargo'] },
{ key: 'phoneNumber', header: strings['gc.f.mobile'], ltr: true },
{ key: 'distDate', header: strings['gc.f.dist'], ltr: true },
{ key: 'orderDate', header: strings['gc.f.order'], ltr: true },
{ key: 'remainingMinutes', header: strings['gc.f.remaining'], render: (r) => (r.remainingMinutes === null ? '-' : String(r.remainingMinutes).padStart(2, '0')), ltr: true },
{ key: 'notes', header: strings['gc.f.reply'] },
],
};
}
function CommunicationPage() {
const { t } = useFeatureUi(strings);
const { can } = useAuth();
const toast = useToast();
const confirm = useConfirm();
const [sp] = useSearchParams();
const [busy, setBusy] = useState(false);
const meta = useMemo(() => gridMeta(), []);
const block = useWrite(() => api.post<{ message: string; count: number }>(`${BASE}/blacklist`), { invalidate: [gridKey(GRID)], toastSuccess: false, onSuccess: (r) => { if (r.count === 0) toast.info(t('gc.blacklist.none')); else toast.success(r.message); } });
const exportXlsx = async () => {
setBusy(true);
const params: Record<string, string> = {};
sp.forEach((v, k) => { if (!['page', 'pageSize', 'size', 'f'].includes(k)) params[k] = v; });
try { await downloadFile(`${BASE}/export`, params, 'COMMUNICATION.xlsx'); }
catch (e) { toast.error(e instanceof Error ? e.message : String(e)); }
finally { setBusy(false); }
};
return (
<>
<PageHeader
title={t('gc.title')}
subtitle={t('gc.subtitle')}
actions={(
<>
{can('grains.communication.report') && <Button variant="outlined" startIcon={<DownloadIcon />} disabled={busy} onClick={() => void exportXlsx()}>{t('gc.export')}</Button>}
{can('grains.communication.blacklist') && (
<Button variant="contained" color="error" startIcon={<BlockIcon />} disabled={block.isPending}
onClick={async () => { if (await confirm({ message: t('gc.blacklist.confirm'), danger: true })) block.mutate(undefined as never); }}>
{t('gc.blacklist')}
</Button>
)}
</>
)}
/>
<DataGrid meta={meta} />
</>
);
}
export const routes: RouteObject[] = [{ path: '/grains/communication', element: <CommunicationPage /> }];
export const menu: MenuItem[] = [
{ key: 'grains.communication', title: strings['gc.menu'], icon: PhoneInTalkIcon, path: '/grains/communication' },
];

View File

@ -0,0 +1,32 @@
import { defineStrings } from '@/i18n/useUi';
/** Strings of the communication officer screen (legacy captions MENU.GRAINS_CALLES, COMMUNICATION.*, verbatim in Arabic). */
export default defineStrings({
'gc.menu': { en: 'Voice call system', ar: 'نظام الاتصال الصوتي' },
'gc.title': { en: 'Communication officer screen', ar: 'شاشة موظف الاتصالات' },
'gc.subtitle': { en: 'Distributed permits and the answers of their owners (last 30 days)', ar: 'الارساليات الموزعة وردود اصحابها (اخر 30 يوم)' },
'gc.export': { en: 'Excel', ar: 'تصدير Excel' },
'gc.blacklist': { en: 'Add to blacklist', ar: 'إضافة على قائمة المنع' },
'gc.blacklist.confirm': { en: 'Stop the postponement of every permit that did not answer? Their owners are notified.', ar: 'هل تريد ايقاف خاصية التثبيت والتأجيل عن جميع الارساليات التي لم يتم الرد عليها؟ سيتم اشعار اصحابها.' },
'gc.blacklist.none': { en: 'No permit is waiting for an answer.', ar: 'لا توجد ارساليات بدون رد.' },
'gc.f.tn': { en: 'Truck', ar: 'رقم الشاحنة' },
'gc.f.pn': { en: 'Permit number', ar: 'رقم الارسالية' },
'gc.f.cargo': { en: 'Cargo type', ar: 'نوع المادة' },
'gc.f.cargoOrder': { en: 'Cargo type', ar: 'نوع المادة' },
'gc.f.mobile': { en: 'Mobile', ar: 'رقم الموبايل' },
'gc.f.dist': { en: 'Distribution time', ar: 'وقت التوزيع' },
'gc.f.order': { en: 'Order date', ar: 'تاريخ الطلبية' },
'gc.f.remaining': { en: 'Minutes left to answer', ar: 'الوقت المتبقي للرد(د)' },
'gc.f.reply': { en: 'Reply', ar: 'الرد' },
'gc.f.shift': { en: 'Shift', ar: 'الشفت' },
'gc.f.blocked': { en: 'Postponement stopped', ar: 'ايقاف التأجيل' },
'gc.f.from': { en: 'Order from', ar: 'من تاريخ الطلبية' },
'gc.f.to': { en: 'Order to', ar: 'الى تاريخ الطلبية' },
'gc.shift.1': { en: 'Morning', ar: 'الصباحي' },
'gc.shift.2': { en: 'Evening', ar: 'المسائي' },
'gc.yes': { en: 'Yes', ar: 'نعم' },
'gc.no': { en: 'No', ar: 'لا' },
'gc.status.PENDING': { en: 'No reply', ar: 'لم يتم الرد' },
'gc.status.CLOSE': { en: 'Confirmed', ar: 'تم الإجابة - موافق' },
'gc.status.DELETED': { en: 'Postponed', ar: 'تم الإجابة - تأجيل' },
});

View File

@ -1,5 +1,6 @@
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { api, API_BASE, ApiError, getToken, MOCK } from '@/api/client'; import { api, API_BASE, ApiError, getToken, MOCK } from '@/api/client';
import { trackStart } from '@/api/activity';
import { useWrite } from '@/api/hooks'; import { useWrite } from '@/api/hooks';
import { gridKey } from '@/components/DataGrid'; import { gridKey } from '@/components/DataGrid';
import type { OptionItem, OptionsLoader } from '@/components/meta/types'; import type { OptionItem, OptionsLoader } from '@/components/meta/types';
@ -174,6 +175,8 @@ export async function downloadFile(apiPath: string, params: Record<string, strin
const qs = new URLSearchParams(); const qs = new URLSearchParams();
for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== '') qs.append(k, String(v)); for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== '') qs.append(k, String(v));
const token = getToken(); const token = getToken();
const done = trackStart('report'); // blocking "generating the report" card until the file arrives
try {
const res = await fetch(`${API_BASE}${apiPath}?${qs}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} }); const res = await fetch(`${API_BASE}${apiPath}?${qs}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
if (!res.ok) { if (!res.ok) {
let problem: { detail?: string; title?: string } | undefined; let problem: { detail?: string; title?: string } | undefined;
@ -191,4 +194,5 @@ export async function downloadFile(apiPath: string, params: Record<string, strin
a.click(); a.click();
a.remove(); a.remove();
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
} finally { done(); }
} }

View File

@ -3,7 +3,7 @@ import { defineStrings } from '@/i18n/useUi';
/** Feature strings of the Grains "registry" slice (trucks, trailers, drivers, blacklist, weighbridge control). */ /** Feature strings of the Grains "registry" slice (trucks, trailers, drivers, blacklist, weighbridge control). */
export default defineStrings({ export default defineStrings({
// ---- menu // ---- menu
'reg.menu.group': { en: 'Fleet registry', ar: 'سجل الأسطول' }, 'reg.menu.group': { en: 'Fleet registry', ar: 'تسجيل التموين' },
'reg.menu.controlGroup': { en: 'Restrictions and weighbridge', ar: 'المنع وضبط الميزان' }, 'reg.menu.controlGroup': { en: 'Restrictions and weighbridge', ar: 'المنع وضبط الميزان' },
'reg.menu.trucks': { en: 'Trucks', ar: 'القاطرات' }, 'reg.menu.trucks': { en: 'Trucks', ar: 'القاطرات' },
'reg.menu.trailers': { en: 'Trailers', ar: 'المقطورات' }, 'reg.menu.trailers': { en: 'Trailers', ar: 'المقطورات' },

View File

@ -1,5 +1,6 @@
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { API_BASE, api, ApiError, getToken } from '@/api/client'; import { API_BASE, api, ApiError, getToken } from '@/api/client';
import { trackStart } from '@/api/activity';
import { useWrite } from '@/api/hooks'; import { useWrite } from '@/api/hooks';
import type { OptionItem, OptionsLoader } from '@/components/meta/types'; import type { OptionItem, OptionsLoader } from '@/components/meta/types';
@ -101,6 +102,8 @@ export function fetchTable(key: string, params: Record<string, unknown>) {
export async function downloadExcel(key: string, params: Record<string, string>): Promise<void> { export async function downloadExcel(key: string, params: Record<string, string>): Promise<void> {
const qs = new URLSearchParams(params).toString(); const qs = new URLSearchParams(params).toString();
const token = getToken(); const token = getToken();
const done = trackStart('report');
try {
const res = await fetch(`${API_BASE}${base}/tables/${key}/export${qs ? `?${qs}` : ''}`, { const res = await fetch(`${API_BASE}${base}/tables/${key}/export${qs ? `?${qs}` : ''}`, {
headers: token ? { Authorization: `Bearer ${token}` } : {}, headers: token ? { Authorization: `Bearer ${token}` } : {},
}); });
@ -120,6 +123,7 @@ export async function downloadExcel(key: string, params: Record<string, string>)
a.click(); a.click();
a.remove(); a.remove();
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
} finally { done(); }
} }
// ------------------------------------------------------------------ imports (multipart) // ------------------------------------------------------------------ imports (multipart)

View File

@ -93,7 +93,6 @@ function JobCard({ job }: { job: JobItem }) {
const busy = save.isPending || start.isPending || stop.isPending || run.isPending; const busy = save.isPending || start.isPending || stop.isPending || run.isPending;
const title = lang === 'ar' ? job.titleAr : job.titleEn; const title = lang === 'ar' ? job.titleAr : job.titleEn;
const description = lang === 'ar' ? job.descriptionAr : job.descriptionEn;
const state = job.running ? 'running' : job.enabled ? 'started' : 'stopped'; const state = job.running ? 'running' : job.enabled ? 'started' : 'stopped';
const addTime = () => { const addTime = () => {
@ -114,13 +113,10 @@ function JobCard({ job }: { job: JobItem }) {
}; };
return ( return (
<Paper sx={{ p: 2 }}> <Paper sx={{ p: 1.5 }}>
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}> <Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>
<ScheduleIcon color="primary" /> <ScheduleIcon color="primary" />
<Box sx={{ flex: 1, minWidth: 220 }}> <Typography sx={{ fontWeight: 700, flex: 1, minWidth: 220, textAlign: 'start' }} dir="ltr">{job.key}</Typography>
<Typography sx={{ fontWeight: 700 }}>{title}</Typography>
<Typography variant="caption" color="text.secondary" dir="ltr" sx={{ display: 'block', textAlign: 'start' }}>{job.key}</Typography>
</Box>
<Chip <Chip
label={t(`jobs.state.${state}` as const)} label={t(`jobs.state.${state}` as const)}
color={state === 'running' ? 'info' : state === 'started' ? 'success' : 'default'} color={state === 'running' ? 'info' : state === 'started' ? 'success' : 'default'}
@ -128,9 +124,7 @@ function JobCard({ job }: { job: JobItem }) {
/> />
</Stack> </Stack>
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>{description}</Typography> <Box sx={{ display: 'grid', gap: 1.5, mt: 1, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, minmax(0, 1fr))' } }}>
<Box sx={{ display: 'grid', gap: 2, mt: 2, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, minmax(0, 1fr))' } }}>
<Box> <Box>
<Typography variant="caption" color="text.secondary">{t('jobs.lastRun')}</Typography> <Typography variant="caption" color="text.secondary">{t('jobs.lastRun')}</Typography>
{job.lastStart ? ( {job.lastStart ? (
@ -152,8 +146,8 @@ function JobCard({ job }: { job: JobItem }) {
</Box> </Box>
</Box> </Box>
<Typography variant="subtitle2" sx={{ mt: 2.5, mb: 1 }}>{t('jobs.schedule')}</Typography> <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1.25, mb: 0.5 }}>{t('jobs.schedule')}</Typography>
<Stack spacing={1.5}> <Stack direction="row" spacing={1.5} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
<ToggleButtonGroup exclusive size="small" color="primary" value={type} onChange={(_, v: 'INTERVAL' | 'DAILY' | null) => v && setType(v)}> <ToggleButtonGroup exclusive size="small" color="primary" value={type} onChange={(_, v: 'INTERVAL' | 'DAILY' | null) => v && setType(v)}>
<ToggleButton value="INTERVAL">{t('jobs.type.interval')}</ToggleButton> <ToggleButton value="INTERVAL">{t('jobs.type.interval')}</ToggleButton>
<ToggleButton value="DAILY">{t('jobs.type.daily')}</ToggleButton> <ToggleButton value="DAILY">{t('jobs.type.daily')}</ToggleButton>
@ -194,7 +188,7 @@ function JobCard({ job }: { job: JobItem }) {
)} )}
</Stack> </Stack>
<Stack direction="row" spacing={1} useFlexGap sx={{ mt: 2.5, flexWrap: 'wrap' }}> <Stack direction="row" spacing={1} useFlexGap sx={{ mt: 1.25, flexWrap: 'wrap' }}>
<Button variant="outlined" startIcon={<SaveIcon />} disabled={busy || !scheduleOk || !dirty} onClick={saveOnly}>{t('jobs.save')}</Button> <Button variant="outlined" startIcon={<SaveIcon />} disabled={busy || !scheduleOk || !dirty} onClick={saveOnly}>{t('jobs.save')}</Button>
{job.enabled ? ( {job.enabled ? (
<Button variant="outlined" color="error" startIcon={<StopIcon />} disabled={busy} onClick={() => stop.mutate(job.key)}>{t('jobs.stop')}</Button> <Button variant="outlined" color="error" startIcon={<StopIcon />} disabled={busy} onClick={() => stop.mutate(job.key)}>{t('jobs.stop')}</Button>

View File

@ -0,0 +1,171 @@
import { useQuery } from '@tanstack/react-query';
import { API_BASE, ApiError, api, getToken, type PagedResult } from '@/api/client';
import { trackStart } from '@/api/activity';
import { useWrite } from '@/api/hooks';
import { gridKey } from '@/components/DataGrid';
import type { OptionItem, OptionsLoader } from '@/components/meta/types';
export const BASE = '/receipts';
export const GRID_RECEIPTS = 'receipts';
export interface ReceiptRow {
id: number;
receiptNo: number | null;
pn: number | null;
shipmentMode: string | null;
fmShipmentMode: string | null;
cargoType: string | null;
crn: number | null;
caCode: number | null;
caName: string | null;
tn: string | null;
trn: string | null;
drvr: string | null;
nnpn: string | null;
mobile: string | null;
statusCode: string | null;
creationDate: string | null;
createdBy: string | null;
dln: string | null;
dled: string | null;
scac: number | null;
companyName: string | null;
fees: number | null;
receiptType: number | null;
receiptTypeCaption: string | null;
permitStatus: string | null;
permitStatusCaption: string | null;
confirmationBy: string | null;
confirmationName: string | null;
confirmationDate: string | null;
creationSource: number;
credit: number;
requestId: number | null;
rejectReason: number | null;
rejectReasonNote: string | null;
revokeDate: string | null;
revokeBy: string | null;
}
export interface ReceiptActions {
update: boolean;
confirm: boolean;
paid: boolean;
print: boolean;
revoke: boolean;
acceptRevoke: boolean;
rejectRevoke: boolean;
}
export interface ReceiptDetail {
receipt: ReceiptRow;
actions: ReceiptActions;
rejectReasonName: string | null;
}
export interface ReceiptLogRow {
id: number;
methodName: string | null;
logDate: string | null;
login: string | null;
oldData: string | null;
newData: string | null;
}
export interface ReceiptType {
id: number;
caption: string | null;
fees: number | null;
description: string | null;
scac: number | null;
}
interface Named { code: string | null; name: string | null }
export interface ReceiptLookups { types: ReceiptType[]; rejectReasons: Named[]; cargoTypes: Named[] }
export interface ReceiptAutoFill { trn: string | null; nnpn: string | null; drvr: string | null; mobile: string | null; pn: string | null }
export interface ReceiptPrint { receipt: ReceiptRow; firstMoveText: string; description: string; showCargo: boolean; showGnpn: boolean }
export interface ReceiptResult { message: string; id: number | null }
// ---------------------------------------------------------------- lookups
export const useReceiptLookups = () =>
useQuery({ queryKey: ['receipts.lookups'], queryFn: () => api.get<ReceiptLookups>(`${BASE}/lookups`), staleTime: 5 * 60_000 });
let cache: { at: number; promise: Promise<ReceiptLookups> } | null = null;
function loadLookups(): Promise<ReceiptLookups> {
if (!cache || Date.now() - cache.at > 60_000) {
const promise = api.get<ReceiptLookups>(`${BASE}/lookups`);
promise.catch(() => { cache = null; });
cache = { at: Date.now(), promise };
}
return cache.promise;
}
/** Cargo types (CARGOTYPE) for the selects. */
export const cargoOptions: OptionsLoader = {
key: 'receipts.cargo',
load: async () => (await loadLookups()).cargoTypes.map((c): OptionItem => ({ value: c.code ?? '', label: c.name ?? '' })),
};
/** Receipt types of the supply tender company (327); type 7 is the zero-fee one the legacy never offered. */
export const typeOptions: OptionsLoader = {
key: 'receipts.types',
load: async () => (await loadLookups()).types.filter((t) => t.scac === 327 && t.id !== 7).map((t): OptionItem => ({ value: t.id, label: `${(t.caption ?? String(t.id)).trim()} - ${t.fees ?? 0} دينار` })),
};
// ---------------------------------------------------------------- reads / writes
const keys = () => [gridKey(GRID_RECEIPTS), ['receipts.one'], ['receipts.log']];
export const useReceipt = (id: number | null) =>
useQuery({ queryKey: ['receipts.one', id], queryFn: () => api.get<ReceiptDetail>(`${BASE}/${id}`), enabled: id !== null });
export const useReceiptLog = (id: number, page: number, pageSize: number, enabled: boolean) =>
useQuery({
queryKey: ['receipts.log', id, page, pageSize],
queryFn: () => api.get<PagedResult<ReceiptLogRow>>(`${BASE}/${id}/log`, { page, pageSize }, { silent: true }),
enabled,
});
export const useCreateReceipt = () => useWrite((body: Record<string, unknown>) => api.post<ReceiptResult>(BASE, body), { invalidate: keys() });
export const useUpdateReceipt = () => useWrite((v: { id: number; body: Record<string, unknown> }) => api.put<ReceiptResult>(`${BASE}/${v.id}`, v.body), { invalidate: keys() });
export const useReceiptAction = () =>
useWrite(
(v: { id: number; action: 'confirm' | 'paid' | 'revoke' | 'accept-revoke' | 'reject-revoke'; body?: unknown }) =>
api.post<ReceiptResult>(`${BASE}/${v.id}/${v.action}`, v.body),
{ invalidate: keys() },
);
export const printReceipt = (id: number) => api.post<ReceiptPrint>(`${BASE}/${id}/print`);
export const fetchTruckFill = (tn: string) => api.get<ReceiptAutoFill | undefined>(`${BASE}/autofill/truck`, { tn }, { silent: true });
export const fetchDriverFill = (nnpn: string) => api.get<ReceiptAutoFill | undefined>(`${BASE}/autofill/driver`, { nnpn }, { silent: true });
export interface AuditOutcome { compared: number; advanced: number }
/** Audit upload: multipart POST; the answer is the result workbook, saved as a download. */
export async function runAudit(form: FormData): Promise<AuditOutcome> {
const token = getToken();
const done = trackStart('report');
try {
const res = await fetch(`${API_BASE}${BASE}/audit`, { method: 'POST', body: form, headers: token ? { Authorization: `Bearer ${token}` } : {} });
if (!res.ok) {
let problem: { detail?: string; title?: string } | undefined;
try { problem = await res.json(); } catch { /* not JSON */ }
throw new ApiError(res.status, problem?.detail || problem?.title || res.statusText, problem);
}
const disposition = res.headers.get('Content-Disposition') ?? '';
const match = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(disposition);
const name = match ? decodeURIComponent(match[1]) : 'audit_result.xlsx';
const url = URL.createObjectURL(await res.blob());
const a = document.createElement('a');
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
return { compared: Number(res.headers.get('X-Audit-Compared')) || 0, advanced: Number(res.headers.get('X-Audit-Advanced')) || 0 };
} finally { done(); }
}

View File

@ -0,0 +1,151 @@
import type { FieldMeta, FormMeta, GridMeta, StatusMeta } from '@/components/meta/types';
import strings from './strings';
import { GRID_RECEIPTS, BASE, cargoOptions, typeOptions, type ReceiptRow } from './api';
const s = strings;
export const receiptStatuses: StatusMeta[] = [
{ value: 'NOT_RECEIVED', label: s['rc.status.NOT_RECEIVED'], color: 'default' },
{ value: 'RECEIVED', label: s['rc.status.RECEIVED'], color: 'success' },
{ value: 'UNPAID', label: s['rc.status.UNPAID'], color: 'warning' },
{ value: 'PAID', label: s['rc.status.PAID'], color: 'success' },
{ value: 'AUDITED', label: s['rc.status.AUDITED'], color: 'info' },
{ value: 'COMPLETED', label: s['rc.status.COMPLETED'], color: 'primary' },
{ value: 'PENDING_RVKD', label: s['rc.status.PENDING_RVKD'], color: 'warning' },
{ value: 'RVKD', label: s['rc.status.RVKD'], color: 'error' },
];
const yesNo = [{ value: '1', label: s['rc.kind.1'] }, { value: '0', label: s['rc.kind.0'] }];
const sources = [{ value: '0', label: s['rc.source.0'] }, { value: '1', label: s['rc.source.1'] }];
/** Legacy PERMITSRECEIPTSGRID: number, permit, company, cargo, truck, fees, kind, created, status; filters number, permit, truck, trailer, cargo, kind, payment way, dates. */
export function receiptsGrid(h: { onOpen: (r: ReceiptRow) => void }): GridMeta<ReceiptRow> {
return {
key: GRID_RECEIPTS,
endpoint: BASE,
rowKey: (r) => r.id,
onRowClick: h.onOpen,
pageSize: 16,
emptyAsGrid: true,
defaultFilters: { statusCode: 'RECEIVED' },
status: { param: 'statusCode', options: receiptStatuses },
filters: [
{ name: 'receiptNo', type: 'text', label: s['rc.f.receiptNo'], ltr: true },
{ name: 'pn', type: 'text', label: s['rc.f.pn'], ltr: true },
{ name: 'tn', type: 'text', label: s['rc.f.tn'], ltr: true },
{ name: 'trn', type: 'text', label: s['rc.f.trn'], ltr: true },
{ name: 'shipmentMode', type: 'select', label: s['rc.f.cargoType'], options: cargoOptions },
{ name: 'credit', type: 'select', label: s['rc.f.credit'], options: yesNo },
{ name: 'creationSource', type: 'select', label: s['rc.f.source'], options: sources },
{ name: 'createDateFrom', type: 'date', label: s['rc.f.createDateFrom'] },
{ name: 'createDateTo', type: 'date', label: s['rc.f.createDateTo'] },
],
columns: [
{ key: 'receiptNo', header: s['rc.f.receiptNo'], ltr: true },
{ key: 'pn', header: s['rc.f.pn'], ltr: true },
{ key: 'companyName', header: s['rc.f.company'] },
{ key: 'cargoType', header: s['rc.f.cargoType'] },
{ key: 'tn', header: s['rc.f.tn'], ltr: true },
{ key: 'fees', header: s['rc.f.fees'], format: 'number', ltr: true },
{ key: 'credit', header: s['rc.f.credit'], render: (r) => (r.credit === 0 ? s['rc.kind.0'].ar : s['rc.kind.1'].ar) },
{ key: 'creationDate', header: s['rc.f.creationDate'], format: 'datetime' },
{ key: 'statusCode', header: s['rc.f.status'], format: 'status', statuses: receiptStatuses },
],
};
}
const text = (name: string, label: FieldMeta['label'], extra: Partial<FieldMeta> = {}): FieldMeta => ({ name, type: 'text', label, ...extra });
const digits = { regex: /^\d+$/, message: s['rc.digits'] };
/** Create form of company 327 (legacy PERMITSRECEIPTSMain.html): kind, type, permit, truck, trailer, driver, licence, cargo type(s). */
export function createForm(): FormMeta {
return {
key: 'receipts.create.form',
sections: [
{
key: 'receipt', title: s['rc.sec.receipt'], columns: 2,
fields: [
{ name: 'credit', type: 'select', label: s['rc.f.onCredit'], required: true, options: [{ value: '0', label: s['rc.no'] }, { value: '1', label: s['rc.yes'] }], defaultValue: '0' },
{ name: 'receiptType', type: 'select', label: s['rc.f.receiptType'], required: true, options: typeOptions },
text('pn', s['rc.f.pn'], { required: true, maxLength: 15, inputKind: 'code', pattern: digits }),
{ name: 'fmShipmentMode', type: 'select', label: s['rc.f.fmShipmentMode'], options: cargoOptions, hiddenWhen: { field: 'receiptType', op: 'nin', value: ['1', '2'] }, required: false, requiredWhen: { field: 'receiptType', op: 'in', value: ['1', '2'] } },
{ name: 'shipmentMode', type: 'select', label: s['rc.f.shipmentMode'], required: true, options: cargoOptions, helper: s['rc.f.shipmentModeHelp'] },
],
},
{
key: 'vehicle', title: s['rc.sec.vehicle'], columns: 2,
fields: [
text('tn', s['rc.f.tn'], { required: true, maxLength: 45, inputKind: 'plate' }),
text('trn', s['rc.f.trn'], { required: true, maxLength: 45, inputKind: 'plate' }),
text('nnpn', s['rc.f.nnpn'], { required: true, maxLength: 20, inputKind: 'code' }),
text('drvr', s['rc.f.drvr'], { required: true, maxLength: 300 }),
text('dln', s['rc.f.dln'], { required: true, maxLength: 50, inputKind: 'code' }),
{ name: 'dled', type: 'date', label: s['rc.f.dled'], required: true },
],
},
],
};
}
/** Receipt page: read-only data of the receipt and, while it may be edited, the legacy edit fields (permit, cargo types, truck, trailer, driver). */
export function detailForm(): FormMeta {
const ro = { readOnly: true } as const;
return {
key: 'receipts.detail.form',
sections: [
{
key: 'receipt', title: s['rc.sec.receipt'], columns: 2,
fields: [
text('receiptNo', s['rc.f.receiptNo'], { ...ro, ltr: true }),
text('creditText', s['rc.f.credit'], ro),
text('receiptTypeCaption', s['rc.f.receiptType'], { ...ro, span: 'full' }),
text('fees', s['rc.f.fees'], { ...ro, ltr: true }),
text('companyName', s['rc.f.company'], ro),
text('pn', s['rc.f.pn'], { maxLength: 15, inputKind: 'code', pattern: digits }),
{ name: 'fmShipmentMode', type: 'select', label: s['rc.f.fmShipmentMode'], options: cargoOptions, hiddenWhen: { field: 'fmShipmentMode', op: 'empty' } },
{ name: 'shipmentMode', type: 'select', label: s['rc.f.shipmentMode'], options: cargoOptions },
],
},
{
key: 'vehicle', title: s['rc.sec.vehicle'], columns: 2,
fields: [
text('tn', s['rc.f.tn'], { maxLength: 45, inputKind: 'plate' }),
text('trn', s['rc.f.trn'], { maxLength: 45, inputKind: 'plate' }),
text('nnpn', s['rc.f.nnpn'], { maxLength: 20, inputKind: 'code' }),
text('drvr', s['rc.f.drvr'], { maxLength: 300 }),
text('dln', s['rc.f.dln'], { ...ro, ltr: true }),
text('dled', s['rc.f.dled'], { ...ro, ltr: true }),
],
},
{
key: 'record', title: s['rc.sec.record'], columns: 2,
fields: [
text('creationSourceText', s['rc.f.source'], ro),
text('createdBy', s['rc.f.createdBy'], { ...ro, ltr: true }),
text('creationDate', s['rc.f.creationDate'], { ...ro, ltr: true }),
text('confirmationBy', s['rc.f.confirmationBy'], { ...ro, ltr: true, hiddenWhen: { field: 'confirmationBy', op: 'empty' } }),
text('confirmationDate', s['rc.f.confirmationDate'], { ...ro, ltr: true, hiddenWhen: { field: 'confirmationDate', op: 'empty' } }),
text('rejectReasonName', s['rc.f.rejectReason'], { ...ro, span: 'full', hiddenWhen: { field: 'rejectReasonName', op: 'empty' } }),
text('rejectReasonNote', s['rc.f.rejectNote'], { ...ro, span: 'full', hiddenWhen: { field: 'rejectReasonNote', op: 'empty' } }),
],
},
],
};
}
const pad = (n: number) => String(n).padStart(2, '0');
const stamp = (v: string | null) => {
if (!v) return '';
const d = new Date(v);
return Number.isNaN(d.getTime()) ? v : `${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
export function receiptToValues(r: ReceiptRow, rejectReasonName: string | null): Record<string, unknown> {
return {
receiptNo: r.receiptNo ?? '', creditText: r.credit === 0 ? s['rc.kind.0'].ar : s['rc.kind.1'].ar, receiptTypeCaption: r.receiptTypeCaption ?? '', fees: r.fees ?? '',
companyName: r.companyName ?? '', pn: r.pn ?? '', fmShipmentMode: r.fmShipmentMode ?? '', shipmentMode: r.shipmentMode ?? '', tn: r.tn ?? '', trn: r.trn ?? '',
nnpn: r.nnpn ?? '', drvr: r.drvr ?? '', dln: r.dln ?? '', dled: r.dled ?? '', creationSourceText: r.creationSource === 0 ? s['rc.source.0'].ar : s['rc.source.1'].ar,
createdBy: r.createdBy ?? '', creationDate: stamp(r.creationDate), confirmationBy: r.confirmationBy && r.confirmationBy !== '0' ? r.confirmationBy : '',
confirmationDate: stamp(r.confirmationDate), rejectReasonName: rejectReasonName ?? '', rejectReasonNote: r.rejectReasonNote ?? '',
};
}

View File

@ -0,0 +1,419 @@
import { useMemo, useRef, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import {
Alert, Box, Button, Collapse, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Paper, Stack, Table, TableBody, TableCell, TableContainer,
TableHead, TableRow, TextField, Typography,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import BlockIcon from '@mui/icons-material/Block';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import DownloadIcon from '@mui/icons-material/Download';
import FactCheckIcon from '@mui/icons-material/FactCheck';
import HistoryIcon from '@mui/icons-material/History';
import ListAltIcon from '@mui/icons-material/ListAlt';
import PaidIcon from '@mui/icons-material/Paid';
import PrintIcon from '@mui/icons-material/Print';
import UploadFileIcon from '@mui/icons-material/UploadFile';
import type { ApiError } from '@/api/client';
import { Barcode } from '@/components/Barcode';
import { DataGrid, gridReturnUrl } from '@/components/DataGrid';
import { LoadingBanner } from '@/components/LoadingBanner';
import { Logo } from '@/components/Logo';
import { MetaForm } from '@/components/MetaForm';
import { PageHeader } from '@/components/PageHeader';
import { Pager } from '@/components/Pager';
import { SectionPaper } from '@/components/SectionPaper';
import { SectionTitle } from '@/components/SectionTitle';
import { StatusChip } from '@/components/StatusChip';
import { formatDateTime } from '@/components/meta/format';
import { useFeatureUi } from '@/i18n/useUi';
import { elementToPdfUrl } from '@/lib/pdf';
import { useAuth } from '@/providers/AuthProvider';
import { useConfirm } from '@/providers/ConfirmProvider';
import { useToast } from '@/providers/ToastProvider';
import { downloadFile } from '../grains-orders/api';
import {
BASE, fetchDriverFill, fetchTruckFill, printReceipt, runAudit, useCreateReceipt, useReceipt, useReceiptAction, useReceiptLog, useReceiptLookups,
type ReceiptAutoFill, type ReceiptPrint,
} from './api';
import { createForm, detailForm, receiptStatuses, receiptToValues, receiptsGrid } from './meta';
import strings from './strings';
const ROOT = '/receipts';
const fieldErrorsOf = (e: ApiError) => ({ ...e.fieldErrors }) as Record<string, string>;
function ExportButton() {
const { t } = useFeatureUi(strings);
const { can } = useAuth();
const toast = useToast();
const [sp] = useSearchParams();
const [busy, setBusy] = useState(false);
if (!can('receipts.report')) return null;
const run = async () => {
setBusy(true);
const params: Record<string, string> = {};
sp.forEach((v, k) => { if (!['page', 'pageSize', 'size', 'f'].includes(k)) params[k] = v; });
try { await downloadFile(`${BASE}/export`, params, 'PERMITSRECEIPTS.xlsx'); }
catch (e) { toast.error(e instanceof Error ? e.message : String(e)); }
finally { setBusy(false); }
};
return <Button variant="outlined" startIcon={<DownloadIcon />} disabled={busy} onClick={() => void run()}>{t('rc.export')}</Button>;
}
export function ReceiptsPage() {
const { t } = useFeatureUi(strings);
const navigate = useNavigate();
const { can } = useAuth();
const meta = useMemo(() => receiptsGrid({ onOpen: (r) => navigate(`${ROOT}/${r.id}`) }), [navigate]);
return (
<>
<PageHeader
title={t('rc.title')}
subtitle={t('rc.subtitle')}
actions={(
<>
<ExportButton />
{can('receipts.create') && <Button variant="contained" startIcon={<AddIcon />} onClick={() => navigate(`${ROOT}/new`)}>{t('rc.new')}</Button>}
</>
)}
/>
<DataGrid meta={meta} />
</>
);
}
// ---------------------------------------------------------------- create
export function ReceiptCreatePage() {
const { t } = useFeatureUi(strings);
const navigate = useNavigate();
const create = useCreateReceipt();
const [serverErrors, setServerErrors] = useState<Record<string, string>>({});
const mobile = useRef<string | null>(null);
const timer = useRef<number | undefined>(undefined);
const meta = useMemo(() => createForm(), []);
/** Legacy: entering the truck number filled trailer, driver number and name from the truck's grains permit; the driver number filled name and mobile. */
const onFieldChange = (name: string, value: unknown, patch: (v: Record<string, unknown>) => void) => {
if (name !== 'tn' && name !== 'nnpn') return;
window.clearTimeout(timer.current);
const text = String(value ?? '').trim();
if (text.length < 2) return;
timer.current = window.setTimeout(() => {
void (async () => {
if (name === 'tn') {
const g: ReceiptAutoFill | undefined = await fetchTruckFill(text);
if (g) patch({ trn: g.trn ?? '', nnpn: g.nnpn ?? '', drvr: g.drvr ?? '' });
return;
}
const d: ReceiptAutoFill | undefined = await fetchDriverFill(text);
if (d) { mobile.current = d.mobile ?? null; patch({ drvr: d.drvr ?? '' }); }
})();
}, 500);
};
const submit = (payload: Record<string, unknown>) =>
new Promise<void>((resolve) => {
setServerErrors({});
const body = { ...payload, scac: 327, credit: Number(payload.credit), receiptType: Number(payload.receiptType), mobile: mobile.current };
create.mutate(body, {
onSuccess: (res) => { resolve(); navigate(res.id ? `${ROOT}/${res.id}` : gridReturnUrl(ROOT), { replace: true }); },
onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); },
});
});
return (
<Stack spacing={2}>
<PageHeader title={t('rc.createTitle')} backTo={ROOT} />
<Alert severity="info">{t('rc.fill.help')}</Alert>
<MetaForm
meta={meta}
mode="create"
serverErrors={serverErrors}
onFieldChange={onFieldChange}
cancelLabel={t('rc.return')}
onCancel={() => navigate(gridReturnUrl(ROOT))}
onSubmit={submit}
/>
</Stack>
);
}
// ---------------------------------------------------------------- detail
function Slip({ data, innerRef }: { data: ReceiptPrint; innerRef: React.Ref<HTMLDivElement> }) {
const { t } = useFeatureUi(strings);
const r = data.receipt;
const now = new Date();
const p2 = (n: number) => String(n).padStart(2, '0');
const printDate = `${now.getFullYear()}-${p2(now.getMonth() + 1)}-${p2(now.getDate())} ${p2(now.getHours())}:${p2(now.getMinutes())}:${p2(now.getSeconds())}`;
const rows: [string, string][] = [
[t('rc.slip.pn'), String(r.pn ?? '')],
...(data.showCargo ? [[t('rc.slip.cargo'), r.cargoType ?? ''] as [string, string]] : []),
[t('rc.slip.tn'), r.tn ?? ''], [t('rc.slip.trn'), r.trn ?? ''], [t('rc.slip.driver'), r.drvr ?? ''], [t('rc.slip.nnpn'), r.nnpn ?? ''],
[t('rc.slip.description'), data.description],
];
return (
<Box ref={innerRef} dir="rtl" data-pdf-literal sx={{ width: 560, fontFamily: 'Arial, Tahoma, sans-serif', color: '#000', bgcolor: '#fff', p: 3 }}>
<Logo on="light" height={40} />
<Box sx={{ textAlign: 'center', fontSize: 20, mt: 1 }}>{r.companyName}</Box>
<Box sx={{ textAlign: 'center', fontSize: 15, borderBottom: '2px solid #000', pb: 1 }}>{data.firstMoveText}</Box>
<Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1.6fr', rowGap: 1.2, mt: 2, fontSize: 16 }}>
<Box>{t('rc.slip.number')}</Box>
<Box sx={{ textAlign: 'center' }}><Barcode value={String(r.receiptNo ?? '')} height={46} barWidth={2} /><Box dir="ltr">{r.receiptNo}</Box></Box>
{rows.map(([k, v]) => (<Box key={k} sx={{ display: 'contents' }}><Box>{k}</Box><Box>{v}</Box></Box>))}
</Box>
<Box sx={{ mt: 2, fontSize: 16, textAlign: 'center', borderTop: '2px solid #000', pt: 1.5 }}>
{r.credit === 0 ? t('rc.slip.note', { company: r.companyName ?? '', fees: r.fees ?? 0 }) : <b style={{ fontSize: 22 }}>{t('rc.slip.claim', { fees: r.fees ?? 0 })}</b>}
</Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', mt: 2, fontSize: 14 }}>
<Box>{t('rc.slip.printDate')}: <span dir="ltr">{printDate}</span></Box>
<Box sx={{ border: '1px solid #000', width: 220, height: 70, textAlign: 'center', fontSize: 13 }}>{t('rc.slip.stamp')}</Box>
</Box>
</Box>
);
}
function methodLabel(m: string | null, t: (k: never) => string) {
const key = `rc.method.${m ?? ''}`;
return key in strings ? (t as (k: string) => string)(key) : (m ?? '');
}
/** Movements of the receipt (legacy log grid, 5 per page; details = old and new values of the log row). */
function ReceiptLog({ id }: { id: number }) {
const { t } = useFeatureUi(strings);
const [open, setOpen] = useState(false);
const [page, setPage] = useState(0);
const [size, setSize] = useState(5);
const [shown, setShown] = useState<{ method: string; o: Record<string, string>; n: Record<string, string> } | null>(null);
const q = useReceiptLog(id, page + 1, size, open);
const rows = q.data?.items ?? [];
const head = { fontWeight: 700, textAlign: 'start' } as const;
const parse = (s: string | null): Record<string, string> => { try { return s ? (JSON.parse(s) as Record<string, string>) : {}; } catch { return {}; } };
const prop = (k: string) => { const key = `rc.prop.${k.toUpperCase() === 'RESULT' || k.toUpperCase() === 'REMARKS' ? k.toLowerCase() : k.toUpperCase()}`; return key in strings ? t(key as keyof typeof strings) : k; };
return (
<SectionPaper sx={{ p: 2 }}>
<Box role="button" tabIndex={0} aria-expanded={open} onClick={() => setOpen((o) => !o)} sx={{ cursor: 'pointer', '& h2': { mb: open ? 1.5 : 0 } }}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen((o) => !o); } }}>
<SectionTitle icon={HistoryIcon} title={t('rc.log')} />
</Box>
<Collapse in={open} unmountOnExit>
{q.isLoading ? <LoadingBanner /> : rows.length === 0 ? <Typography color="text.secondary">{t('rc.log.empty')}</Typography> : (
<>
<TableContainer component={Paper} variant="outlined">
<Table size="small">
<TableHead>
<TableRow>
<TableCell sx={head}>{t('rc.log.method')}</TableCell><TableCell sx={head}>{t('rc.log.date')}</TableCell>
<TableCell sx={head}>{t('rc.log.user')}</TableCell><TableCell sx={head}>{t('rc.log.details')}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((r) => {
const o = parse(r.oldData); const n = parse(r.newData); const keys = Object.keys({ ...o, ...n });
return (
<TableRow key={r.id}>
<TableCell sx={{ textAlign: 'start' }}>{methodLabel(r.methodName, t as unknown as (k: never) => string)}</TableCell>
<TableCell sx={{ textAlign: 'start' }}><bdi dir="ltr">{formatDateTime(r.logDate)}</bdi></TableCell>
<TableCell sx={{ textAlign: 'start' }}><bdi dir="ltr">{r.login}</bdi></TableCell>
<TableCell sx={{ textAlign: 'start' }}>
{keys.length > 0 && (
<Button size="small" startIcon={<ListAltIcon fontSize="small" />} onClick={() => setShown({ method: methodLabel(r.methodName, t as unknown as (k: never) => string), o, n })}>{t('rc.log.details')}</Button>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
<Pager count={q.data?.totalCount ?? 0} page={page} rowsPerPage={size} rowsPerPageOptions={[5, 10, 25]}
onPageChange={(_, p) => setPage(p)} onRowsPerPageChange={(e) => { setSize(Number(e.target.value)); setPage(0); }} />
</>
)}
</Collapse>
<Dialog open={shown !== null} onClose={() => setShown(null)} fullWidth maxWidth="sm">
<DialogTitle>{t('rc.log.details')}{shown ? ` - ${shown.method}` : ''}</DialogTitle>
<DialogContent>
{shown && (
<TableContainer component={Paper} variant="outlined">
<Table size="small">
<TableHead>
<TableRow>
<TableCell sx={head}>{t('rc.log.property')}</TableCell><TableCell sx={head}>{t('rc.log.old')}</TableCell><TableCell sx={head}>{t('rc.log.new')}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{Object.keys({ ...shown.o, ...shown.n }).map((k) => (
<TableRow key={k}>
<TableCell sx={{ textAlign: 'start', fontWeight: 600 }}>{prop(k)}</TableCell>
<TableCell sx={{ textAlign: 'start' }}>{shown.o[k] || '-'}</TableCell>
<TableCell sx={{ textAlign: 'start' }}>{shown.n[k] || '-'}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
</DialogContent>
<DialogActions><Button onClick={() => setShown(null)}>{t('common.close')}</Button></DialogActions>
</Dialog>
</SectionPaper>
);
}
function RevokeDialog({ open, busy, onClose, onSubmit }: { open: boolean; busy: boolean; onClose: () => void; onSubmit: (reason: number, note: string) => void }) {
const { t } = useFeatureUi(strings);
const lookups = useReceiptLookups();
const [reason, setReason] = useState('');
const [note, setNote] = useState('');
return (
<Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth="xs">
<DialogTitle>{t('rc.revoke.title')}</DialogTitle>
<DialogContent>
<TextField select fullWidth autoFocus margin="dense" label={t('rc.revoke.reason')} value={reason} onChange={(e) => setReason(e.target.value)} slotProps={{ select: { displayEmpty: true } }}>
<MenuItem value="" disabled>{t('rc.revoke.select')}</MenuItem>
{(lookups.data?.rejectReasons ?? []).map((x) => <MenuItem key={x.code} value={x.code ?? ''}>{x.name}</MenuItem>)}
</TextField>
<TextField fullWidth multiline minRows={2} margin="dense" label={t('rc.revoke.note')} value={note} onChange={(e) => setNote(e.target.value)} slotProps={{ htmlInput: { maxLength: 1500 } }} />
</DialogContent>
<DialogActions>
<Button color="inherit" onClick={onClose} disabled={busy}>{t('common.cancel')}</Button>
<Button color="error" variant="contained" disabled={busy || !reason} onClick={() => onSubmit(Number(reason), note)}>{t('rc.revoke.submit')}</Button>
</DialogActions>
</Dialog>
);
}
export function ReceiptPage() {
const { t } = useFeatureUi(strings);
const navigate = useNavigate();
const confirm = useConfirm();
const toast = useToast();
const params = useParams();
const id = params.id ? Number(params.id) : null;
const q = useReceipt(id);
const action = useReceiptAction();
const [revoking, setRevoking] = useState(false);
const [slip, setSlip] = useState<ReceiptPrint | null>(null);
const slipRef = useRef<HTMLDivElement>(null);
const meta = useMemo(() => detailForm(), []);
const d = q.data;
const initial = useMemo(() => (d ? receiptToValues(d.receipt, d.rejectReasonName) : {}), [d]);
if (q.isLoading) return <LoadingBanner />;
if (!d || id === null) return <Alert severity="error">{q.error?.message ?? t('rc.loadFailed')}</Alert>;
const { receipt, actions } = d;
const run = async (kind: 'confirm' | 'paid' | 'accept-revoke' | 'reject-revoke') => {
const key = kind === 'accept-revoke' ? 'rc.confirm.acceptRevoke' : kind === 'reject-revoke' ? 'rc.confirm.rejectRevoke' : kind === 'paid' ? 'rc.confirm.paid' : 'rc.confirm.confirm';
if (!(await confirm({ message: t(key) }))) return;
action.mutate({ id, action: kind }, { onSuccess: (res) => { if (kind === 'paid' && res.id) navigate(`${ROOT}/${res.id}`); else if (kind !== 'confirm') navigate(gridReturnUrl(ROOT)); } });
};
/** Legacy printPermitsReceipts: the server checks and logs, the slip is laid out here and saved as an A5 PDF. */
const print = async () => {
try {
const data = await printReceipt(id);
setSlip(data);
await new Promise((r) => window.setTimeout(r, 120));
const url = await elementToPdfUrl(slipRef.current!, 'portrait');
const a = document.createElement('a');
a.href = url; a.download = `${data.receipt.receiptNo}.pdf`;
document.body.appendChild(a); a.click(); a.remove();
} catch (e) {
toast.error(e instanceof Error ? e.message : t('rc.printFailed'));
} finally { setSlip(null); }
};
return (
<Stack spacing={2}>
<PageHeader
title={t('rc.detailTitle', { number: receipt.receiptNo ?? '' })}
status={<StatusChip value={receipt.statusCode} statuses={receiptStatuses} size="medium" />}
backTo={ROOT}
actions={(
<>
{actions.confirm && <Button variant="contained" color="success" startIcon={<CheckCircleIcon />} disabled={action.isPending} onClick={() => void run('confirm')}>{t('rc.action.confirm')}</Button>}
{actions.paid && <Button variant="contained" color="success" startIcon={<PaidIcon />} disabled={action.isPending} onClick={() => void run('paid')}>{t('rc.action.paid')}</Button>}
{actions.print && <Button variant="outlined" startIcon={<PrintIcon />} onClick={() => void print()}>{t('rc.action.print')}</Button>}
{actions.acceptRevoke && <Button variant="contained" color="error" onClick={() => void run('accept-revoke')}>{t('rc.action.acceptRevoke')}</Button>}
{actions.rejectRevoke && <Button variant="outlined" onClick={() => void run('reject-revoke')}>{t('rc.action.rejectRevoke')}</Button>}
{actions.revoke && <Button variant="outlined" color="error" startIcon={<BlockIcon />} disabled={action.isPending} onClick={() => setRevoking(true)}>{t('rc.action.revoke')}</Button>}
</>
)}
/>
<MetaForm
meta={meta}
mode="view"
initialValues={initial}
/>
<ReceiptLog id={id} />
<RevokeDialog
open={revoking} busy={action.isPending} onClose={() => setRevoking(false)}
onSubmit={(reason, note) => action.mutate({ id, action: 'revoke', body: { reason, note } }, { onSuccess: () => { setRevoking(false); navigate(gridReturnUrl(ROOT)); } })}
/>
{slip && <Box sx={{ position: 'fixed', insetInlineStart: -10000, top: 0 }}><Slip data={slip} innerRef={slipRef} /></Box>}
</Stack>
);
}
// ---------------------------------------------------------------- audit
export function ReceiptAuditPage() {
const { t } = useFeatureUi(strings);
const navigate = useNavigate();
const toast = useToast();
const [file, setFile] = useState<File | null>(null);
const [user, setUser] = useState('');
const [from, setFrom] = useState('');
const [to, setTo] = useState('');
const [timeFrom, setTimeFrom] = useState('');
const [timeTo, setTimeTo] = useState('');
const [busy, setBusy] = useState(false);
const input = useRef<HTMLInputElement>(null);
const run = async () => {
if (!file) { toast.warning(t('rc.audit.needFile')); return; }
if (!user.trim() && !from && !to) { toast.warning(t('rc.audit.needFilter')); return; }
const form = new FormData();
form.append('file', file);
if (user.trim()) form.append('confirmationBy', user.trim());
if (from) form.append('dateFrom', from);
if (to) form.append('dateTo', to);
if (timeFrom) form.append('timeFrom', timeFrom);
if (timeTo) form.append('timeTo', timeTo);
setBusy(true);
try {
const r = await runAudit(form);
toast.success(t('rc.audit.done', { compared: r.compared, advanced: r.advanced }));
} catch (e) { toast.error(e instanceof Error ? e.message : String(e)); }
finally { setBusy(false); }
};
return (
<Stack spacing={2}>
<PageHeader title={t('rc.audit.title')} backTo={ROOT} />
<Alert severity="info">{t('rc.audit.help')}</Alert>
<SectionPaper sx={{ p: 2 }}>
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: 'repeat(2, minmax(0, 1fr))' } }}>
<TextField label={t('rc.audit.user')} value={user} onChange={(e) => setUser(e.target.value)} slotProps={{ htmlInput: { dir: 'ltr' } }} />
<Box />
<TextField type="date" label={t('rc.audit.dateFrom')} value={from} onChange={(e) => setFrom(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} />
<TextField type="date" label={t('rc.audit.dateTo')} value={to} onChange={(e) => setTo(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} />
<TextField type="time" label={t('rc.audit.timeFrom')} value={timeFrom} onChange={(e) => setTimeFrom(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} />
<TextField type="time" label={t('rc.audit.timeTo')} value={timeTo} onChange={(e) => setTimeTo(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} />
</Box>
<Stack direction="row" spacing={1.5} useFlexGap sx={{ mt: 2, alignItems: 'center', flexWrap: 'wrap' }}>
<input ref={input} type="file" hidden accept=".xlsx" onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
<Button variant="outlined" startIcon={<UploadFileIcon />} onClick={() => input.current?.click()}>{t('rc.audit.choose')}</Button>
<Typography variant="body2" dir="ltr">{file?.name ?? ''}</Typography>
</Stack>
<Stack direction="row" spacing={1.5} sx={{ mt: 2 }}>
<Button variant="contained" disabled={busy} startIcon={<FactCheckIcon />} onClick={() => void run()}>{t('rc.audit.run')}</Button>
<Button color="inherit" onClick={() => navigate(gridReturnUrl(ROOT))}>{t('rc.return')}</Button>
</Stack>
</SectionPaper>
</Stack>
);
}

View File

@ -0,0 +1,17 @@
import type { RouteObject } from 'react-router-dom';
import ReceiptLongIcon from '@mui/icons-material/ReceiptLong';
import type { MenuItem } from '@/shell/types';
import { ReceiptAuditPage, ReceiptCreatePage, ReceiptPage, ReceiptsPage } from './pages';
import strings from './strings';
/** Permit receipts (سندات القبض والمطالبات المالية), ported from the AqabaTCS menu entry MENU.PERMITSRECEIPTS. Keys: db/receipts-permissions.sql. */
export const routes: RouteObject[] = [
{ path: '/receipts', element: <ReceiptsPage /> },
{ path: '/receipts/new', element: <ReceiptCreatePage />, handle: { crumb: strings['rc.crumb.new'] } },
{ path: '/receipts/audit', element: <ReceiptAuditPage />, handle: { crumb: strings['rc.crumb.audit'] } },
{ path: '/receipts/:id', element: <ReceiptPage />, handle: { crumb: strings['rc.crumb.details'] } },
];
export const menu: MenuItem[] = [
{ key: 'receipts', title: strings['rc.menu'], icon: ReceiptLongIcon, path: '/receipts', createPath: '/receipts/new', createKey: 'receipts.create' },
];

View File

@ -0,0 +1,181 @@
import { defineStrings } from '@/i18n/useUi';
/** Strings of the permit receipts screens (legacy captions MENU.PERMITSRECEIPTS, PERMITSRECEIPTS.*, PUBLIC.*, verbatim in Arabic). */
export default defineStrings({
'rc.menu': { en: 'Receipts and financial claims', ar: 'سندات القبض والمطالبات المالية' },
'rc.title': { en: 'Receipts and financial claims', ar: 'سندات القبض والمطالبات المالية' },
'rc.subtitle': { en: 'Cash receipts and financial claims of the permits', ar: 'سندات القبض والمطالبات المالية للتصاريح' },
'rc.new': { en: 'New receipt', ar: 'وصل جديد' },
'rc.createTitle': { en: 'New receipt', ar: 'وصل جديد' },
'rc.detailTitle': { en: 'Receipt {number}', ar: 'الوصل {number}' },
'rc.crumb.new': { en: 'New', ar: 'جديد' },
'rc.crumb.details': { en: 'Details', ar: 'التفاصيل' },
'rc.crumb.audit': { en: 'Audit', ar: 'تدقيق' },
'rc.loadFailed': { en: 'The receipt could not be loaded.', ar: 'تعذر تحميل الوصل.' },
'rc.return': { en: 'Back', ar: 'عودة' },
'rc.export': { en: 'Excel', ar: 'تصدير Excel' },
// statuses (PERMITSRECEIPTS.STATUS.*)
'rc.status.NOT_RECEIVED': { en: 'Not received', ar: 'غير مستلم' },
'rc.status.RECEIVED': { en: 'Received', ar: 'مستلم' },
'rc.status.UNPAID': { en: 'Unpaid', ar: 'غير مسدد' },
'rc.status.PAID': { en: 'Paid', ar: 'مسدد' },
'rc.status.AUDITED': { en: 'Audited', ar: 'مدقق' },
'rc.status.COMPLETED': { en: 'Completed', ar: 'مكتمل' },
'rc.status.PENDING_RVKD': { en: 'Cancellation pending', ar: 'قيد الالغاء' },
'rc.status.RVKD': { en: 'Cancelled', ar: 'ملغي' },
// fields
'rc.f.receiptNo': { en: 'Number', ar: 'الرقم' },
'rc.f.pn': { en: 'Permit number', ar: 'رقم التصريح' },
'rc.f.company': { en: 'Company', ar: 'اسم الشركة' },
'rc.f.cargoType': { en: 'Cargo type', ar: 'النمط' },
'rc.f.shipmentMode': { en: 'Cargo type', ar: 'النمط' },
'rc.f.shipmentModeHelp': { en: 'For a double permit: the second move cargo type.', ar: 'للتصريح المزدوج: نمط الحركة الثانية.' },
'rc.f.fmShipmentMode': { en: 'First move cargo type', ar: 'نمط الحركة الاولى' },
'rc.f.smShipmentMode': { en: 'Second move cargo type', ar: 'نمط الحركة الثانية' },
'rc.f.tn': { en: 'Truck', ar: 'رقم الشاحنة' },
'rc.f.trn': { en: 'Trailer', ar: 'رقم المقطورة' },
'rc.f.drvr': { en: 'Driver name', ar: 'اسم السائق' },
'rc.f.nnpn': { en: 'National number', ar: 'الرقم الوطني' },
'rc.f.mobile': { en: 'Mobile', ar: 'الموبايل' },
'rc.f.dln': { en: 'Driving licence no.', ar: 'رقم رخصة السائق' },
'rc.f.dled': { en: 'Driving licence expiry', ar: 'تاريخ انتهاء رخصة السائق' },
'rc.f.fees': { en: 'Fees', ar: 'الأجور' },
'rc.f.credit': { en: 'Kind', ar: 'النوع' },
'rc.f.onCredit': { en: 'On credit (financial claim)', ar: 'على الذمة (مطالبة مالية)' },
'rc.f.receiptType': { en: 'Receipt type', ar: 'نوع الوصل' },
'rc.f.creationDate': { en: 'Created', ar: 'تاريخ الانشاء' },
'rc.f.createdBy': { en: 'Created by', ar: 'إنشاء بواسطة' },
'rc.f.confirmationDate': { en: 'Confirmation date', ar: 'تاريخ التأكيد' },
'rc.f.confirmationBy': { en: 'Confirmed by', ar: 'تأكيد بواسطة' },
'rc.f.status': { en: 'Status', ar: 'الحالة' },
'rc.f.source': { en: 'Payment way', ar: 'طريقة الدفع' },
'rc.f.rejectReason': { en: 'Cancellation reason', ar: 'سبب الإلغاء' },
'rc.f.rejectNote': { en: 'Cancellation note', ar: 'ملاحظات الإلغاء' },
'rc.f.createDateFrom': { en: 'Created from', ar: 'من تاريخ الانشاء' },
'rc.f.createDateTo': { en: 'Created to', ar: 'الى تاريخ الانشاء' },
'rc.f.permitStatus': { en: 'Permit status', ar: 'حالة التصريح' },
'rc.kind.0': { en: 'Cash receipt', ar: 'سند قبض' },
'rc.kind.1': { en: 'Financial claim', ar: 'مطالبة مالية' },
'rc.source.0': { en: 'Cash', ar: 'نقداً' },
'rc.source.1': { en: 'Electronic payment', ar: 'دفع الالكتروني' },
'rc.yes': { en: 'Yes', ar: 'نعم' },
'rc.no': { en: 'No', ar: 'لا' },
'rc.sec.receipt': { en: 'Receipt', ar: 'الوصل' },
'rc.sec.vehicle': { en: 'Truck and driver', ar: 'الشاحنة والسائق' },
'rc.sec.record': { en: 'Record', ar: 'معلومات السجل' },
'rc.digits': { en: 'Digits only', ar: 'الحقل لا يقبل أحرف' },
// actions
'rc.action.confirm': { en: 'Confirm', ar: 'تأكيد الوصل' },
'rc.action.paid': { en: 'Paid', ar: 'تأكيد استلام نقد' },
'rc.action.print': { en: 'Print', ar: 'طباعة' },
'rc.action.revoke': { en: 'Cancel', ar: 'الغاء' },
'rc.action.acceptRevoke': { en: 'Approve cancellation', ar: 'موافقة على الالغاء' },
'rc.action.rejectRevoke': { en: 'Reject cancellation', ar: 'رفض الالغاء' },
'rc.action.save': { en: 'Update', ar: 'تعديل' },
'rc.confirm.confirm': { en: 'Confirm this receipt?', ar: 'هل تريد تأكيد الوصل؟' },
'rc.confirm.paid': { en: 'Confirm that the cash was received? A cash receipt is created.', ar: 'هل تريد تأكيد استلام النقد؟ سيتم انشاء سند قبض.' },
'rc.confirm.acceptRevoke': { en: 'Approve the cancellation?', ar: 'هل تريد الموافقة على الالغاء؟' },
'rc.confirm.rejectRevoke': { en: 'Reject the cancellation? The receipt returns to received.', ar: 'هل تريد رفض الالغاء؟ سيعود الوصل الى مستلم.' },
'rc.revoke.title': { en: 'Cancel the receipt', ar: 'الغاء الوصل' },
'rc.revoke.reason': { en: 'Reason', ar: 'سبب الإلغاء' },
'rc.revoke.select': { en: 'Choose the reason', ar: 'يجب اختيار سبب الرفض' },
'rc.revoke.note': { en: 'Notes', ar: 'ملاحظات' },
'rc.revoke.submit': { en: 'Cancel the receipt', ar: 'الغاء الوصل' },
'rc.printFailed': { en: 'The slip could not be created.', ar: 'تعذر انشاء الوصل للطباعة.' },
// create form helpers
'rc.fill.help': { en: 'Enter the truck number to fill the trailer, driver number and name from its grains permit; the driver number fills the name.', ar: 'عند ادخال رقم الشاحنة تتم تعبئة رقم المقطورة والرقم الوطني واسم السائق من تصريح الشاحنة، وعند ادخال الرقم الوطني تتم تعبئة اسم السائق.' },
'rc.fill.title': { en: 'Fill from the system', ar: 'تعبئة من النظام' },
'rc.fill.truck': { en: 'Truck number', ar: 'رقم الشاحنة' },
'rc.fill.nnpn': { en: 'Driver national number', ar: 'الرقم الوطني للسائق' },
'rc.fill.go': { en: 'Fill', ar: 'تعبئة' },
'rc.fill.none': { en: 'Nothing found for these numbers.', ar: 'لا يوجد معلومات' },
'rc.fill.gnpn': { en: 'Grains permit {pn} found for the truck.', ar: 'تم ايجاد التصريح {pn} للشاحنة.' },
// log
'rc.log': { en: 'Movements log', ar: 'سجل الحركات' },
'rc.log.empty': { en: 'No movements', ar: 'لا يوجد معلومات' },
'rc.log.method': { en: 'Movement', ar: 'نوع الحركة' },
'rc.log.date': { en: 'Date', ar: 'تاريخ التعديل' },
'rc.log.user': { en: 'User', ar: 'اسم المستخدم' },
'rc.log.details': { en: 'Details', ar: 'التفاصيل' },
'rc.log.property': { en: 'Property', ar: 'نوع الحركة' },
'rc.log.old': { en: 'Old data', ar: 'البيانات القديمة' },
'rc.log.new': { en: 'New data', ar: 'البيانات الجديدة' },
'rc.method.CONFIRM': { en: 'Confirmed', ar: 'تأكيد الوصل' },
'rc.method.PAID': { en: 'Paid', ar: 'دفع' },
'rc.method.CREATE': { en: 'Created', ar: 'إنشاء' },
'rc.method.PRINT': { en: 'Printed', ar: 'طباعة' },
'rc.method.REVOKE': { en: 'Cancelled', ar: 'الغاء' },
'rc.method.ACCEPT_REVOKE': { en: 'Cancellation approved', ar: 'موافقة على الالغاء' },
'rc.method.REJECT_REVOKE': { en: 'Cancellation rejected', ar: 'رفض الالغاء' },
'rc.method.AUDIT': { en: 'Audit', ar: 'تدقيق سندات القبض المالية' },
'rc.method.FIN_AUDIT': { en: 'Financial audit', ar: 'تدقيق مالي' },
'rc.prop.SCAC': { en: 'Company code', ar: 'رقم الشركة' },
'rc.prop.FEES': { en: 'Fees', ar: 'الأجور' },
'rc.prop.FMSHIPMENTMODE': { en: 'First move cargo', ar: 'نمط الحركة الاولى' },
'rc.prop.SHIPMENTMODE': { en: 'Cargo type', ar: 'النمط' },
'rc.prop.TN': { en: 'Truck', ar: 'رقم الشاحنة' },
'rc.prop.TRN': { en: 'Trailer', ar: 'رقم المقطورة' },
'rc.prop.DLN': { en: 'Driving licence no.', ar: 'رقم رخصة السائق' },
'rc.prop.DLED': { en: 'Driving licence expiry', ar: 'تاريخ انتهاء رخصة السائق' },
'rc.prop.NNPN': { en: 'National number', ar: 'الرقم الوطني' },
'rc.prop.DRVR': { en: 'Driver name', ar: 'اسم السائق' },
'rc.prop.MOBILE': { en: 'Mobile', ar: 'الموبايل' },
'rc.prop.PN': { en: 'Permit number', ar: 'رقم التصريح' },
'rc.prop.CRN': { en: 'Loading order no.', ar: 'رقم إذن التحميل' },
'rc.prop.CA_CODE': { en: 'Clearing agent', ar: 'رقم المخلص' },
'rc.prop.CREATIONDATE': { en: 'Created', ar: 'تاريخ الانشاء' },
'rc.prop.CREATION_DATE': { en: 'Created', ar: 'تاريخ الانشاء' },
'rc.prop.CREATED_BY': { en: 'Created by', ar: 'إنشاء بواسطة' },
'rc.prop.CONFIRMATION_BY': { en: 'Confirmed by', ar: 'تأكيد بواسطة' },
'rc.prop.RECEIPT_TYPE': { en: 'Receipt type', ar: 'نوع الوصل' },
'rc.prop.CREDIT': { en: 'Kind', ar: 'النوع' },
'rc.prop.RECEIPT_NO': { en: 'Number', ar: 'الرقم' },
'rc.prop.INBOUNDTYPECODE': { en: 'Operation type', ar: 'نوع العملية' },
'rc.prop.FMINBOUNDTYPECODE': { en: 'First move operation', ar: 'عملية الحركة الاولى' },
'rc.prop.ORIGINADDRESSID': { en: 'Entry centre', ar: 'مركز الدخول' },
'rc.prop.DESTINATIONADDRESSID': { en: 'Exit centre', ar: 'مركز الخروج' },
'rc.prop.PERMIT_STATUS': { en: 'Permit status', ar: 'حالة التصريح' },
'rc.prop.REJECT_REASON': { en: 'Cancellation reason', ar: 'سبب الإلغاء' },
'rc.prop.STATUSCODE': { en: 'Status', ar: 'الحالة' },
'rc.prop.NOTES': { en: 'Notes', ar: 'ملاحظات' },
'rc.prop.result': { en: 'Result', ar: 'النتيجة' },
'rc.prop.remarks': { en: 'Remarks', ar: 'الملاحظات' },
// slip
'rc.slip.number': { en: 'Number', ar: 'الرقم' },
'rc.slip.pn': { en: 'Permit number', ar: 'رقم التصريح' },
'rc.slip.cargo': { en: 'Cargo type', ar: 'النمط' },
'rc.slip.tn': { en: 'Truck', ar: 'رقم الشاحنة' },
'rc.slip.trn': { en: 'Trailer', ar: 'رقم المقطورة' },
'rc.slip.driver': { en: 'Driver name', ar: 'اسم السائق' },
'rc.slip.nnpn': { en: 'National number', ar: 'الرقم الوطني' },
'rc.slip.description': { en: 'Permit description', ar: 'وصف التصريح' },
'rc.slip.note': { en: 'I, the representative of {company}, received {fees} dinars for leak and transport document services.', ar: 'استلمت أنا مندوب {company} مبلغ مالي بمقدار {fees} دينار بدل خدمات تسريب و وثيقة نقل' },
'rc.slip.claim': { en: '{fees} dinars / on credit', ar: '{fees} دينار / ذمم' },
'rc.slip.printDate': { en: 'Print date', ar: 'تاريخ الطباعة' },
'rc.slip.stamp': { en: 'Company stamp / employee signature', ar: 'ختم الشركة \\ توقيع الموظف' },
// audit
'rc.audit.menu': { en: 'Audit', ar: 'تدقيق سندات القبض المالية' },
'rc.audit.title': { en: 'Receipts audit', ar: 'تدقيق سندات القبض المالية' },
'rc.audit.help': {
en: 'Upload the permits Excel file (.xlsx). The receipts confirmed by the user / in the period are compared with it; those that match move to the next status, and a result file is downloaded.',
ar: 'ارفع ملف معلومات التصاريح (.xlsx). تتم مقارنة الوصولات التي أكدها المستخدم او ضمن الفترة مع الملف، وتنتقل المطابقة منها الى الحالة التالية، ويتم تنزيل ملف النتيجة.',
},
'rc.audit.user': { en: 'Confirmed by (login)', ar: 'تأكيد بواسطة' },
'rc.audit.dateFrom': { en: 'Confirmed from', ar: 'من تاريخ التأكيد' },
'rc.audit.dateTo': { en: 'Confirmed to', ar: 'الى تاريخ التأكيد' },
'rc.audit.timeFrom': { en: 'From time', ar: 'من الساعة' },
'rc.audit.timeTo': { en: 'To time', ar: 'الى الساعة' },
'rc.audit.file': { en: 'Permits file', ar: 'ملف التصاريح' },
'rc.audit.choose': { en: 'Choose the file', ar: 'اختر الملف' },
'rc.audit.run': { en: 'Audit', ar: 'تدقيق' },
'rc.audit.needFile': { en: 'Upload the permits file first.', ar: 'يرجى اضافة ملف معلومات التصاريح لغاية الدقيق' },
'rc.audit.needFilter': { en: 'Fill the user or both dates.', ar: 'يجب تعبئة احد حقول الفلترة (المستخدم او التاريخ)' },
'rc.audit.done': { en: '{compared} receipts compared, {advanced} moved to the next status. The result file was downloaded.', ar: 'تمت مقارنة {compared} وصل، وانتقل {advanced} منها الى الحالة التالية. تم تنزيل ملف النتيجة.' },
});

View File

@ -0,0 +1,150 @@
import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { API_BASE, api, getToken } from '@/api/client';
import { useWrite } from '@/api/hooks';
import { gridKey } from '@/components/DataGrid';
import type { OptionItem, OptionsLoader } from '@/components/meta/types';
export type RegistrarKind = 'drivers' | 'trucks' | 'trailers';
export const KINDS: RegistrarKind[] = ['drivers', 'trucks', 'trailers'];
export const baseOf = (kind: RegistrarKind) => `/registrar/${kind}`;
export const gridOf = (kind: RegistrarKind) => `registrar.${kind}`;
/** Row of DRIVERS_INFO / TRUCKS_INFO / TRAILERS_INFO (one shape for the three; columns a table does not have are null). */
export interface RegistrarRecord {
id: number;
statusCode: string | null;
plateNo: string | null;
plateCode: string | null;
nationality: string | null;
nnpn: string | null;
nameAr: string | null;
nameEn: string | null;
dateOfBirth: string | null;
bloodGroup: string | null;
address: string | null;
licenseType: string | null;
licenseIssueDate: string | null;
mobile: string | null;
licenseNo: string | null;
licenseExpiryDate: string | null;
licenseRegistrationNo: string | null;
manufacturer: string | null;
manufactureYear: number | null;
vehicleType: string | null;
category: string | null;
color: string | null;
secondaryColor: string | null;
model: string | null;
vinNumber: string | null;
engineNumber: string | null;
loadingWeight: number | null;
grossWeight: number | null;
emptyWeight: number | null;
ownerName: string | null;
ownerNnpn: string | null;
ownerPhoneNumber: number | null;
ownerAddress: string | null;
governate: string | null;
notes: string | null;
revokeReason: string | null;
createdBy: string | null;
creationDate: string | null;
updatedBy: string | null;
lastUpdateDate: string | null;
}
export interface RegistrarAttachment {
id: number;
fileName: string;
}
export interface RegistrarActions {
update: boolean;
complete: boolean;
revoke: boolean;
reopen: boolean;
}
export interface RegistrarDetail {
record: RegistrarRecord;
attachments: RegistrarAttachment[];
actions: RegistrarActions;
}
export interface RegistrarResult {
message: string;
}
interface LookupItem {
code: string;
ar: string;
en: string;
}
// ---------------------------------------------------------------- lists
let listsCache: { at: number; promise: Promise<Record<string, LookupItem[]>> } | null = null;
/** One request serves the twelve lists of the forms (each select asks for its own list). */
function loadLists(): Promise<Record<string, LookupItem[]>> {
if (!listsCache || Date.now() - listsCache.at > 60_000) {
const promise = api.get<{ lists: Record<string, LookupItem[]> }>('/registrar/lookups').then((r) => r.lists);
promise.catch(() => { listsCache = null; });
listsCache = { at: Date.now(), promise };
}
return listsCache.promise;
}
export function listOptions(list: string): OptionsLoader {
return {
key: `registrar.${list}`,
load: async () => (await loadLists())[list]?.map((i): OptionItem => ({ value: i.code, label: { en: i.en, ar: i.ar } })) ?? [],
};
}
/** The same lists as plain data (revoke dialog, code to name in the grids). */
export function useRegistrarLists() {
return useQuery({ queryKey: ['registrar.lists'], queryFn: loadLists, staleTime: 5 * 60_000 });
}
// ---------------------------------------------------------------- record
export const recordKey = (kind: RegistrarKind, id: number | null) => ['registrar.one', kind, id];
export const useRegistrarRecord = (kind: RegistrarKind, id: number | null) =>
useQuery({ queryKey: recordKey(kind, id), queryFn: () => api.get<RegistrarDetail>(`${baseOf(kind)}/${id}`), enabled: id !== null });
const keys = (kind: RegistrarKind) => [gridKey(gridOf(kind)), ['registrar.one', kind]];
export const useRegistrarUpdate = (kind: RegistrarKind) =>
useWrite((v: { id: number; body: Record<string, unknown> }) => api.put<RegistrarResult>(`${baseOf(kind)}/${v.id}`, v.body), { invalidate: keys(kind) });
export const useRegistrarAction = (kind: RegistrarKind) =>
useWrite(
(v: { id: number; action: 'complete' | 'reopen' | 'revoke'; reason?: string }) =>
api.post<RegistrarResult>(`${baseOf(kind)}/${v.id}/${v.action}`, v.action === 'revoke' ? { reason: v.reason } : undefined),
{ invalidate: keys(kind) },
);
// ---------------------------------------------------------------- pictures
/**
* A picture of the record as an object URL. The API serves it after the permission check (it needs the bearer token, which an img tag cannot send),
* so it is fetched here; the page only allows own and blob images.
*/
export function useAttachmentImage(kind: RegistrarKind, id: number, attachmentId: number) {
const [state, setState] = useState<{ url?: string; failed?: boolean }>({});
useEffect(() => {
let alive = true;
let objectUrl: string | undefined;
const token = getToken();
fetch(`${API_BASE}${baseOf(kind)}/${id}/attachments/${attachmentId}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} })
.then((res) => (res.ok ? res.blob() : Promise.reject(new Error(String(res.status)))))
.then((blob) => { objectUrl = URL.createObjectURL(blob); if (alive) setState({ url: objectUrl }); })
.catch(() => { if (alive) setState({ failed: true }); });
return () => { alive = false; if (objectUrl) URL.revokeObjectURL(objectUrl); };
}, [kind, id, attachmentId]);
return state;
}

View File

@ -0,0 +1,196 @@
import type { FieldMeta, FilterMeta, FormMeta, GridMeta, OptionItem, Rule, StatusMeta } from '@/components/meta/types';
import strings from './strings';
import { gridOf, baseOf, listOptions, type RegistrarKind, type RegistrarRecord } from './api';
const s = strings;
export const registrarStatuses: StatusMeta[] = [
{ value: 'PENDING', label: s['rg.status.PENDING'], color: 'warning' },
{ value: 'COMPLETED', label: s['rg.status.COMPLETED'], color: 'success' },
{ value: 'INCOMPLETE', label: s['rg.status.INCOMPLETE'], color: 'default' },
{ value: 'REVOKE', label: s['rg.status.REVOKE'], color: 'error' },
];
const numberLabel = { drivers: s['rg.f.nnpn'], trucks: s['rg.f.plateTruck'], trailers: s['rg.f.plateTrailer'] } as const;
/**
* Legacy DRIVERINFOGRID / TRUCKINFOGRID / TRAILERINFOGRID: number, licence, name (owner), created, status; the screen opens on the PENDING records.
* Filters: number (NNPN / TN / TRN), licence, name (drivers) or owner (trucks, trailers), chassis number (trucks, trailers), creation dates.
*/
export function registrarGrid(kind: RegistrarKind, h: { onOpen: (r: RegistrarRecord) => void }): GridMeta<RegistrarRecord> {
const driver = kind === 'drivers';
const filters: FilterMeta[] = [
{ name: 'number', type: 'text', label: numberLabel[kind], ltr: true },
{ name: 'licenseNo', type: 'text', label: s['rg.f.licenseNo'], ltr: true },
driver
? { name: 'name', type: 'text', label: s['rg.f.nameAr'] }
: { name: 'ownerName', type: 'text', label: s['rg.f.ownerName'] },
...(driver ? [] : [{ name: 'vinNumber', type: 'text', label: s['rg.f.vinNumber'], ltr: true } as FilterMeta]),
{ name: 'createDateFrom', type: 'date', label: s['rg.f.createDateFrom'] },
{ name: 'createDateTo', type: 'date', label: s['rg.f.createDateTo'] },
];
return {
key: gridOf(kind),
endpoint: baseOf(kind),
rowKey: (r) => r.id,
onRowClick: h.onOpen,
pageSize: 16,
emptyAsGrid: true,
defaultFilters: { statusCode: 'PENDING' },
status: { param: 'statusCode', options: registrarStatuses },
filters,
columns: [
driver
? { key: 'nnpn', header: s['rg.f.nnpn'], ltr: true }
: { key: 'plateNo', header: numberLabel[kind], ltr: true },
{ key: 'licenseNo', header: s['rg.f.licenseNo'], ltr: true },
driver
? { key: 'name', header: s['rg.f.name'], render: (r) => r.nameAr || r.nameEn || '' }
: { key: 'ownerName', header: s['rg.f.ownerName'] },
{ key: 'creationDate', header: s['rg.f.creationDate'], format: 'date' },
{ key: 'statusCode', header: s['rg.f.status'], format: 'status', statuses: registrarStatuses },
],
};
}
// ---------------------------------------------------------------- forms
/** Legacy form: the fields with the `required` class, minus the ones skipped for foreign registrations (*_excludedVaildFieldsArr). */
const JORDAN: Rule = { field: 'nationality', op: 'eq', value: 'jo' };
const FOREIGN_CODE_VISIBLE: Rule = { any: [{ field: 'nationality', op: 'eq', value: 'jo' }, { field: 'nationality', op: 'empty' }] };
const text = (name: string, label: FieldMeta['label'], extra: Partial<FieldMeta> = {}): FieldMeta => ({ name, type: 'text', label, ...extra });
const select = (name: string, label: FieldMeta['label'], list: string, extra: Partial<FieldMeta> = {}): FieldMeta =>
({ name, type: 'select', label, options: listOptions(list), ...extra });
const needJo = { requiredWhen: JORDAN } as const;
const digits = { regex: /^\d+$/, message: s['rg.digits'] };
/** Years from this year down to 1941, with the legacy "not entered" (0) first. */
function yearOptions() {
const out: OptionItem[] = [{ value: '0', label: s['rg.f.noEntry'] }];
for (let y = new Date().getFullYear(); y > 1940; y--) out.push({ value: String(y), label: String(y) });
return out;
}
const recordFields = (): FieldMeta[] => [
text('createdBy', s['rg.f.createdBy'], { readOnly: true, ltr: true, hiddenOnCreate: true }),
text('creationDate', s['rg.f.creationDate'], { readOnly: true, ltr: true, hiddenOnCreate: true }),
text('updatedBy', s['rg.f.updatedBy'], { readOnly: true, ltr: true, hiddenOnCreate: true }),
text('lastUpdateDate', s['rg.f.lastUpdateDate'], { readOnly: true, ltr: true, hiddenOnCreate: true }),
];
function driverForm(): FormMeta {
return {
key: 'registrar.drivers.form',
sections: [
{
key: 'main', title: s['rg.sec.main'], columns: 2,
fields: [
select('nationality', s['rg.f.nationality'], 'NATIONALITY', { required: true }),
text('nnpn', s['rg.f.nnpn'], { required: true, maxLength: 20, inputKind: 'code' }),
text('nameAr', s['rg.f.nameAr'], { maxLength: 300, helper: s['rg.nameHint'], pattern: { regex: /^[ء-ي ]*$/, message: s['rg.arabicOnly'] } }),
text('nameEn', s['rg.f.nameEn'], { maxLength: 300, pattern: { regex: /^[a-zA-Z ]+$/, message: s['rg.englishOnly'] } }),
text('mobile', s['rg.f.mobile'], { maxLength: 14, inputKind: 'phone', pattern: digits }),
{ name: 'dateOfBirth', type: 'date', label: s['rg.f.dateOfBirth'], ...needJo },
select('bloodGroup', s['rg.f.bloodGroup'], 'BLOOD_GROUP', needJo),
select('governate', s['rg.f.governate'], 'JORDAN_GOVERNATE', needJo),
text('address', s['rg.f.address'], { maxLength: 750, span: 'full', ...needJo }),
],
},
{
key: 'licence', title: s['rg.sec.licence'], columns: 2,
fields: [
text('licenseNo', s['rg.f.licenseNo'], { required: true, maxLength: 20, inputKind: 'code' }),
select('licenseType', s['rg.f.licenseType'], 'DRIVER_LICENSE_TYPE', { required: true }),
{ name: 'licenseIssueDate', type: 'date', label: s['rg.f.licenseIssueDate'], ...needJo },
{ name: 'licenseExpiryDate', type: 'date', label: s['rg.f.licenseExpiryDate'], ...needJo },
{ name: 'notes', type: 'textarea', label: s['rg.f.notes'], maxLength: 250, rows: 4, span: 'full' },
],
},
{ key: 'record', title: s['rg.sec.record'], columns: 2, fields: [...revokeField('DRIVER_REVOKE_REASON'), ...recordFields()] },
],
};
}
/** Truck and trailer form: the same layout; a trailer has no vehicle class, its category is optional and its engine number and load are not required. */
function vehicleForm(kind: 'trucks' | 'trailers'): FormMeta {
const truck = kind === 'trucks';
return {
key: `registrar.${kind}.form`,
sections: [
{
key: 'main', title: s['rg.sec.main'], columns: 2,
fields: [
select('nationality', s['rg.f.nationality'], 'NATIONALITY', { required: true }),
text('plateNo', truck ? s['rg.f.plateTruck'] : s['rg.f.plateTrailer'], { required: true, maxLength: 45, inputKind: 'plate' }),
text('plateCode', truck ? s['rg.f.plateCodeTruck'] : s['rg.f.plateCodeTrailer'], { maxLength: 45, inputKind: 'code', hiddenWhen: FOREIGN_CODE_VISIBLE }),
],
},
{
key: 'owner', title: s['rg.sec.owner'], columns: 2,
fields: [
text('ownerName', s['rg.f.ownerName'], { maxLength: 500, ...needJo }),
select('governate', s['rg.f.governate'], 'JORDAN_GOVERNATE', needJo),
text('ownerAddress', s['rg.f.ownerAddress'], { maxLength: 750, span: 'full', ...needJo }),
],
},
{
key: 'vehicle', title: s['rg.sec.vehicle'], columns: 2,
fields: [
select('manufacturer', s['rg.f.manufacturer'], 'VEHICLE_MANIFACTURER', { required: true }),
text('model', s['rg.f.model'], { maxLength: truck ? 60 : 20, inputKind: 'code', ...(truck ? needJo : { required: true }) }),
select('color', s['rg.f.color'], 'COLOR', truck ? { required: true } : needJo),
select('secondaryColor', s['rg.f.secondaryColor'], 'COLOR'),
...(truck ? [select('vehicleType', s['rg.f.vehicleType'], 'TRUCK_TYPE', needJo)] : []),
{ name: 'manufactureYear', type: 'select', label: s['rg.f.manufactureYear'], options: yearOptions(), ...needJo },
select('category', s['rg.f.category'], truck ? 'TRUCK_USAGE_TYPE' : 'TRAILER_USAGE_TYPE', truck ? needJo : {}),
text('vinNumber', s['rg.f.vinNumber'], { maxLength: 50, inputKind: 'code', ...needJo }),
text('engineNumber', s['rg.f.engineNumber'], { maxLength: 50, inputKind: 'code', ...(truck ? needJo : {}) }),
text('loadingWeight', s['rg.f.loadingWeight'], { maxLength: 12, inputKind: 'code', pattern: digits, ...(truck ? needJo : {}) }),
text('grossWeight', s['rg.f.grossWeight'], { maxLength: 12, inputKind: 'code', pattern: digits, ...needJo }),
],
},
{
key: 'licence', title: s['rg.sec.licence'], columns: 2,
fields: [
text('licenseNo', s['rg.f.licenseNo'], { maxLength: 20, inputKind: 'code', ...needJo }),
text('licenseRegistrationNo', s['rg.f.licenseRegistrationNo'], { maxLength: 20, inputKind: 'code', ...needJo }),
{ name: 'licenseExpiryDate', type: 'date', label: s['rg.f.licenseExpiryDate'], ...needJo },
{ name: 'notes', type: 'textarea', label: s['rg.f.notes'], maxLength: 250, rows: 4, span: 'full' },
],
},
{ key: 'record', title: s['rg.sec.record'], columns: 2, fields: [...revokeField(truck ? 'TRUCK_REVOKE_REASON' : 'TRAILER_REVOKE_REASON'), ...recordFields()] },
],
};
}
/** The rejection reason of a rejected record (read only; the reject dialog sets it). */
function revokeField(list: string): FieldMeta[] {
return [select('revokeReason', s['rg.f.revokeReason'], list, { readOnly: true, span: 'full', hiddenWhen: { field: 'revokeReason', op: 'empty' } })];
}
export function registrarForm(kind: RegistrarKind): FormMeta {
return kind === 'drivers' ? driverForm() : vehicleForm(kind);
}
// ---------------------------------------------------------------- record <-> form values
const DATE_FIELDS = ['dateOfBirth', 'licenseIssueDate', 'licenseExpiryDate'] as const;
const pad = (n: number) => String(n).padStart(2, '0');
/** dd/mm/yyyy hh:mm:ss, the legacy view format; left to right in the page. */
const stamp = (v: string | null) => {
if (!v) return '';
const d = new Date(v);
if (Number.isNaN(d.getTime())) return v;
return `${pad(d.getDate())}/${pad(d.getMonth() + 1)}/${d.getFullYear()} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};
/** Form values of a record: dates as yyyy-mm-dd, numbers as text, the stamps formatted. */
export function recordToValues(r: RegistrarRecord): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(r)) out[k] = v === null || v === undefined ? '' : typeof v === 'number' ? String(v) : v;
for (const f of DATE_FIELDS) out[f] = r[f] ? r[f]!.slice(0, 10) : '';
out.creationDate = stamp(r.creationDate);
out.lastUpdateDate = stamp(r.lastUpdateDate);
return out;
}

View File

@ -0,0 +1,222 @@
import { useMemo, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import {
Alert, Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Skeleton, Stack, TextField, Typography,
} from '@mui/material';
import BlockIcon from '@mui/icons-material/Block';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import DownloadIcon from '@mui/icons-material/Download';
import ImageIcon from '@mui/icons-material/Image';
import UndoIcon from '@mui/icons-material/Undo';
import type { ApiError } from '@/api/client';
import { DataGrid, gridReturnUrl } from '@/components/DataGrid';
import { LoadingBanner } from '@/components/LoadingBanner';
import { MetaForm } from '@/components/MetaForm';
import { PageHeader } from '@/components/PageHeader';
import { SectionPaper } from '@/components/SectionPaper';
import { SectionTitle } from '@/components/SectionTitle';
import { StatusChip } from '@/components/StatusChip';
import { useFeatureUi } from '@/i18n/useUi';
import { useAuth } from '@/providers/AuthProvider';
import { useConfirm } from '@/providers/ConfirmProvider';
import { useToast } from '@/providers/ToastProvider';
import { downloadFile } from '../grains-orders/api';
import {
baseOf, useAttachmentImage, useRegistrarAction, useRegistrarLists, useRegistrarRecord, useRegistrarUpdate,
type RegistrarAttachment, type RegistrarKind,
} from './api';
import { recordToValues, registrarForm, registrarGrid, registrarStatuses } from './meta';
import strings from './strings';
export const rootOf = (kind: RegistrarKind) => `/registrar/${kind}`;
const ENTITY: Record<RegistrarKind, string> = { drivers: 'DRIVERINFO', trucks: 'TRUCKINFO', trailers: 'TRAILERINFO' };
const REVOKE_LIST: Record<RegistrarKind, string> = { drivers: 'DRIVER_REVOKE_REASON', trucks: 'TRUCK_REVOKE_REASON', trailers: 'TRAILER_REVOKE_REASON' };
const fieldErrorsOf = (e: ApiError) => ({ ...e.fieldErrors }) as Record<string, string>;
function ExportButton({ kind }: { kind: RegistrarKind }) {
const { t } = useFeatureUi(strings);
const { can } = useAuth();
const toast = useToast();
const [sp] = useSearchParams();
const [busy, setBusy] = useState(false);
if (!can(`registrar.${kind}.report`)) return null;
const run = async () => {
setBusy(true);
const params: Record<string, string> = {};
sp.forEach((v, k) => { if (!['page', 'pageSize', 'size', 'f'].includes(k)) params[k] = v; });
try { await downloadFile(`${baseOf(kind)}/export`, params, `${ENTITY[kind]}.xlsx`); }
catch (e) { toast.error(e instanceof Error ? e.message : String(e)); }
finally { setBusy(false); }
};
return <Button variant="outlined" startIcon={<DownloadIcon />} disabled={busy} onClick={() => void run()}>{t('rg.export')}</Button>;
}
export function RegistrarGridPage({ kind }: { kind: RegistrarKind }) {
const { t } = useFeatureUi(strings);
const navigate = useNavigate();
const meta = useMemo(() => registrarGrid(kind, { onOpen: (r) => navigate(`${rootOf(kind)}/${r.id}`) }), [kind, navigate]);
return (
<>
<PageHeader title={t(`rg.menu.${kind}`)} subtitle={t(`rg.subtitle.${kind}`)} actions={<ExportButton kind={kind} />} />
<DataGrid meta={meta} />
</>
);
}
/** The front and back pictures of the licence, served by the API (legacy: filepond[0] / filepond[1]). */
function Picture({ kind, id, file }: { kind: RegistrarKind; id: number; file: RegistrarAttachment }) {
const { t } = useFeatureUi(strings);
const img = useAttachmentImage(kind, id, file.id);
return (
<Box sx={{ width: { xs: '100%', sm: 320 }, minHeight: 200 }}>
{img.failed ? (
<Alert severity="warning">{t('rg.pictures.failed')}</Alert>
) : !img.url ? (
<Skeleton variant="rounded" height={220} />
) : (
<Box
component="a" href={img.url} target="_blank" rel="noopener noreferrer" title={t('rg.pictures.open')}
sx={{ display: 'block', border: 1, borderColor: 'divider', borderRadius: 1, overflow: 'hidden', bgcolor: 'background.paper' }}
>
<Box component="img" src={img.url} alt={file.fileName} sx={{ display: 'block', width: '100%', maxHeight: 360, objectFit: 'contain' }} />
</Box>
)}
<Typography variant="caption" color="text.secondary" dir="ltr" sx={{ display: 'block', mt: 0.5, wordBreak: 'break-all' }}>{file.fileName}</Typography>
</Box>
);
}
function Pictures({ kind, id, files }: { kind: RegistrarKind; id: number; files: RegistrarAttachment[] }) {
const { t } = useFeatureUi(strings);
return (
<SectionPaper sx={{ p: 2 }}>
<SectionTitle icon={ImageIcon} title={t('rg.sec.pictures')} />
{files.length === 0 ? (
<Typography color="text.secondary">{t('rg.pictures.empty')}</Typography>
) : (
<Stack direction="row" useFlexGap spacing={2} sx={{ flexWrap: 'wrap' }}>
{files.map((f) => <Picture key={f.id} kind={kind} id={id} file={f} />)}
</Stack>
)}
</SectionPaper>
);
}
/** Reject: the reason comes from the kind's revoke-reason list (legacy 2-step revoke: pick the reason, then confirm). */
function RevokeDialog({ kind, open, busy, onClose, onSubmit }: {
kind: RegistrarKind; open: boolean; busy: boolean; onClose: () => void; onSubmit: (reason: string) => void;
}) {
const { t, lang } = useFeatureUi(strings);
const lists = useRegistrarLists();
const [reason, setReason] = useState('');
const items = lists.data?.[REVOKE_LIST[kind]] ?? [];
return (
<Dialog open={open} onClose={busy ? undefined : onClose} fullWidth maxWidth="xs">
<DialogTitle>{t('rg.revoke.title')}</DialogTitle>
<DialogContent>
<TextField
select fullWidth autoFocus margin="dense" label={t('rg.revoke.reason')} value={reason} onChange={(e) => setReason(e.target.value)}
slotProps={{ select: { displayEmpty: true } }}
>
<MenuItem value="" disabled>{t('rg.revoke.select')}</MenuItem>
{items.map((i) => <MenuItem key={i.code} value={i.code}>{lang === 'ar' ? i.ar : i.en}</MenuItem>)}
</TextField>
</DialogContent>
<DialogActions>
<Button color="inherit" onClick={onClose} disabled={busy}>{t('common.cancel')}</Button>
<Button color="error" variant="contained" disabled={busy || !reason} onClick={() => onSubmit(reason)}>{t('rg.revoke.submit')}</Button>
</DialogActions>
</Dialog>
);
}
export function RegistrarDetailPage({ kind }: { kind: RegistrarKind }) {
const { t } = useFeatureUi(strings);
const navigate = useNavigate();
const confirm = useConfirm();
const params = useParams();
const id = params.id ? Number(params.id) : null;
const q = useRegistrarRecord(kind, id);
const update = useRegistrarUpdate(kind);
const action = useRegistrarAction(kind);
const [serverErrors, setServerErrors] = useState<Record<string, string>>({});
const [revoking, setRevoking] = useState(false);
const meta = useMemo(() => registrarForm(kind), [kind]);
const detail = q.data;
const initial = useMemo(() => (detail ? recordToValues(detail.record) : {}), [detail]);
const root = rootOf(kind);
if (q.isLoading) return <LoadingBanner />;
if (!detail || id === null) return <Alert severity="error">{q.error?.message ?? t('rg.loadFailed')}</Alert>;
const { record, actions } = detail;
const number = kind === 'drivers' ? (record.nnpn ?? '') : (record.plateNo ?? '');
const submit = (payload: Record<string, unknown>) =>
new Promise<void>((resolve) => {
setServerErrors({});
update.mutate({ id, body: payload }, {
onSuccess: () => resolve(),
onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); },
});
});
const run = async (kindOfAction: 'complete' | 'reopen') => {
if (!(await confirm({ message: t(kindOfAction === 'complete' ? 'rg.confirm.complete' : 'rg.confirm.reopen') }))) return;
setServerErrors({});
action.mutate({ id, action: kindOfAction }, {
onSuccess: () => navigate(gridReturnUrl(root)),
onError: (e) => setServerErrors(fieldErrorsOf(e)),
});
};
const reject = (reason: string) =>
action.mutate({ id, action: 'revoke', reason }, {
onSuccess: () => { setRevoking(false); navigate(gridReturnUrl(root)); },
});
const anyAction = actions.update || actions.complete || actions.revoke || actions.reopen;
return (
<Stack spacing={2}>
<PageHeader
title={t(`rg.detail.${kind}`, { number })}
status={<StatusChip value={record.statusCode} statuses={registrarStatuses} size="medium" />}
backTo={root}
actions={(
<>
{actions.complete && (
<Button variant="contained" color="success" startIcon={<CheckCircleIcon />} disabled={action.isPending} onClick={() => void run('complete')}>
{t('rg.action.complete')}
</Button>
)}
{actions.revoke && (
<Button variant="outlined" color="error" startIcon={<BlockIcon />} disabled={action.isPending} onClick={() => setRevoking(true)}>
{t('rg.action.revoke')}
</Button>
)}
{actions.reopen && (
<Button variant="outlined" startIcon={<UndoIcon />} disabled={action.isPending} onClick={() => void run('reopen')}>
{t('rg.action.reopen')}
</Button>
)}
</>
)}
/>
{!anyAction && <Alert severity="info">{t('rg.readOnly')}</Alert>}
<MetaForm
meta={meta}
mode={actions.update ? 'edit' : 'view'}
initialValues={initial}
serverErrors={serverErrors}
submitLabel={t('rg.action.save')}
cancelLabel={t('rg.return')}
onCancel={() => navigate(gridReturnUrl(root))}
onSubmit={submit}
>
<Pictures kind={kind} id={id} files={detail.attachments} />
</MetaForm>
<RevokeDialog kind={kind} open={revoking} busy={action.isPending} onClose={() => setRevoking(false)} onSubmit={reject} />
</Stack>
);
}

View File

@ -0,0 +1,31 @@
import type { RouteObject } from 'react-router-dom';
import AssignmentIndIcon from '@mui/icons-material/AssignmentInd';
import BadgeIcon from '@mui/icons-material/Badge';
import LocalShippingIcon from '@mui/icons-material/LocalShipping';
import RvHookupIcon from '@mui/icons-material/RvHookup';
import type { MenuItem } from '@/shell/types';
import { RegistrarDetailPage, RegistrarGridPage, rootOf } from './pages';
import { KINDS, type RegistrarKind } from './api';
import strings from './strings';
/**
* Registrar (نظام التسجيل), ported from the AqabaTCS menu block "MENU.REGISTRAR": the driver, truck and trailer licences registered from the mobile app,
* reviewed here. Each screen is granted by the key registrar.<kind> (db/registrar-permissions.sql); the actions inside by the keys of the kind.
*/
export const routes: RouteObject[] = KINDS.flatMap((kind: RegistrarKind) => [
{ path: rootOf(kind), element: <RegistrarGridPage kind={kind} /> },
{ path: `${rootOf(kind)}/:id`, element: <RegistrarDetailPage kind={kind} />, handle: { crumb: strings['rg.crumb.details'] } },
]);
export const menu: MenuItem[] = [
{
key: 'registrar',
title: strings['rg.menu'],
icon: AssignmentIndIcon,
children: [
{ key: 'registrar.drivers', title: strings['rg.menu.drivers'], icon: BadgeIcon, path: rootOf('drivers') },
{ key: 'registrar.trucks', title: strings['rg.menu.trucks'], icon: LocalShippingIcon, path: rootOf('trucks') },
{ key: 'registrar.trailers', title: strings['rg.menu.trailers'], icon: RvHookupIcon, path: rootOf('trailers') },
],
},
];

View File

@ -0,0 +1,100 @@
import { defineStrings } from '@/i18n/useUi';
/** Strings of the registrar screens (legacy captions MENU.REGISTRAR*, PUBLIC.*, DRIVERINFO.* / TRUCKINFO.* / TRAILERINFO.*, verbatim in Arabic). */
export default defineStrings({
'rg.menu': { en: 'Registration system', ar: 'التسجيل العام' },
'rg.menu.drivers': { en: 'Driver licences', ar: 'رخص السائقين' },
'rg.menu.trucks': { en: 'Truck licences', ar: 'رخص الشاحنات' },
'rg.menu.trailers': { en: 'Trailer licences', ar: 'رخص المقطورات' },
'rg.subtitle.drivers': { en: 'Drivers registered from the mobile app, waiting for review', ar: 'السائقون المسجلون من تطبيق الموبايل: التدقيق والتأكيد' },
'rg.subtitle.trucks': { en: 'Trucks registered from the mobile app, waiting for review', ar: 'الشاحنات المسجلة من تطبيق الموبايل: التدقيق والتأكيد' },
'rg.subtitle.trailers': { en: 'Trailers registered from the mobile app, waiting for review', ar: 'المقطورات المسجلة من تطبيق الموبايل: التدقيق والتأكيد' },
'rg.detail.drivers': { en: 'Driver {number}', ar: 'معلومات السائق {number}' },
'rg.detail.trucks': { en: 'Truck {number}', ar: 'معلومات الشاحنة {number}' },
'rg.detail.trailers': { en: 'Trailer {number}', ar: 'معلومات المقطورة {number}' },
'rg.crumb.details': { en: 'Details', ar: 'التفاصيل' },
'rg.loadFailed': { en: 'The record could not be loaded.', ar: 'تعذر تحميل السجل.' },
'rg.return': { en: 'Back', ar: 'عودة' },
'rg.export': { en: 'Excel', ar: 'تصدير Excel' },
// statuses (DRIVERINFO.STATUS.* ...)
'rg.status.PENDING': { en: 'Under review', ar: 'قيد التدقيق' },
'rg.status.COMPLETED': { en: 'Completed', ar: 'مكتمل' },
'rg.status.INCOMPLETE': { en: 'Incomplete', ar: 'غير مكتمل' },
'rg.status.REVOKE': { en: 'Rejected', ar: 'مرفوض' },
// actions
'rg.action.complete': { en: 'Confirm', ar: 'تأكيد' },
'rg.action.revoke': { en: 'Reject', ar: 'رفض' },
'rg.action.reopen': { en: 'Back to review', ar: 'إعادة الى قيد التدقيق' },
'rg.action.save': { en: 'Update', ar: 'تعديل' },
'rg.confirm.complete': { en: 'Confirm this registration? The user who registered it is notified.', ar: 'هل تريد تأكيد التسجيل؟ سيصل اشعار للمستخدم الذي سجله.' },
'rg.confirm.reopen': { en: 'Move this registration back to review?', ar: 'هل تريد اعادة التسجيل الى قيد التدقيق؟' },
'rg.revoke.title': { en: 'Reject the registration', ar: 'رفض التسجيل' },
'rg.revoke.reason': { en: 'Rejection reason', ar: 'سبب الرفض' },
'rg.revoke.select': { en: 'Choose the reason', ar: 'أختر السبب' },
'rg.revoke.needReason': { en: 'Choose the rejection reason first.', ar: 'يرجى اختيار سبب الرفض من أعلى النموذج' },
'rg.revoke.submit': { en: 'Reject', ar: 'رفض' },
'rg.readOnly': { en: 'This record cannot be edited in its current status or with your rights.', ar: 'لا يمكن تعديل السجل في حالته الحالية أو بصلاحياتك.' },
'rg.fillHint': { en: 'A registration can only be confirmed when every required field is filled (save first).', ar: 'لا يمكن تأكيد التسجيل قبل تعبئة جميع الحقول المطلوبة (احفظ التعديلات اولا).' },
// sections
'rg.sec.main': { en: 'Registration data', ar: 'معلومات التسجيل' },
'rg.sec.licence': { en: 'Licence', ar: 'الرخصة' },
'rg.sec.owner': { en: 'Owner', ar: 'المالك' },
'rg.sec.vehicle': { en: 'Vehicle', ar: 'المركبة' },
'rg.sec.record': { en: 'Record', ar: 'معلومات السجل' },
'rg.sec.pictures': { en: 'Pictures', ar: 'الصور' },
'rg.pictures.empty': { en: 'No pictures', ar: 'لا يوجد صور' },
'rg.pictures.open': { en: 'Open the picture', ar: 'فتح الصورة' },
'rg.pictures.failed': { en: 'The picture could not be loaded', ar: 'تعذر تحميل الصورة' },
// fields (PUBLIC.* captions)
'rg.f.number': { en: 'Number', ar: 'الرقم' },
'rg.f.nationality': { en: 'Nationality', ar: 'الجنسية' },
'rg.f.nameAr': { en: 'Name (Arabic)', ar: 'الأسم بالعربي' },
'rg.f.nameEn': { en: 'Name (English)', ar: 'الأسم بالأنجليزي' },
'rg.f.name': { en: 'Driver name', ar: 'اسم السائق' },
'rg.f.nnpn': { en: 'National number', ar: 'الرقم الوطني' },
'rg.f.mobile': { en: 'Mobile', ar: 'الموبايل' },
'rg.f.dateOfBirth': { en: 'Date of birth', ar: 'تاريخ الميلاد' },
'rg.f.bloodGroup': { en: 'Blood group', ar: 'فصيلة الدم' },
'rg.f.governate': { en: 'Governorate', ar: 'المحافظة' },
'rg.f.address': { en: 'Address', ar: 'العنوان' },
'rg.f.licenseNo': { en: 'Licence number', ar: 'رقم الرخصة' },
'rg.f.licenseType': { en: 'Licence class', ar: 'فئة الرخصة' },
'rg.f.licenseIssueDate': { en: 'Licence issue date', ar: 'تاريخ اصدار الرخصة' },
'rg.f.licenseExpiryDate': { en: 'Licence expiry date', ar: 'تاريخ انتهاء الرخصة' },
'rg.f.licenseRegistrationNo': { en: 'Registration number', ar: 'رقم التسجيل' },
'rg.f.plateTruck': { en: 'Truck number', ar: 'رقم الشاحنة' },
'rg.f.plateTrailer': { en: 'Trailer number', ar: 'رقم المقطورة' },
'rg.f.plateCodeTruck': { en: 'Truck number code', ar: 'ترميز رقم الشاحنة' },
'rg.f.plateCodeTrailer': { en: 'Trailer number code', ar: 'ترميز رقم المقطورة' },
'rg.f.ownerName': { en: 'Owner name', ar: 'اسم المالك' },
'rg.f.ownerAddress': { en: 'Owner address', ar: 'العنوان' },
'rg.f.manufacturer': { en: 'Vehicle make', ar: 'نوع المركبة' },
'rg.f.model': { en: 'Vehicle model', ar: 'صنف المركبة' },
'rg.f.color': { en: 'Colour', ar: 'اللون' },
'rg.f.secondaryColor': { en: 'Secondary colour', ar: 'اللون الفرعي' },
'rg.f.vehicleType': { en: 'Vehicle class', ar: 'فئه المركبة' },
'rg.f.manufactureYear': { en: 'Year of manufacture', ar: 'سنه الصنع' },
'rg.f.category': { en: 'Use', ar: 'صفة الأستعمال' },
'rg.f.vinNumber': { en: 'Chassis number', ar: 'رقم الشاصي' },
'rg.f.engineNumber': { en: 'Engine number', ar: 'رقم المحرك' },
'rg.f.loadingWeight': { en: 'Load', ar: 'الحمولة' },
'rg.f.grossWeight': { en: 'Gross weight', ar: 'الوزن القائم' },
'rg.f.notes': { en: 'Notes', ar: 'ملاحظات' },
'rg.f.revokeReason': { en: 'Rejection reason', ar: 'سبب الرفض' },
'rg.f.createdBy': { en: 'Created by', ar: 'انشاء بواسطة' },
'rg.f.creationDate': { en: 'Created', ar: 'تاريخ الانشاء' },
'rg.f.updatedBy': { en: 'Updated by', ar: 'حُدث بواسطة' },
'rg.f.lastUpdateDate': { en: 'Updated', ar: 'حدُث بتاريخ' },
'rg.f.createDateFrom': { en: 'Created from', ar: 'من تاريخ الانشاء' },
'rg.f.createDateTo': { en: 'Created to', ar: 'الى تاريخ الانشاء' },
'rg.f.status': { en: 'Status', ar: 'الحالة' },
'rg.f.noEntry': { en: 'Not entered', ar: 'غير مدخل' },
'rg.digits': { en: 'Digits only', ar: 'الحقل لا يقبل أحرف' },
'rg.arabicOnly': { en: 'Arabic letters only', ar: 'الاسم بالعربية يجب ان يكون باحرف عربية' },
'rg.englishOnly': { en: 'English letters only', ar: 'الاسم بالانجليزية يجب ان يكون باحرف انجليزية' },
'rg.nameHint': { en: 'Fill the Arabic or the English name.', ar: 'يجب تعبئة الاسم العربي او الانجليزي' },
});

View File

@ -125,6 +125,8 @@ export const ui = {
'confirm.yes': { en: 'Confirm', ar: 'تأكيد' }, 'confirm.yes': { en: 'Confirm', ar: 'تأكيد' },
'confirm.no': { en: 'Cancel', ar: 'إلغاء' }, 'confirm.no': { en: 'Cancel', ar: 'إلغاء' },
'busy.saving': { en: 'Saving...', ar: 'جاري الحفظ...' }, 'busy.saving': { en: 'Saving...', ar: 'جاري الحفظ...' },
'busy.report': { en: 'Generating the report...', ar: 'جاري انشاء التقرير...' },
'busy.reportHint': { en: 'This can take a moment for large reports. Please wait, the file downloads automatically.', ar: 'قد يستغرق ذلك بعض الوقت للتقارير الكبيرة. يرجى الانتظار، سيتم تنزيل الملف تلقائيا.' },
'busy.savingHint': { en: 'Please wait, do not close this page.', ar: 'يرجى الانتظار وعدم إغلاق الصفحة.' }, 'busy.savingHint': { en: 'Please wait, do not close this page.', ar: 'يرجى الانتظار وعدم إغلاق الصفحة.' },
// toasts / errors // toasts / errors