Compare commits
22 Commits
QA_old_ver
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
02e7fea1ec | |
|
|
ed18621821 | |
|
|
28e629ccac | |
|
|
31771e3c73 | |
|
|
dc72cf2869 | |
|
|
90260edd8e | |
|
|
6027edb98b | |
|
|
ab0d26fbf5 | |
|
|
2cdb74f082 | |
|
|
18d74d1b53 | |
|
|
0819427bdf | |
|
|
ef0e72ff9d | |
|
|
03d16e742a | |
|
|
84facf2ddf | |
|
|
4066151033 | |
|
|
a318d2b2f0 | |
|
|
514a76d7c7 | |
|
|
91d6416198 | |
|
|
3a230fd556 | |
|
|
2a339afee3 | |
|
|
e487c05248 | |
|
|
0eb83d3bb5 |
|
|
@ -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;
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
-- Permit receipts: the grains (GN) permit number of the receipt, "رقم الارسالية" (legacy form field GNPN, which the legacy never stored).
|
||||
-- Run in the primary (NAFITHTCS) schema BEFORE deploying this version of the receipts screen. Safe to re-run; not run by the app.
|
||||
DECLARE
|
||||
n NUMBER;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO n FROM user_tab_columns WHERE table_name = 'PERMITS_RECEIPTS' AND column_name = 'GNPN';
|
||||
IF n = 0 THEN
|
||||
EXECUTE IMMEDIATE 'ALTER TABLE PERMITS_RECEIPTS ADD (GNPN NUMBER)';
|
||||
END IF;
|
||||
END;
|
||||
/
|
||||
|
|
@ -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;
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
-- Refinery (المصفاة): role REFINERY_OP (موظف عطاء الصرف) sees the الارساليات screen with the شحن الديزل (Excel) report, print and the
|
||||
-- payment actions. Safe to re-run; not run by the app.
|
||||
-- Run order: part 1 in the NTP schema (only needed where the role row is missing; it exists in the legacy data), part 2 in the primary
|
||||
-- (NAFITHTCS) schema, after db/grains-screen-permissions.sql. Afterwards assign role REFINERY_OP to the users who need it (NTPUSERS):
|
||||
-- they sign in as before. The API applies the rows within about a minute, the browser on the next reload / sign-in.
|
||||
-- SU needs no rows. Everything else of the refinery module (wage claims, commission claims, wallets, variables, cards, the other
|
||||
-- trip reports, the reverse-advance actions, recalculate balance) stays with REFINERY_MGR and SU.
|
||||
|
||||
-- ---------------------------------------------------------------------------------------------------------------------------
|
||||
-- Part 1 (NTP schema): the role row, copied from REFINERY_MGR (level, type, manager columns) when REFINERY_OP does not exist yet.
|
||||
-- ---------------------------------------------------------------------------------------------------------------------------
|
||||
INSERT INTO ROLES (CODE, NAME, DIRECTMANAGER, EMPLOYEES, MANAGERS, LEVELNUMBER, ROLETYPE, TENDER)
|
||||
SELECT 'REFINERY_OP', 'موظف عطاء الصرف', r.DIRECTMANAGER, r.EMPLOYEES, r.MANAGERS, r.LEVELNUMBER, r.ROLETYPE, r.TENDER
|
||||
FROM ROLES r
|
||||
WHERE r.CODE = 'REFINERY_MGR'
|
||||
AND NOT EXISTS (SELECT 1 FROM ROLES x WHERE x.CODE = 'REFINERY_OP');
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- ---------------------------------------------------------------------------------------------------------------------------
|
||||
-- Part 2 (primary schema): 13 keys.
|
||||
-- screen refinery.trips (list, view, history)
|
||||
-- report refinery.trips.dieselReport (شحن الديزل Excel)
|
||||
-- print refinery.trips.print (cash voucher)
|
||||
-- diesel refinery.trips.firstAdvance, secondAdvance
|
||||
-- cash refinery.trips.cashPayment, receipt
|
||||
-- bank / orange refinery.trips.payment, orangePayment
|
||||
-- e-wallet refinery.trips.exchange, exchangeAudit, activateWalletExchange, confirmExchange (Dinarak is OFF until configured)
|
||||
-- ---------------------------------------------------------------------------------------------------------------------------
|
||||
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
|
||||
SELECT 'REFINERY_OP', v.resource_key
|
||||
FROM (SELECT 'refinery.trips' AS resource_key FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.dieselReport' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.print' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.firstAdvance' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.secondAdvance' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.cashPayment' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.receipt' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.payment' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.orangePayment' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.exchange' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.exchangeAudit' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.activateWalletExchange' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.confirmExchange' FROM dual) v
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p
|
||||
WHERE p.rolecode = 'REFINERY_OP' AND p.resource_key = v.resource_key);
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- Check (expect 13 rows):
|
||||
-- SELECT resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'REFINERY_OP' ORDER BY resource_key;
|
||||
-- Take a right away by deleting its row, e.g.:
|
||||
-- DELETE FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'REFINERY_OP' AND resource_key = 'refinery.trips.confirmExchange';
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
-- Refinery (المصفاة) modules ported from AqabaTCS: trips, wage claims, commission claims, wallets, variables, cards.
|
||||
-- Authority: SU (always allowed by the code, needs no row) and REFINERY_MGR (rows below: 6 screens + every action key).
|
||||
-- Run on a database where GRAINS_SCREEN_PERMISSIONS exists (db/grains-screen-permissions.sql). Safe to re-run. Not executed by the application.
|
||||
-- Delete a row to take a key away (the API applies it within about a minute, the browser on the next reload or sign-in).
|
||||
-- Give another role access: copy the block and change the role code.
|
||||
|
||||
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
|
||||
SELECT 'REFINERY_MGR', v.resource_key
|
||||
FROM (SELECT 'refinery.trips' AS resource_key FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.firstAdvance' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.secondAdvance' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.firstAdvanceReverse' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.secondAdvanceReverse' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.exchange' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.exchangeAudit' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.receipt' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.payment' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.activateWalletExchange' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.orangePayment' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.cashPayment' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.confirmExchange' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.print' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.report' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.operatorReport' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.exchangeReport' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.dieselReport' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.cardsReport' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.bankReport' FROM dual UNION ALL
|
||||
SELECT 'refinery.trips.recalculateBalance' FROM dual UNION ALL
|
||||
SELECT 'refinery.wageClaims' FROM dual UNION ALL
|
||||
SELECT 'refinery.wageClaims.create' FROM dual UNION ALL
|
||||
SELECT 'refinery.wageClaims.close' FROM dual UNION ALL
|
||||
SELECT 'refinery.wageClaims.transfer' FROM dual UNION ALL
|
||||
SELECT 'refinery.wageClaims.report' FROM dual UNION ALL
|
||||
SELECT 'refinery.commissionClaims' FROM dual UNION ALL
|
||||
SELECT 'refinery.commissionClaims.create' FROM dual UNION ALL
|
||||
SELECT 'refinery.commissionClaims.complete' FROM dual UNION ALL
|
||||
SELECT 'refinery.commissionClaims.report' FROM dual UNION ALL
|
||||
SELECT 'refinery.wallets' FROM dual UNION ALL
|
||||
SELECT 'refinery.wallets.create' FROM dual UNION ALL
|
||||
SELECT 'refinery.wallets.update' FROM dual UNION ALL
|
||||
SELECT 'refinery.wallets.activate' FROM dual UNION ALL
|
||||
SELECT 'refinery.wallets.deactivate' FROM dual UNION ALL
|
||||
SELECT 'refinery.wallets.report' FROM dual UNION ALL
|
||||
SELECT 'refinery.variables' FROM dual UNION ALL
|
||||
SELECT 'refinery.variables.create' FROM dual UNION ALL
|
||||
SELECT 'refinery.variables.update' FROM dual UNION ALL
|
||||
SELECT 'refinery.variables.tonPriceCorrection' FROM dual UNION ALL
|
||||
SELECT 'refinery.variables.report' FROM dual UNION ALL
|
||||
SELECT 'refinery.variables.remainingBalanceReport' FROM dual UNION ALL
|
||||
SELECT 'refinery.cards' FROM dual UNION ALL
|
||||
SELECT 'refinery.cards.create' FROM dual UNION ALL
|
||||
SELECT 'refinery.cards.activate' FROM dual UNION ALL
|
||||
SELECT 'refinery.cards.deactivate' FROM dual UNION ALL
|
||||
SELECT 'refinery.cards.report' FROM dual) v
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p
|
||||
WHERE p.rolecode = 'REFINERY_MGR' AND p.resource_key = v.resource_key);
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- Check (expect 47 rows):
|
||||
-- SELECT resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE rolecode = 'REFINERY_MGR' AND resource_key LIKE 'refinery.%' ORDER BY resource_key;
|
||||
|
|
@ -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;
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
-- Registry Excel export rights (NAFITHTCS schema): who sees the "تصدير Excel" button of the trucks, trailers and drivers lists.
|
||||
-- The application has NO role list for this: only these rows decide (SU always may). Safe to re-run: a row is only inserted
|
||||
-- when it is not there yet. Not executed by the application.
|
||||
--
|
||||
-- Starting values copy the legacy screens (truckGrid.cfm / driverGrid.cfm):
|
||||
-- trucks, trailers : GTO, GOO, GNAC (+ CO, which has the same rights as GTO)
|
||||
-- drivers : GTO, GOO (+ CO)
|
||||
--
|
||||
-- To take a right away, delete the row; the API applies it within about a minute (permissions are cached per role for 60 seconds)
|
||||
-- and the user's browser picks it up on the next page reload or sign-in.
|
||||
|
||||
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
|
||||
SELECT v.rolecode, v.resource_key
|
||||
FROM (
|
||||
SELECT 'GTO' AS rolecode, 'grains.registry.trucks.export' AS resource_key FROM dual UNION ALL
|
||||
SELECT 'GOO', 'grains.registry.trucks.export' FROM dual UNION ALL
|
||||
SELECT 'GNAC', 'grains.registry.trucks.export' FROM dual UNION ALL
|
||||
SELECT 'CO', 'grains.registry.trucks.export' FROM dual UNION ALL
|
||||
SELECT 'GTO', 'grains.registry.trailers.export' FROM dual UNION ALL
|
||||
SELECT 'GOO', 'grains.registry.trailers.export' FROM dual UNION ALL
|
||||
SELECT 'GNAC', 'grains.registry.trailers.export' FROM dual UNION ALL
|
||||
SELECT 'CO', 'grains.registry.trailers.export' FROM dual UNION ALL
|
||||
SELECT 'GTO', 'grains.registry.drivers.export' FROM dual UNION ALL
|
||||
SELECT 'GOO', 'grains.registry.drivers.export' FROM dual UNION ALL
|
||||
SELECT 'CO', 'grains.registry.drivers.export' 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;
|
||||
|
||||
-- Check (expect 11 rows):
|
||||
-- SELECT rolecode, resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE resource_key LIKE 'grains.registry.%.export' ORDER BY 2, 1;
|
||||
|
|
@ -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 |
|
||||
| `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` |
|
||||
| `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):
|
||||
`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`
|
||||
|
|
@ -50,6 +55,7 @@ Apply these scripts once per database (not run by the application), in this orde
|
|||
|
||||
1. `db/grains-screen-permissions.sql` - role to screen/action permissions (`GRAINS_SCREEN_PERMISSIONS`)
|
||||
2. `db/registry-create-permissions.sql` - add / edit rights of trucks, trailers and drivers (safe to re-run)
|
||||
2b. `db/registry-export-permissions.sql` - Excel export rights of the trucks, trailers and drivers lists (`grains.registry.*.export`; without rows nobody but SU sees the button) (safe to re-run)
|
||||
3. `db/disabled-features.sql` - features switched OFF for everybody, SU included (safe to re-run)
|
||||
4. `db/permits-create-permission.sql` - right to register a turn (تسجيل دور) from the permits list, granted to GOO (safe to re-run)
|
||||
5. `db/menu-reorganisation.sql` - new طلبية التموين screen, GOO reports reduced to two, GOO loses ضبط الميزان (safe to re-run)
|
||||
|
|
@ -57,6 +63,12 @@ Apply these scripts once per database (not run by the application), in this orde
|
|||
5c. `db/role-co.sql` - new role CO with the same rights as GTO: role row (NTP schema) + copy of every GTO row in GRAINS_SCREEN_PERMISSIONS (safe to re-run)
|
||||
7. `db/grains-jobs.sql` - tables of the scheduled jobs (`GRAINS_JOBS`, `GRAINS_JOB_RUNS`), primary schema. Without it the scheduler stays idle. Jobs are then started, stopped and timed on the SU screen "المهام المجدولة" (`/jobs`); nothing runs until a job is started there. `Jobs:SchedulerEnabled=false` (set in appsettings.Development.json) switches the scheduler loop off for a process
|
||||
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)
|
||||
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)
|
||||
11b. `db/receipts-gn-permit.sql` - adds PERMITS_RECEIPTS.GNPN (رقم الارسالية of the receipt); run it in the primary schema BEFORE deploying the receipts screen of this version (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
|
||||
included: the menu entry and buttons disappear and the API answers 403. It overrides every other row. Delete the row to bring the
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
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.
|
||||
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.
|
||||
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).
|
||||
|
|
@ -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%'`.
|
||||
|
||||
### 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).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,74 @@
|
|||
# Refinery migration: shared brief for the porting agents
|
||||
|
||||
Port refinery modules of the legacy ColdFusion app **AqabaTCS** (`C:\inetpub\wwwroot\AqabaTCS_LIVE`, read-only) into NTP V2
|
||||
(.NET 10 API + Oracle 11g/Dapper + React/MUI web). Read first: `CLAUDE.md`, `docs/MIGRATION.md`, `docs/refinery-db-objects.txt`
|
||||
(text of the legacy DB views and the diesel / amount functions, already extracted), and `docs/schema/NAFITHTCS.md` sections
|
||||
`REFINERY_*`. Reference slices that show the house style: `src/NTP.Application/Grains/Registry`, `.../Orders` (BillingService),
|
||||
`src/NTP.Infrastructure/Persistence/Repositories/Grains/*`, `src/NTP.Api/Controllers/V1/Grains/RegistryController.cs`,
|
||||
`web/src/features/grains-registry` (pages, meta, strings, api hooks).
|
||||
|
||||
## Legacy layout (AqabaTCS)
|
||||
- Backend per entity: `backend/entities/<entity>/` : `*dao.cfc` (SQL), `*factory.cfc` (business rules, validation, transactions, log rows),
|
||||
`*factoryweb.cfc` (web layer: filter whitelist, role specific branches, row actions), `*bean.cfc` (fields).
|
||||
- Frontend per entity: `frontend/entities/<ENTITY>/<ENTITY>GRID`, `<ENTITY>` (form), `<ENTITY>Log` (history popup): `.js` + `.html`.
|
||||
- Menu / authority: `customtags/Menu.cfm` (entries REFINERYTRIP, REFINERY_WAGE_CLAIM, REFINERY_COMMISSION_CLAIM, REFINERY_WALLET,
|
||||
REFINERY_VARIABLES, REFINERY_CARDS). Grids read DB views (`REFINERY_*_VIEW`, text in docs/refinery-db-objects.txt); `common.getGridData`
|
||||
builds the filter SQL (look at `backend/common/common.cfc` when you need to know how a filter field maps to a column).
|
||||
- Captions (Arabic UI / message texts) are in the database: `select code, ar from ntp.lt_caption where code like 'REFINERY%'` (also
|
||||
`PUBLIC.%`, `ERROR.%`, `MESSAGE.%`, `MENU.%` for the codes you meet). **User-facing texts must be the legacy Arabic captions, verbatim.**
|
||||
|
||||
## Read-only database access (NAFITHTCS, real data)
|
||||
`dotnet "C:\Users\samers\AppData\Local\Temp\claude\d72adf472b8502c5\42c5454f-ddae-4fd6-af13-dba201a0f7ce\scratchpad\q\out\q.dll" NAFITHTCS "select ..."`
|
||||
(only SELECT / WITH; prints `|` separated rows, max 400). Use it to check columns, status codes, sample rows, views, `user_source`,
|
||||
`user_tab_columns`, `ntp.lt_caption`. Never print or copy a connection string; never write to the database; do not run SQL scripts.
|
||||
`appsettings.Local.json` is in the MAIN checkout (`C:\inetpub\wwwroot\NTP_V2\src\NTP.Api\`), not in your worktree: you cannot run the API.
|
||||
|
||||
## Rules (see CLAUDE.md too, they apply)
|
||||
- Oracle 11.2: no OFFSET/FETCH or identity, page with ROWNUM (`OracleSql.Paginate`), sequences for ids (`SEQ_REFINERY_*` exist). Dapper with
|
||||
classes that have settable properties for results. Bind by name; do not add unused DynamicParameters. Bind numbers, no `TO_CHAR` on indexed columns.
|
||||
Reuse the legacy views where it is simplest (they exist in the database) but prefer explicit SQL when the view is slow or wrong for the screen.
|
||||
- Layers: thin controllers (`src/NTP.Api/Controllers/V1/Refinery/<Module>Controller.cs`, route `api/v{version}/refinery/<module>`, `[RequirePermission(key)]`),
|
||||
services + contracts + validators + repository interfaces in `src/NTP.Application/Refinery/<Module>/`, Dapper repositories in
|
||||
`src/NTP.Infrastructure/Persistence/Repositories/Refinery/<Module>/` (class names `*Service` / `*Repository` registered by convention against `I{Name}`).
|
||||
Primary connection `IDbSession` (NAFITHTCS) holds all REFINERY_* tables; `IUnitOfWork.ExecuteInTransactionAsync` for multi-statement writes.
|
||||
Errors: `BusinessException` (422), `ForbiddenException`, `NotFoundException`, FluentValidation (400) with the legacy Arabic text.
|
||||
- The legacy `*_LOG` tables (OLD_DATA / NEW_DATA JSON, METHOD_NAME, USER_ID, USER_IP) are written on every legacy action: keep doing it
|
||||
(same method names, same JSON content as far as you can see in the factory) and port the log popup (history list + old/new view).
|
||||
Find out what legacy puts in USER_ID / CREATED_BY (numeric NTPUSERS id vs login) and use the matching `ICurrentUser` member.
|
||||
- **Authority**: ONLY `SU` (always allowed by the code) and role `REFINERY_MGR` get access. Do not port the legacy role-specific branches
|
||||
(REFINERY_MGR, REFINERY_OP, EXCHANGE_OP, REFINERY_AC, OPOFF, hard-coded user ids ...). Instead: one screen key per module (already defined in
|
||||
`PermissionKeys.Refinery.cs`) and one **action key per legacy action** (e.g. `refinery.trips.firstAdvance`), declared in YOUR OWN partial file
|
||||
`src/NTP.Application/Access/PermissionKeys.Refinery.<Module>.cs` (`public static partial class PermissionKeys`). Every endpoint carries
|
||||
`[RequirePermission(...)]` with the right key; the web hides buttons with `useAuth().can(key)`. Do NOT add them to `PermissionDefaults`
|
||||
(rows in GRAINS_SCREEN_PERMISSIONS are the source; the lead writes `db/refinery-permissions.sql` from the key list you report).
|
||||
Where a legacy rule depended on the role only to narrow what a user sees, drop it and say so in your report.
|
||||
- **No secrets, no real side effects**: legacy code contains hard-coded credentials (e.g. the Jopetrol SOAP password). Never copy them. External
|
||||
calls go behind `IDinarakGateway` / `IJopetrolGateway` (`src/NTP.Application/Refinery/Integrations/RefineryGateways.cs`, already written; do not
|
||||
change the signatures) with options from configuration and `Enabled=false` by default; add the non-secret defaults to
|
||||
`src/NTP.Api/appsettings.json` (section `Refinery:...`) and say in your report which env vars hold the secrets. Never call a real endpoint.
|
||||
- Web (React 19, MUI 9): Arabic (RTL), logical CSS properties, metadata-driven `DataGrid` / `MetaForm` from `web/src/components`, strings `{ en, ar }`
|
||||
in the module's `strings.ts`, API hooks with React Query like `grains-registry/api.ts`. Put everything of a module under
|
||||
`web/src/features/refinery/<module>/` and export from `web/src/features/refinery/<module>/index.ts`:
|
||||
`export const routes: RouteObject[]` (absolute paths `/refinery/<module>...`) and `export const menuItems: MenuItem[]` (leaf entries only: key = the
|
||||
screen key, title, icon, path; the lead composes the group and `features/refinery/routes.tsx`). Do NOT create `features/refinery/routes.tsx`.
|
||||
- Port behaviour, not markup: same filters, same grid columns, same row actions, same validations and messages, same status flow. Do not port dead
|
||||
code (check callers / Menu.cfm). Cite legacy `file:line` in code comments where a rule is non-obvious.
|
||||
- Tests: xUnit in `tests/NTP.Tests/Refinery/` for pure logic (calculations, status rules, validators). `dotnet test tests/NTP.Tests`.
|
||||
|
||||
## Working environment
|
||||
- You work in your own git worktree. Do not touch the main checkout. Do NOT start the API or the dev server (ports are used by the lead).
|
||||
- First copy these uncommitted foundation files from the main checkout into the same relative paths in your worktree (they are identical for all agents):
|
||||
`src/NTP.Application/Access/PermissionDefaults.cs` (class made `partial`), `src/NTP.Application/Access/PermissionKeys.Refinery.cs`,
|
||||
`src/NTP.Application/Refinery/Integrations/RefineryGateways.cs` (all under `C:\inetpub\wwwroot\NTP_V2\`). Commit them with your work.
|
||||
- Web checks need node_modules: in your worktree `web/` create a junction to the main one: `cmd /c mklink /J node_modules C:\inetpub\wwwroot\NTP_V2\web\node_modules`
|
||||
(do not commit it; check `git status`). Then `cd web && npx tsc -b --noEmit`.
|
||||
- Build with `dotnet build src/NTP.Api` and test with `dotnet test tests/NTP.Tests` in your worktree. Everything must build and pass before you finish.
|
||||
- Shared files you may have to touch (re-read right before editing, make a minimal Edit, never rewrite): `src/NTP.Infrastructure/DependencyInjection.cs`
|
||||
(gateway registration), `src/NTP.Api/appsettings.json`. Touch nothing else outside your module folders.
|
||||
- Commit your work in the worktree branch (one commit, clear message, end it with the line `Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>`).
|
||||
Do not push.
|
||||
|
||||
## Report back (your final message, plain text, concise)
|
||||
1. Branch name and commit hash. 2. Files added / changed outside your module folders. 3. **Exact list of permission keys** you declared (screen + action keys).
|
||||
4. What you did NOT port or changed on purpose (and why). 5. Anything you could not verify (nothing was run against real data except read-only SELECTs).
|
||||
6. Open questions for the owner.
|
||||
|
|
@ -0,0 +1,983 @@
|
|||
=== VIEWS (user_views text, NAFITHTCS) ===
|
||||
|
||||
--- REFINERY_CARDS_VIEW
|
||||
select "ID","TN","CARD_NUMBER","BOX_NO","CURRENT_BALANCE","CREATION_DATE","CREATED_BY","UPDATE_DATE","UPDATED_BY","STATUS_CODE","LAST_TRIP_ID"
|
||||
from REFINERY_CARDS
|
||||
|
||||
|
||||
--- REFINERY_CARDS_LOG_VIEW
|
||||
select "ID","ENTITIY_ID","METHOD_NAME","BALANCE_BEFORE","BALANCE_AFTER","CREATED_BY",to_char( "CREATION_DATE",'dd/mm/yyyy HH24:MI') CREATION_DATE,"UPDATED_BY",to_char(LAST_UPDATE_DATE,'dd/mm/yyyy HH24:MI') LAST_UPDATE_DATE, "AMOUNT","PN"
|
||||
from REFINERY_CARDS_LOG
|
||||
|
||||
|
||||
--- REFINERY_COMMISSION_CLAIM_VIEW
|
||||
select "ID","COMMISSION_CLAIM_NO",to_char("COMMISSION_CLAIM_DATE",'dd/mm/yyyy') COMMISSION_CLAIM_DATE,
|
||||
to_char(trunc(COMMISSION_CLAIM_DATE) , 'yyyymmdd') as COMMISSION_CLAIM_DATE_STRING,
|
||||
"STATUS_CODE" ,
|
||||
(select count(id) from refinery_wage_claim tr where tr.COMMISSION_claim_id = REFINERY_COMMISSION_CLAIM.id) trip_cnt
|
||||
from REFINERY_COMMISSION_CLAIM
|
||||
|
||||
|
||||
--- REFINERY_COMMISSION_LOG_VIEW
|
||||
select n.login,t."ID",t."ENTITIY_ID",t."METHOD_NAME",to_char(t."LOG_DATE",'dd/mm/yyyy HH24:MI') LOG_DATE,t."USER_ID",t."USER_IP",t."OLD_DATA",t."NEW_DATA" from refinery_commission_claim_log t
|
||||
join ntp.ntpusers n ON
|
||||
t.user_id = n.id(+)
|
||||
order by t.id desc
|
||||
|
||||
|
||||
--- REFINERY_TRIPS_VIEW
|
||||
select REFINERY_TRIPS."ID",
|
||||
"SECOND_ADVANCE_PAYMENT",
|
||||
"FIRST_ADVANCE_PAYMENT",
|
||||
"PN",REFINERY_TRIPS."STATUS_CODE",
|
||||
to_char("DISPATCH_DATE",'dd/mm/yyyy') DISPATCH_DATE,
|
||||
to_char("ACTUAL_LOADING_DATE",'dd/mm/yyyy') ACTUAL_LOADING_DATE,
|
||||
DateToString("ACTUAL_LOADING_DATE") ACTUAL_LOADING_DATE_STRING,
|
||||
DATETOSTRING(RECEIVED_DATE) RECEIVED_DATE_STRING,
|
||||
ACTUAL_LOADING_DATE LOADING_DATE,
|
||||
"ACTUAL_LOADING_TIME",
|
||||
Datetostring("DISCHARGE_ENTRY_DATE") DISCHARGE_ENTRY_DATE_STRING,
|
||||
"LOADING_CENTER","CLIENT_NO",comp.display_name CLIENT_NAME,
|
||||
REFINERY_TRIPS."TN","TRN",REFINERY_TRIPS."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_TIME",
|
||||
"DISCHARGE_EXIT_DATE",
|
||||
"DISCHARGE_EXIT_TIME",
|
||||
"ACTUAL_GROSS_WEIGHT",
|
||||
"ACTUAL_EMPTY_WEIGHT",
|
||||
"NET_DISCHARGE_WEIGHT",
|
||||
"NET_WAGE" ,REFINERY_TRIPS.DIESEL_CHARGE,
|
||||
wa.epayment,
|
||||
|
||||
decode(paid_wallet.wallet_number,null,wa.wallet_number,paid_wallet.wallet_number) wallet_number,
|
||||
decode(paid_wallet.company_code,null,wa.company_code,paid_wallet.company_code) company_code,
|
||||
decode(paid_wallet.owner_nnpn,null,wa.owner_nnpn,paid_wallet.owner_nnpn) owner_nnpn,
|
||||
decode(paid_wallet.owner_name,null,wa.owner_name,paid_wallet.owner_name) owner_name,
|
||||
decode(paid_wallet.owner_name_english,null,wa.owner_name_english,paid_wallet.owner_name_english) owner_name_english,
|
||||
decode(paid_wallet.iban,null,wa.iban,paid_wallet.iban) iban,
|
||||
decode(paid_wallet.bank_account,null,wa.bank_account,paid_wallet.bank_account) bank_account,
|
||||
decode(paid_wallet.bank_name,null,wa.bank_name,paid_wallet.bank_name) bank_name,
|
||||
|
||||
decode(wa.id,null,'0','1') as HAVE_PAYMENT_METHOD,
|
||||
drvr_wallet.wallet_number driver_wallet_number,
|
||||
decode(REFINERY_TRIPS.WAGE_CLAIM_ID ,null,'0','1') as HAS_WAGE_CLAIM,
|
||||
RECEIVED_BY,RECEIVED_DATE,PAYMENTED_BY,PAYMENTED_DATE,
|
||||
REFINERY_TRIPS.Payment_Options,
|
||||
REFINERY_TRIPS.VOUCHER_SERIAL_NUMBER,
|
||||
|
||||
--Datetostring("PAYMENTED_DATE") ,
|
||||
|
||||
--decode(REFINERY_TRIPS.Status_Code,'EXCHANGED',Datetostring(REFINERY_TRIPS.PAYMENTED_DATE),'READY_TO_PAY',Datetostring(REFINERY_TRIPS.Received_Date),
|
||||
--'DISCHARGED',Datetostring(REFINERY_TRIPS.ACTUAL_LOADING_DATE)) PAYMENTED_DATE_STRING,
|
||||
|
||||
Datetostring(REFINERY_TRIPS.ACTUAL_LOADING_DATE) PAYMENTED_DATE_STRING,
|
||||
|
||||
DISCHARGE_ENTRY_DATE,to_char("DISCHARGE_ENTRY_DATE",'dd/mm/yyyy') DISCHARGE_ENTRY_DATE_DISPLAY,
|
||||
to_char("PAYMENTED_DATE",'dd/mm/yyyy') PAYMENTED_DATE_DISPLAY,
|
||||
"WATER_AMOUNT","SEDIMENT_AMOUNT",REFINERY_TRIPS."TRIP_STATUS",REFINERY_TRIPS."USER_ID",REFINERY_TRIPS."LAST_UPDATE_DATE","DAY_TIME","PROGRAM_ID","WORK_STN_ID","EXCHANGE_CLAIM_NO","PAID_AMOUNT_WATER",
|
||||
WAGE_CLAIM_ID,
|
||||
rwc.wage_claim_no,
|
||||
info.name_ar DRVR,
|
||||
REVERSE_PAYMENT,
|
||||
S.FIRSTNAME RECEIVED_BY_NAME,
|
||||
LT.AR STATUS_CODE_AR,remarks,
|
||||
REFINERY_TRIPS.Loading_No,
|
||||
(NET_LOADING_WEIGHT - net_discharge_weight) as "WEIGHT_DIIERANCE",
|
||||
CARD.CARD_NUMBER,CARD.CURRENT_BALANCE,
|
||||
decode(wa.epayment,null,unistr('\0644\0627\0020\064A\0648\062C\062F'),'0',unistr('\062D\0648\0627\0644\0629'),'1',unistr('\0627\0644\0643\062A\0631\0648\0646\064A')) as PAYMENT_METHOD,
|
||||
--decode(wa.epayment,null,0,'0',1,'1',2) as PAYMENT_METHOD_CODE,
|
||||
decode(REFINERY_TRIPS.PAYMENT_OPTIONS,NULL,decode(wa.epayment,null,0,'0',1,'1',2),'CACH_PAYMENT',3) as PAYMENT_METHOD_CODE,
|
||||
Datetostring("PAYMENTED_DATE") PAYMENTED_DATE_STRING_SEARCH,
|
||||
|
||||
REFINERY_TRIPS.DINARAK_REFERENCE_ID , REFINERY_WALLET_ID ,
|
||||
(CASE WHEN WATER_AMOUNT > 0 THEN 1
|
||||
ELSE 0 END) as WATER_EXIST,
|
||||
|
||||
decode(paid_wallet.epayment,null,'','0',unistr('\062D\0648\0627\0644\0629'),'1',unistr('\0627\0644\0643\062A\0631\0648\0646\064A')) as paid_epayment
|
||||
,"TRIP_NET_WAGE" , "REMAINING_BALANCE" ,penalty_amount , penalty_quantity
|
||||
|
||||
from REFINERY_TRIPS,ntp.lt_caption lt,refinery_wage_claim rwc,drivers_info info,refinery_company comp,REFINERY_WALLET wa,NTP.NTPUSERS S,REFINERY_WALLET drvr_wallet,
|
||||
REFINERY_CARDS CARD,REFINERY_WALLET paid_wallet
|
||||
where LT.CODE(+) = 'REFINERYTRIP.STATUS.'|| REFINERY_TRIPS.STATUS_CODE
|
||||
and rwc.id(+)=REFINERY_TRIPS.Wage_Claim_Id
|
||||
and wa.tn(+)=REFINERY_TRIPS.tn
|
||||
and info.nnpn(+)=REFINERY_TRIPS.Nnpn
|
||||
and info.status_code(+) = 'COMPLETED'
|
||||
and comp.code(+) = CLIENT_NO
|
||||
AND s.id(+)=REFINERY_TRIPS.Received_By
|
||||
and to_char(drvr_wallet.driver_nnpn(+))=REFINERY_TRIPS.Nnpn
|
||||
and CARD.TN(+) = REFINERY_TRIPS.tn
|
||||
AND card.Status_Code(+) = 'ACTIVE'
|
||||
and wa.status_code(+) = 'ACTIVE'
|
||||
and drvr_wallet.Status_Code(+)='ACTIVE'
|
||||
and paid_wallet.id(+)=REFINERY_TRIPS.Refinery_Wallet_Id
|
||||
|
||||
|
||||
--- REFINERY_TRIPS_LOG_VIEW
|
||||
select n.login,t."ID",t."ENTITIY_ID",t."METHOD_NAME",to_char(t."LOG_DATE",'dd/mm/yyyy HH24:MI') LOG_DATE,t."USER_ID",t."USER_IP",t."OLD_DATA",t."NEW_DATA" from refinery_trips_LOG t
|
||||
join ntp.ntpusers n ON
|
||||
t.user_id = n.id(+)
|
||||
order by t.id desc
|
||||
|
||||
|
||||
--- REFINERY_VARIABLES_VIEW
|
||||
select rownum ID,GROUP_ID ,to_char("START_DATE",'yyyy-mm-dd') "START_DATE" , Datetostring("START_DATE") START_DATE_STRING, to_char("END_DATE",'yyyy-mm-dd') "END_DATE", Datetostring("END_DATE") END_DATE_STRING,"DIESEL_LITER_PRICE","TON_WAGE","TON_PRICE","DRIVER_TIP","PERMIT_DISPATCH","WAYBILL_FEE","COMMISSION","TOLERANCE_PERCENTAGE","FIRST_ADVANCE_PAYMENT" /*, TON_PRICE_CORRECTION */ from (
|
||||
select start_date,end_date,key_name,key_value ,GROUP_ID from REFINERY_VARIABLES where KEY_NAME != 'AUTDIT_MODE'
|
||||
)
|
||||
pivot
|
||||
(
|
||||
sum(key_value)
|
||||
for key_name in ('DIESEL_LITER_PRICE' DIESEL_LITER_PRICE,'TON_WAGE' TON_WAGE,'TON_PRICE' TON_PRICE,'DRIVER_TIP' DRIVER_TIP,'PERMIT_DISPATCH' PERMIT_DISPATCH,'WAYBILL_FEE' WAYBILL_FEE,'COMMISSION' COMMISSION,'TOLERANCE_PERCENTAGE' TOLERANCE_PERCENTAGE, 'FIRST_ADVANCE_PAYMENT' FIRST_ADVANCE_PAYMENT /* , 'TON_PRICE_CORRECTION' TON_PRICE_CORRECTION */)
|
||||
)
|
||||
order by 1
|
||||
|
||||
|
||||
--- REFINERY_WAGE_CLAIM_VIEW
|
||||
select REFINERY_WAGE_CLAIM."ID","WAGE_CLAIM_NO",to_char("WAGE_CLAIM_DATE",'dd/mm/yyyy') WAGE_CLAIM_DATE,REFINERY_WAGE_CLAIM."STATUS_CODE" ,COMMISSION_CLAIM_ID,
|
||||
decode(REFINERY_WAGE_CLAIM.COMMISSION_CLAIM_ID ,null,'0','1') as HAS_COMMISSION_CLAIM,
|
||||
(select count(id) from refinery_trips tr where tr.wage_claim_id = REFINERY_WAGE_CLAIM.id) trip_cnt,comm.commission_claim_no
|
||||
from REFINERY_WAGE_CLAIM,refinery_commission_claim comm
|
||||
where comm.id(+)=REFINERY_WAGE_CLAIM.COMMISSION_CLAIM_ID
|
||||
|
||||
|
||||
--- REFINERY_WAGE_CLAIM_LOG_VIEW
|
||||
select n.login,t."ID",t."ENTITIY_ID",t."METHOD_NAME",to_char(t."LOG_DATE",'dd/mm/yyyy HH24:MI') LOG_DATE,t."USER_ID",t."USER_IP",t."OLD_DATA",t."NEW_DATA" from refinery_wage_claim_log t
|
||||
join ntp.ntpusers n ON
|
||||
t.user_id = n.id(+)
|
||||
order by t.id desc
|
||||
|
||||
|
||||
--- REFINERY_WALLET_VIEW
|
||||
select "ID"
|
||||
,"TN"
|
||||
,"COMPANY_CODE"
|
||||
,"EPAYMENT"
|
||||
,decode("OWNER_NNPN",null,DRIVER_NNPN,OWNER_NNPN) OWNER_NNPN
|
||||
,decode("OWNER_NNPN",null,DRIVER_NNPN,OWNER_NNPN) NNPN
|
||||
,"WALLET_NUMBER"
|
||||
,decode("OWNER_NAME",null,DRIVER_NAME,OWNER_NAME) OWNER_NAME
|
||||
,"CREATION_DATE"
|
||||
,"DRIVER_NAME"
|
||||
,"DRIVER_NNPN"
|
||||
,"IBAN"
|
||||
,"BANK_ACCOUNT"
|
||||
,"BANK_NAME"
|
||||
,"CREATED_BY"
|
||||
,"UPDATE_DATE"
|
||||
,"UPDATED_BY"
|
||||
,"STATUS_CODE"
|
||||
,"BANK_BRANCH","OWNER_NAME_ENGLISH",
|
||||
----,DECODE("EPAYMENT",0,unistr('\062D\0648\0627\0644\0629'),unistr('\0645\062D\0641\0638\0629\0020\0627\0644\0643\062A\0631\0648\0646\064A\0629')) PAYMENT_METHOD,
|
||||
( CASE
|
||||
WHEN DRIVER_NNPN is not null THEN 'DRAIVER_WALLET'
|
||||
WHEN EPAYMENT = 0 THEN 'BANK'
|
||||
|
||||
ELSE 'EWALLET'
|
||||
END ) PAYMENT_METHOD
|
||||
from REFINERY_WALLET
|
||||
|
||||
|
||||
--- REFINERY_WALLET_LOG_VIEW
|
||||
select n.login,t."ID",t."ENTITIY_ID",t."METHOD_NAME",to_char(t."LOG_DATE",'dd/mm/yyyy HH24:MI') LOG_DATE,t."USER_ID",t."USER_IP",t."OLD_DATA",t."NEW_DATA" from refinery_WALLET_LOG t
|
||||
join ntp.ntpusers n ON
|
||||
t.user_id = n.id(+)
|
||||
order by t.id desc
|
||||
|
||||
|
||||
--- REFINERY_DIESEL_REPORT_VIEW
|
||||
select T.ID, t.pn,t.tn,T.STATUS_CODE,
|
||||
t.discharge_authoriztion_no,c.creation_date,
|
||||
s.firstname,
|
||||
t.DIESEL_CHARGE,
|
||||
|
||||
decode (c.method_name,'FIRST_ADVANCED_PAYMENT',unistr('\0634\062D\0646\0020\0644\0644\062A\062D\0645\064A\0644'),'SECOND_ADVANCED_PAYMENT',unistr('\0634\062D\0646\0020\0644\0644\062A\0641\0631\064A\063A'),'SECOND_ADVANCED_PAYMENT_REVERSE',unistr('\0627\0644\063A\0627\0621\0020\0634\062D\0646\0020\0627\0644\062A\0641\0631\064A\063A'),'FIRST_ADVANCED_PAYMENT_REVERSE',unistr('\0627\0644\063A\0627\0621\0020\0634\062D\0646\0020\0627\0644\062A\062D\0645\064A\0644')) method_name,
|
||||
|
||||
c.balance_before,c.balance_after,C.AMOUNT from refinery_trips_view t,refinery_cards_log c,NTP.NTPUSERS s
|
||||
|
||||
where c.PN=t.PN
|
||||
and s.id(+)=to_number(c.created_by)
|
||||
|
||||
ORDER BY CREATION_DATE
|
||||
|
||||
|
||||
--- REFINERY_CLAIMS_REPORT_VIEW
|
||||
select t."ID",t.WAGE_CLAIM_ID, t.STATUS_CODE,TRIP_STATUS, "DISCHARGE_AUTHORIZTION_NO",discharge_authoriztion_year, to_char(Discharge_Entry_Date , 'dd/mm/yyyy' ) Discharge_Entry_Date, client_no, '' client_NAME,'' serial,loading_no , to_char(actual_loading_date , 'dd/mm/yyyy') actual_loading_date , NET_LOADING_WEIGHT,WATER_AMOUNT , NET_DISCHARGE_WEIGHT
|
||||
,(NET_LOADING_WEIGHT - net_discharge_weight) as "WEIGHT_DIIERANCE",
|
||||
TON_WAGE ,CALCULATED_QUANTITY_TON ,QUANTITY_WAGE ,w.wage_claim_no, TOLERANCE_QUANTITY ,
|
||||
(CASE
|
||||
WHEN Water_amount > 0 THEN
|
||||
'YES'
|
||||
ELSE 'NO'
|
||||
END) WATER_EXIST,
|
||||
|
||||
|
||||
CASE
|
||||
WHEN (NET_LOADING_WEIGHT - net_discharge_weight) < TOLERANCE_QUANTITY THEN
|
||||
ltrim(to_char(0, '0.000'))
|
||||
ELSE ltrim(to_char(PENALTY_QUANTITY, '9999999.999'))
|
||||
END PENALTY_QUANTITY,
|
||||
|
||||
--ltrim(to_char(PENALTY_QUANTITY, '9999999.999')) PENALTY_QUANTITY ,
|
||||
ltrim(to_char(TON_PRICE, '9999999.999')) TON_PRICE ,
|
||||
PENALTY_AMOUNT,
|
||||
ltrim(to_char(DRIVER_TIP, '9999999.999')) DRIVER_TIP ,
|
||||
ltrim(to_char(PERMIT_DISPATCH, '9999999.999')) PERMIT_DISPATCH ,
|
||||
WAYBILL_FEE,DIESEL_LITER_PRICE,
|
||||
ltrim(to_char((select sum(amount) from REFINERY_CARDS_LOG where pn = t.pn),'9999999.99')) advance_payment_FOR_DIESEL,
|
||||
ltrim(to_char(COMMISSION, '9999999.999')) COMMISSION ,
|
||||
ltrim(to_char(NET_WAGE, '9999999.999')) NET_WAGE,T.TN,info.name_ar DRVR
|
||||
|
||||
from REFINERY_TRIPS t,refinery_wage_claim w,DRIVERS_INFO info
|
||||
|
||||
where w.id=t.wage_claim_id
|
||||
and info.nnpn(+)=t.Nnpn
|
||||
and info.status_code(+) = 'COMPLETED'
|
||||
|
||||
|
||||
--- REFINERY_CLAIMS_REPORT
|
||||
select "ID",STATUS_CODE,TRIP_STATUS, "DISCHARGE_AUTHORIZTION_NO",discharge_authoriztion_year, Discharge_Entry_Date, client_no, '' client_NAME,'' serial,loading_no , actual_loading_date, NET_LOADING_WEIGHT,Water_amount , net_discharge_weight ,(NET_LOADING_WEIGHT - net_discharge_weight) as "WEIGHT_DIIERANCE",
|
||||
TON_WAGE ,CALCULATED_QUANTITY_TON ,QUANTITY_WAGE , TOLERANCE_QUANTITY ,
|
||||
(CASE
|
||||
WHEN Water_amount > 0 THEN
|
||||
'YES'
|
||||
ELSE 'NO'
|
||||
END) WATER_EXIST,
|
||||
ltrim(to_char(PENALTY_QUANTITY, '9999999.99')) PENALTY_QUANTITY ,
|
||||
ltrim(to_char(TON_PRICE, '9999999.99')) TON_PRICE ,
|
||||
PENALTY_AMOUNT,
|
||||
ltrim(to_char(DRIVER_TIP, '9999999.99')) DRIVER_TIP ,
|
||||
ltrim(to_char(PERMIT_DISPATCH, '9999999.99')) PERMIT_DISPATCH ,
|
||||
WAYBILL_FEE,DIESEL_LITER_PRICE,
|
||||
ltrim(to_char((select sum(amount) from REFINERY_CARDS_LOG where pn = REFINERY_TRIPS.pn),'9999999.99')) advance_payment_FOR_DIESEL,
|
||||
COMMISSION ,NET_WAGE
|
||||
from REFINERY_TRIPS
|
||||
|
||||
|
||||
=== FUNCTIONS ===
|
||||
|
||||
--- CALCULATEREFINARYDIESEL
|
||||
FUNCTION "CALCULATEREFINARYDIESEL" (RefineryId in numeric)
|
||||
|
||||
return float as
|
||||
|
||||
|
||||
|
||||
DieslCount number;
|
||||
|
||||
LoadingDate date;
|
||||
|
||||
CURRENT_BALANCE float;
|
||||
|
||||
DIESEL_LITER_PRICE float;
|
||||
|
||||
FIRST_ADVANCE_PAYMENT float;
|
||||
|
||||
begin
|
||||
|
||||
|
||||
|
||||
select LOADING_DATE,CURRENT_BALANCE
|
||||
|
||||
into LoadingDate,CURRENT_BALANCE
|
||||
|
||||
from refinery_trips_view where id = RefineryId;
|
||||
|
||||
|
||||
|
||||
SELECT ( select DIESEL_CHARGE from REFINERY_TRIPS where ID = RefineryId)
|
||||
|
||||
into DieslCount FROM DUAL;
|
||||
|
||||
|
||||
|
||||
select key_value into FIRST_ADVANCE_PAYMENT
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'FIRST_ADVANCE_PAYMENT'
|
||||
|
||||
and sysdate between start_date and end_date +1 ;
|
||||
|
||||
|
||||
|
||||
if DieslCount = 0 then -- No First Payment
|
||||
|
||||
return FIRST_ADVANCE_PAYMENT+CURRENT_BALANCE;
|
||||
|
||||
else if DieslCount = 1 then -- No Second Payment
|
||||
|
||||
|
||||
|
||||
-- Get Liter current price
|
||||
|
||||
select key_value into DIESEL_LITER_PRICE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'DIESEL_LITER_PRICE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
|
||||
|
||||
return (DIESEL_LITER_PRICE * 350)+CURRENT_BALANCE-FIRST_ADVANCE_PAYMENT;
|
||||
|
||||
else
|
||||
|
||||
return CURRENT_BALANCE;
|
||||
|
||||
end if;
|
||||
|
||||
end if;
|
||||
|
||||
|
||||
|
||||
end CalculateRefinaryDiesel;
|
||||
|
||||
|
||||
--- CALCULATEREFINARYAMOUNT
|
||||
FUNCTION "CALCULATEREFINARYAMOUNT" (RefineryId in numeric)
|
||||
|
||||
return float as
|
||||
|
||||
FIRST_ADVANCE_PAYMENT float;
|
||||
|
||||
DIESEL_LITER_PRICE float;
|
||||
|
||||
TON_WAGE float;
|
||||
|
||||
TON_PRICE float;
|
||||
|
||||
DRIVER_TIP float;
|
||||
|
||||
PERMIT_DISPATCH float;
|
||||
|
||||
WAYBILL_FEE float;
|
||||
|
||||
COMMISSION float;
|
||||
|
||||
TOLERANCE_PERCENTAGE float;
|
||||
|
||||
NetLoadingWeight int;
|
||||
|
||||
NetDischargeWeight int;
|
||||
|
||||
CalculatedAmount float;
|
||||
|
||||
WaterAmount int;
|
||||
|
||||
FineQuantity float;
|
||||
|
||||
AllowQuantity float;
|
||||
|
||||
LoadingDate Date;
|
||||
|
||||
truckNumber int;
|
||||
|
||||
REMAINING_BALANCE float;
|
||||
|
||||
begin
|
||||
|
||||
select tn,net_loading_weight,
|
||||
|
||||
net_discharge_weight,
|
||||
|
||||
water_amount,
|
||||
|
||||
actual_loading_date
|
||||
|
||||
into truckNumber,NetLoadingWeight, NetDischargeWeight, WaterAmount, LoadingDate
|
||||
|
||||
from refinery_trips
|
||||
|
||||
where id = RefineryId;
|
||||
|
||||
select key_value
|
||||
|
||||
into FIRST_ADVANCE_PAYMENT
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'FIRST_ADVANCE_PAYMENT'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into DIESEL_LITER_PRICE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'DIESEL_LITER_PRICE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into TON_WAGE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'TON_WAGE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into TON_PRICE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'TON_PRICE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into DRIVER_TIP
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'DRIVER_TIP'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into PERMIT_DISPATCH
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'PERMIT_DISPATCH'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into WAYBILL_FEE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'WAYBILL_FEE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into COMMISSION
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'COMMISSION'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into TOLERANCE_PERCENTAGE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'TOLERANCE_PERCENTAGE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
|
||||
|
||||
AllowQuantity := FLOOR(NetLoadingWeight * TOLERANCE_PERCENTAGE);
|
||||
|
||||
|
||||
|
||||
FineQuantity := (NetLoadingWeight - NetDischargeWeight - WaterAmount);
|
||||
|
||||
|
||||
|
||||
IF FineQuantity <= AllowQuantity THEN
|
||||
|
||||
FineQuantity := 0;
|
||||
|
||||
else
|
||||
|
||||
FineQuantity := FineQuantity - AllowQuantity;
|
||||
|
||||
end if;
|
||||
|
||||
|
||||
|
||||
FineQuantity := (FineQuantity / 1000) * TON_PRICE;
|
||||
|
||||
|
||||
|
||||
IF WaterAmount >= (NetLoadingWeight - NetDischargeWeight) THEN
|
||||
|
||||
CalculatedAmount := (NetLoadingWeight) / 1000;
|
||||
|
||||
ELSE
|
||||
|
||||
CalculatedAmount := (NetDischargeWeight + WaterAmount) / 1000;
|
||||
|
||||
end if;
|
||||
|
||||
|
||||
|
||||
CalculatedAmount := (CalculatedAmount * TON_WAGE) - FineQuantity -
|
||||
|
||||
DRIVER_TIP - PERMIT_DISPATCH - WAYBILL_FEE -
|
||||
|
||||
(DIESEL_LITER_PRICE * 350) - COMMISSION;
|
||||
|
||||
|
||||
|
||||
--- calcualte amount after remaining balance
|
||||
|
||||
select remaining_balance
|
||||
|
||||
into REMAINING_BALANCE
|
||||
|
||||
from REFINERY_REMAINING_BALANCE
|
||||
|
||||
where tn = truckNumber ;
|
||||
|
||||
CalculatedAmount := CalculatedAmount +REMAINING_BALANCE;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return ROUND(CalculatedAmount, 3);
|
||||
|
||||
|
||||
|
||||
end CalculateRefinaryAmount;
|
||||
|
||||
|
||||
--- CALCULATEREFINARYAMOUNT6
|
||||
FUNCTION "CALCULATEREFINARYAMOUNT6" (RefineryId in numeric)
|
||||
|
||||
return float as
|
||||
|
||||
FIRST_ADVANCE_PAYMENT float;
|
||||
|
||||
DIESEL_LITER_PRICE float;
|
||||
|
||||
TON_WAGE float;
|
||||
|
||||
TON_PRICE float;
|
||||
|
||||
DRIVER_TIP float;
|
||||
|
||||
PERMIT_DISPATCH float;
|
||||
|
||||
WAYBILL_FEE float;
|
||||
|
||||
COMMISSION float;
|
||||
|
||||
TOLERANCE_PERCENTAGE float;
|
||||
|
||||
NetLoadingWeight int;
|
||||
|
||||
NetDischargeWeight int;
|
||||
|
||||
CalculatedAmount float;
|
||||
|
||||
WaterAmount int;
|
||||
|
||||
FineQuantity float;
|
||||
|
||||
AllowQuantity float;
|
||||
|
||||
LoadingDate Date;
|
||||
|
||||
truckNumber int;
|
||||
|
||||
REMAINING_BALANCE float;
|
||||
|
||||
begin
|
||||
|
||||
select tn,net_loading_weight,
|
||||
|
||||
net_discharge_weight,
|
||||
|
||||
water_amount,
|
||||
|
||||
actual_loading_date
|
||||
|
||||
into truckNumber,NetLoadingWeight, NetDischargeWeight, WaterAmount, LoadingDate
|
||||
|
||||
from refinery_trips
|
||||
|
||||
where id = RefineryId;
|
||||
|
||||
select key_value
|
||||
|
||||
into FIRST_ADVANCE_PAYMENT
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'FIRST_ADVANCE_PAYMENT'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into DIESEL_LITER_PRICE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'DIESEL_LITER_PRICE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into TON_WAGE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'TON_WAGE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into TON_PRICE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'TON_PRICE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into DRIVER_TIP
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'DRIVER_TIP'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into PERMIT_DISPATCH
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'PERMIT_DISPATCH'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into WAYBILL_FEE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'WAYBILL_FEE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into COMMISSION
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'COMMISSION'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into TOLERANCE_PERCENTAGE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'TOLERANCE_PERCENTAGE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
|
||||
|
||||
AllowQuantity := FLOOR(NetLoadingWeight * TOLERANCE_PERCENTAGE);
|
||||
|
||||
|
||||
|
||||
FineQuantity := (NetLoadingWeight - NetDischargeWeight - WaterAmount);
|
||||
|
||||
|
||||
|
||||
IF FineQuantity <= AllowQuantity THEN
|
||||
|
||||
FineQuantity := 0;
|
||||
|
||||
else
|
||||
|
||||
FineQuantity := FineQuantity - AllowQuantity;
|
||||
|
||||
end if;
|
||||
|
||||
|
||||
|
||||
FineQuantity := (FineQuantity / 1000) * TON_PRICE;
|
||||
|
||||
|
||||
|
||||
IF WaterAmount >= (NetLoadingWeight - NetDischargeWeight) THEN
|
||||
|
||||
CalculatedAmount := (NetLoadingWeight) / 1000;
|
||||
|
||||
ELSE
|
||||
|
||||
CalculatedAmount := (NetDischargeWeight + WaterAmount) / 1000;
|
||||
|
||||
end if;
|
||||
|
||||
|
||||
|
||||
CalculatedAmount := (CalculatedAmount * TON_WAGE) - FineQuantity -
|
||||
|
||||
DRIVER_TIP - PERMIT_DISPATCH - WAYBILL_FEE -
|
||||
|
||||
(DIESEL_LITER_PRICE * 350) - COMMISSION;
|
||||
|
||||
|
||||
|
||||
--- calcualte amount after remaining balance
|
||||
|
||||
select remaining_balance
|
||||
|
||||
into REMAINING_BALANCE
|
||||
|
||||
from REFINERY_REMAINING_BALANCE
|
||||
|
||||
where tn = truckNumber ;
|
||||
|
||||
CalculatedAmount := CalculatedAmount +REMAINING_BALANCE;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return ROUND(CalculatedAmount, 3);
|
||||
|
||||
|
||||
|
||||
end CalculateRefinaryAmount6;
|
||||
|
||||
|
||||
--- CALCULATEREFINARYAMOUNTREPORT
|
||||
FUNCTION "CALCULATEREFINARYAMOUNTREPORT" (RefineryId in numeric,calType in numeric)
|
||||
|
||||
return float as
|
||||
|
||||
FIRST_ADVANCE_PAYMENT float;
|
||||
|
||||
DIESEL_LITER_PRICE float;
|
||||
|
||||
TON_WAGE float;
|
||||
|
||||
TON_PRICE float;
|
||||
|
||||
DRIVER_TIP float;
|
||||
|
||||
PERMIT_DISPATCH float;
|
||||
|
||||
WAYBILL_FEE float;
|
||||
|
||||
COMMISSION float;
|
||||
|
||||
TOLERANCE_PERCENTAGE float;
|
||||
|
||||
NetLoadingWeight int;
|
||||
|
||||
NetDischargeWeight int;
|
||||
|
||||
CalculatedAmount float;
|
||||
|
||||
WaterAmount int;
|
||||
|
||||
FineQuantity float;
|
||||
|
||||
AllowQuantity float;
|
||||
|
||||
LoadingDate Date;
|
||||
|
||||
begin
|
||||
|
||||
|
||||
|
||||
select net_loading_weight,
|
||||
|
||||
net_discharge_weight,
|
||||
|
||||
water_amount,
|
||||
|
||||
actual_loading_date
|
||||
|
||||
into NetLoadingWeight, NetDischargeWeight, WaterAmount, LoadingDate
|
||||
|
||||
from refinery_trips
|
||||
|
||||
where id = RefineryId;
|
||||
|
||||
select key_value
|
||||
|
||||
into FIRST_ADVANCE_PAYMENT
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'FIRST_ADVANCE_PAYMENT'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into DIESEL_LITER_PRICE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'DIESEL_LITER_PRICE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into TON_WAGE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'TON_WAGE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into TON_PRICE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'TON_PRICE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into DRIVER_TIP
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'DRIVER_TIP'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into PERMIT_DISPATCH
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'PERMIT_DISPATCH'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into WAYBILL_FEE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'WAYBILL_FEE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into COMMISSION
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'COMMISSION'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
select key_value
|
||||
|
||||
into TOLERANCE_PERCENTAGE
|
||||
|
||||
from refinery_variables
|
||||
|
||||
where KEY_NAME = 'TOLERANCE_PERCENTAGE'
|
||||
|
||||
and LoadingDate between start_date and end_date;
|
||||
|
||||
|
||||
|
||||
AllowQuantity := FLOOR(NetLoadingWeight * TOLERANCE_PERCENTAGE);
|
||||
|
||||
|
||||
|
||||
FineQuantity := (NetLoadingWeight - NetDischargeWeight - WaterAmount);
|
||||
|
||||
|
||||
|
||||
IF FineQuantity <= AllowQuantity THEN
|
||||
|
||||
FineQuantity := 0;
|
||||
|
||||
else
|
||||
|
||||
FineQuantity := FineQuantity - AllowQuantity;
|
||||
|
||||
end if;
|
||||
|
||||
|
||||
|
||||
FineQuantity := (FineQuantity / 1000) * TON_PRICE;
|
||||
|
||||
|
||||
|
||||
IF WaterAmount >= (NetLoadingWeight - NetDischargeWeight) THEN
|
||||
|
||||
CalculatedAmount := (NetLoadingWeight) / 1000;
|
||||
|
||||
ELSE
|
||||
|
||||
CalculatedAmount := (NetDischargeWeight + WaterAmount) / 1000;
|
||||
|
||||
end if;
|
||||
|
||||
|
||||
|
||||
if calType = 0 then
|
||||
|
||||
CalculatedAmount := (CalculatedAmount * TON_WAGE) - FineQuantity -
|
||||
|
||||
DRIVER_TIP - PERMIT_DISPATCH - WAYBILL_FEE -
|
||||
|
||||
(DIESEL_LITER_PRICE * 350) - COMMISSION;
|
||||
|
||||
|
||||
|
||||
return ROUND(CalculatedAmount, 4);
|
||||
|
||||
|
||||
|
||||
else
|
||||
|
||||
|
||||
|
||||
return ROUND(CalculatedAmount*TON_WAGE, 4);
|
||||
|
||||
end if;
|
||||
|
||||
|
||||
|
||||
end CalculateRefinaryAmountReport;
|
||||
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -234,12 +234,12 @@ public sealed class OrderReportsController(IOrderReportService reports) : Contro
|
|||
public Task<TenderOrderReportDto> TenderOrders([FromQuery] DateTime orderDate, CancellationToken ct) =>
|
||||
reports.GetTenderOrderReportAsync(orderDate, ct);
|
||||
|
||||
/// format: csv (default) or xlsx.
|
||||
/// Legacy Excel (HTML table) of the distribution ratios.
|
||||
[HttpGet("tender-orders/export")]
|
||||
[RequirePermission(PermissionKeys.OrdersReportOrders)]
|
||||
public async Task<IActionResult> ExportTenderOrders([FromQuery] DateTime orderDate, [FromQuery] string format = "csv", CancellationToken ct = default)
|
||||
public async Task<IActionResult> ExportTenderOrders([FromQuery] DateTime orderDate, CancellationToken ct = default)
|
||||
{
|
||||
var f = await reports.ExportTenderOrderReportAsync(orderDate, format, ct);
|
||||
var f = await reports.ExportTenderOrderReportAsync(orderDate, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@ public sealed class RegistryController(
|
|||
IRegistryOpsService ops,
|
||||
IRegistryLookupService lookups,
|
||||
IRegistryAttachmentService attachments,
|
||||
IRegistryQueuePermitService queuePermits) : ControllerBase
|
||||
IRegistryQueuePermitService queuePermits,
|
||||
IRegistryExportService exports) : ControllerBase
|
||||
{
|
||||
// ------------------------------------------------------------------------------------------ permissions + lookups
|
||||
|
||||
|
|
@ -67,6 +68,33 @@ public sealed class RegistryController(
|
|||
[FromQuery] string? headType, [FromQuery] long? tcscac, [FromQuery] int page = 1, [FromQuery] int pageSize = 15, CancellationToken ct = default) =>
|
||||
trucks.SearchAsync(new TruckListQuery(searchType, tn, chasesNumber, statusCode, headType, tcscac), new PageRequest(page, pageSize), ct);
|
||||
|
||||
/// <summary>Excel of the filtered truck / trailer list (legacy openTruckReportExcel; right from GRAINS_SCREEN_PERMISSIONS).</summary>
|
||||
[HttpGet("trucks/export")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucksExport)]
|
||||
public async Task<IActionResult> ExportTrucks([FromQuery] string? searchType, [FromQuery] string? tn, [FromQuery] string? chasesNumber, [FromQuery] string? statusCode,
|
||||
[FromQuery] string? headType, [FromQuery] long? tcscac, CancellationToken ct)
|
||||
{
|
||||
var f = await exports.ExportTrucksAsync(new TruckListQuery(searchType, tn, chasesNumber, statusCode, headType, tcscac), ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
[HttpGet("trailers/export")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrailersExport)]
|
||||
public async Task<IActionResult> ExportTrailers([FromQuery] string? tn, [FromQuery] string? chasesNumber, [FromQuery] string? statusCode, [FromQuery] long? tcscac, CancellationToken ct)
|
||||
{
|
||||
var f = await exports.ExportTrailersAsync(new TrailerListQuery(tn, chasesNumber, statusCode, tcscac), ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
/// <summary>Excel of the filtered driver list (legacy openDriversReportExcel; right from GRAINS_SCREEN_PERMISSIONS).</summary>
|
||||
[HttpGet("drivers/export")]
|
||||
[RequirePermission(PermissionKeys.RegistryDriversExport)]
|
||||
public async Task<IActionResult> ExportDrivers([FromQuery] string? nnpn, [FromQuery] string? name, [FromQuery] string? statusCode, CancellationToken ct)
|
||||
{
|
||||
var f = await exports.ExportDriversAsync(new DriverListQuery(nnpn, name, statusCode), ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
/// <summary>getTruckInfo (+ connected trailer, destinations, attachments).</summary>
|
||||
[HttpGet("trucks/{id:long}")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks)]
|
||||
|
|
|
|||
|
|
@ -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, Ip);
|
||||
|
||||
[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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Api.Authorization;
|
||||
using NTP.Application.Access;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.Cards;
|
||||
|
||||
namespace NTP.Api.Controllers.V1.Refinery;
|
||||
|
||||
/// <summary>Refinery diesel cards (بطاقات الديزل): port of refinery_cards*.cfc. Access by permission keys only (SU / REFINERY_MGR).</summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/refinery/cards")]
|
||||
[Produces("application/json")]
|
||||
public sealed class CardsController(ICardsService cards) : ControllerBase
|
||||
{
|
||||
private static IReadOnlyList<string> Split(string? statusCode) =>
|
||||
(statusCode ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
/// <summary>search: filters tn and cardNumber (exact), statusCode (one or several, comma separated).</summary>
|
||||
[HttpGet]
|
||||
[RequirePermission(PermissionKeys.RefineryCards)]
|
||||
public Task<PagedResult<CardRow>> Search([FromQuery] string? tn, [FromQuery] string? cardNumber, [FromQuery] string? statusCode,
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 16, CancellationToken ct = default) =>
|
||||
cards.SearchAsync(new CardsQuery(tn, cardNumber, Split(statusCode)), new PageRequest(page, pageSize), ct);
|
||||
|
||||
[HttpGet("export")]
|
||||
[RequirePermission(PermissionKeys.RefineryCardsReport)]
|
||||
public async Task<IActionResult> Export([FromQuery] string? tn, [FromQuery] string? cardNumber, [FromQuery] string? statusCode, CancellationToken ct)
|
||||
{
|
||||
var f = await cards.ExportAsync(new CardsQuery(tn, cardNumber, Split(statusCode)), ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
[HttpGet("{id:long}")]
|
||||
[RequirePermission(PermissionKeys.RefineryCards)]
|
||||
public Task<CardRow> Get(long id, CancellationToken ct) => cards.GetAsync(id, ct);
|
||||
|
||||
/// <summary>log: movements of the card (create, activate, deactivate, diesel top-ups of the trips).</summary>
|
||||
[HttpGet("{id:long}/log")]
|
||||
[RequirePermission(PermissionKeys.RefineryCards)]
|
||||
public Task<PagedResult<CardLogRow>> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 5, CancellationToken ct = default) =>
|
||||
cards.GetLogAsync(id, new PageRequest(page, pageSize), ct);
|
||||
|
||||
[HttpPost]
|
||||
[RequirePermission(PermissionKeys.RefineryCardsCreate)]
|
||||
public Task<CardsResult> Create([FromBody] CreateCardRequest request, CancellationToken ct) => cards.CreateAsync(request, ct);
|
||||
|
||||
[HttpPost("{id:long}/activate")]
|
||||
[RequirePermission(PermissionKeys.RefineryCardsActivate)]
|
||||
public Task<CardsResult> Activate(long id, CancellationToken ct) => cards.ActivateAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/deactivate")]
|
||||
[RequirePermission(PermissionKeys.RefineryCardsDeactivate)]
|
||||
public Task<CardsResult> Deactivate(long id, CancellationToken ct) => cards.DeactivateAsync(id, ct);
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Api.Authorization;
|
||||
using NTP.Application.Access;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.CommissionClaims;
|
||||
using NTP.Application.Refinery.WageClaims;
|
||||
|
||||
namespace NTP.Api.Controllers.V1.Refinery;
|
||||
|
||||
/// <summary>
|
||||
/// Refinery commission claims (مطالبة العمولة): port of backend\entities\refinery_commission_claim. Thin controller; the rules are in
|
||||
/// <see cref="ICommissionClaimService"/>. Search / view / log need the screen key, every action its own key.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/refinery/commission-claims")]
|
||||
[Produces("application/json")]
|
||||
public sealed class CommissionClaimsController(ICommissionClaimService claims) : ControllerBase
|
||||
{
|
||||
private string? Ip => HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
/// <summary>The grid: COMMISSION_CLAIM_NO, COMMISSION_CLAIM_DATE, STATUS_CODE (comma list).</summary>
|
||||
[HttpGet]
|
||||
[RequirePermission(PermissionKeys.RefineryCommissionClaims)]
|
||||
public Task<PagedResult<CommissionClaimRowDto>> Search(
|
||||
[FromQuery] string? commissionClaimNo, [FromQuery] DateOnly? commissionClaimDate, [FromQuery] string? statusCode,
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) =>
|
||||
claims.SearchAsync(new CommissionClaimQuery(commissionClaimNo, commissionClaimDate, Split(statusCode)), new PageRequest(page, pageSize), ct);
|
||||
|
||||
[HttpGet("{id:long}")]
|
||||
[RequirePermission(PermissionKeys.RefineryCommissionClaims)]
|
||||
public Task<CommissionClaimRowDto> Get(long id, CancellationToken ct) => claims.GetAsync(id, ct);
|
||||
|
||||
/// <summary>The wage claims grouped by the commission claim.</summary>
|
||||
[HttpGet("{id:long}/wage-claims")]
|
||||
[RequirePermission(PermissionKeys.RefineryCommissionClaims)]
|
||||
public Task<IReadOnlyList<WageClaimRowDto>> WageClaims(long id, CancellationToken ct) => claims.WageClaimsAsync(id, ct);
|
||||
|
||||
/// <summary>Create dialog: wage claims without a commission claim (statusCode NEW and / or CLOSE, default both).</summary>
|
||||
[HttpGet("wage-claim-candidates")]
|
||||
[RequirePermission(PermissionKeys.RefineryCommissionClaimsCreate)]
|
||||
public Task<IReadOnlyList<WageClaimRowDto>> Candidates([FromQuery] string? statusCode, CancellationToken ct) =>
|
||||
claims.CandidateWageClaimsAsync(Split(statusCode), ct);
|
||||
|
||||
[HttpGet("{id:long}/log")]
|
||||
[RequirePermission(PermissionKeys.RefineryCommissionClaims)]
|
||||
public Task<PagedResult<ClaimLogRowDto>> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 5, CancellationToken ct = default) =>
|
||||
claims.LogAsync(id, new PageRequest(page, pageSize), ct);
|
||||
|
||||
[HttpPost]
|
||||
[RequirePermission(PermissionKeys.RefineryCommissionClaimsCreate)]
|
||||
public Task<ClaimResult> Create(CreateCommissionClaimRequest request, CancellationToken ct) => claims.CreateAsync(request, Ip, ct);
|
||||
|
||||
/// <summary>CLAIM_COMPLETE.</summary>
|
||||
[HttpPost("{id:long}/complete")]
|
||||
[RequirePermission(PermissionKeys.RefineryCommissionClaimsComplete)]
|
||||
public Task<ClaimResult> Complete(long id, CancellationToken ct) => claims.CompleteAsync(id, Ip, ct);
|
||||
|
||||
/// <summary>REPORT: the monthly commission invoice as an Excel file.</summary>
|
||||
[HttpGet("{id:long}/report")]
|
||||
[RequirePermission(PermissionKeys.RefineryCommissionClaimsReport)]
|
||||
public async Task<IActionResult> Report(long id, CancellationToken ct)
|
||||
{
|
||||
var f = await claims.ReportAsync(id, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string> Split(string? s) =>
|
||||
(s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
}
|
||||
|
|
@ -0,0 +1,180 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Api.Authorization;
|
||||
using NTP.Application.Access;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.RemainingBalance;
|
||||
using NTP.Application.Refinery.Trips;
|
||||
|
||||
namespace NTP.Api.Controllers.V1.Refinery;
|
||||
|
||||
/// <summary>
|
||||
/// Refinery trips (legacy REFINERYTRIP: refinerytripfactoryweb.cfc, REFINERYTRIPGRID / REFINERYTRIP / REFINERYTRIPLOG screens).
|
||||
/// Each action has its own permission key (PermissionKeys.Refinery.Trips.cs); the list, the form and the history use the screen key.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/refinery/trips")]
|
||||
[Produces("application/json")]
|
||||
public sealed class TripsController(
|
||||
ITripQueryService queries,
|
||||
ITripActionService actions,
|
||||
ITripReportService reports,
|
||||
IRemainingBalanceService balances) : ControllerBase
|
||||
{
|
||||
// ---- list, form, history
|
||||
[HttpGet]
|
||||
[RequirePermission(PermissionKeys.RefineryTrips)]
|
||||
public Task<PagedResult<TripGridDto>> Search([FromQuery] TripQuery query, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) =>
|
||||
queries.SearchAsync(query, new PageRequest(page, pageSize), ct);
|
||||
|
||||
[HttpGet("{id:long}")]
|
||||
[ProducesResponseType<TripDetailDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[RequirePermission(PermissionKeys.RefineryTrips)]
|
||||
public Task<TripDetailDto> Get(long id, CancellationToken ct) => queries.GetAsync(id, ct);
|
||||
|
||||
[HttpGet("{id:long}/log")]
|
||||
[RequirePermission(PermissionKeys.RefineryTrips)]
|
||||
public Task<PagedResult<TripLogDto>> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) =>
|
||||
queries.LogAsync(id, new PageRequest(page, pageSize), ct);
|
||||
|
||||
// ---- diesel card advances
|
||||
[HttpPost("{id:long}/first-advance")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsFirstAdvance)]
|
||||
public Task<TripsResult> FirstAdvance(long id, CancellationToken ct) => actions.FirstAdvanceAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/second-advance")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsSecondAdvance)]
|
||||
public Task<TripsResult> SecondAdvance(long id, CancellationToken ct) => actions.SecondAdvanceAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/first-advance-reverse")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsFirstAdvanceReverse)]
|
||||
public Task<TripsResult> FirstAdvanceReverse(long id, CancellationToken ct) => actions.FirstAdvanceReverseAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/second-advance-reverse")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsSecondAdvanceReverse)]
|
||||
public Task<TripsResult> SecondAdvanceReverse(long id, CancellationToken ct) => actions.SecondAdvanceReverseAsync(id, ct);
|
||||
|
||||
// ---- wage payment
|
||||
/// <summary>صرف: e-wallet payment through Dinarak.</summary>
|
||||
[HttpPost("{id:long}/exchange")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsExchange)]
|
||||
public Task<TripsResult> Exchange(long id, CancellationToken ct) => actions.ExchangeAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/exchange-audit")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsExchangeAudit)]
|
||||
public Task<TripsResult> ExchangeAudit(long id, CancellationToken ct) => actions.ExchangeAuditAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/receipt")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsReceipt)]
|
||||
public Task<TripsResult> Receipt(long id, CancellationToken ct) => actions.ReceiptAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/payment")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsPayment)]
|
||||
public Task<TripsResult> Payment(long id, CancellationToken ct) => actions.PaymentAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/activate-wallet-exchange")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsActivateWalletExchange)]
|
||||
public Task<TripsResult> ActivateWalletExchange(long id, CancellationToken ct) => actions.ActivateWalletExchangeAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/orange-payment")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsOrangePayment)]
|
||||
public Task<TripsResult> OrangePayment(long id, CancellationToken ct) => actions.OrangePaymentAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/cash-payment")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsCashPayment)]
|
||||
public Task<TripsResult> CashPayment(long id, CancellationToken ct) => actions.CashPaymentAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/confirm-exchange")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsConfirmExchange)]
|
||||
public Task<TripsResult> ConfirmExchange(long id, CancellationToken ct) => actions.ConfirmExchangeAsync(id, ct);
|
||||
|
||||
/// <summary>Cash voucher (سند صرف نقدي): stores the serial on the first call, logs PRINT; the page prints the returned data.</summary>
|
||||
[HttpPost("{id:long}/print")]
|
||||
[ProducesResponseType<TripVoucherDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsPrint)]
|
||||
public Task<TripVoucherDto> Print(long id, CancellationToken ct) => actions.PrintAsync(id, ct);
|
||||
|
||||
// ---- remaining balance of the trucks (used by the variables screen after a ton-price correction)
|
||||
[HttpPost("remaining-balance/recalculate")]
|
||||
[ProducesResponseType<TripsResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsRecalculateBalance)]
|
||||
public Task<TripsResult> RecalculateBalance(RecalculateBalanceRequest request, CancellationToken ct) =>
|
||||
balances.RecalculateForPeriodAsync(request.StartDate, request.EndDate, request.VariableGroupId, ct);
|
||||
|
||||
// ---- reports (xlsx)
|
||||
[HttpGet("reports/trips")]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsReport)]
|
||||
public async Task<IActionResult> TripsReport([FromQuery] TripQuery query, CancellationToken ct)
|
||||
{
|
||||
var f = await reports.TripsAsync(query, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
[HttpGet("reports/operator")]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsOperatorReport)]
|
||||
public async Task<IActionResult> OperatorReport([FromQuery] TripQuery query, CancellationToken ct)
|
||||
{
|
||||
var f = await reports.OperatorAsync(query, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
[HttpGet("reports/exchange")]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsExchangeReport)]
|
||||
public async Task<IActionResult> ExchangeReport([FromQuery] TripQuery query, CancellationToken ct)
|
||||
{
|
||||
var f = await reports.ExchangeAsync(query, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
[HttpGet("reports/diesel")]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsDieselReport)]
|
||||
public async Task<IActionResult> DieselReport([FromQuery] DieselReportQuery query, CancellationToken ct)
|
||||
{
|
||||
var f = await reports.DieselAsync(query, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
[HttpGet("reports/cards")]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsCardsReport)]
|
||||
public async Task<IActionResult> CardsReport([FromQuery] string? tn, CancellationToken ct)
|
||||
{
|
||||
var f = await reports.CardsAsync(tn, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
[HttpGet("reports/bank")]
|
||||
[RequirePermission(PermissionKeys.RefineryTripsBankReport)]
|
||||
public async Task<IActionResult> BankReport([FromQuery] BankReportQuery query, CancellationToken ct)
|
||||
{
|
||||
var f = await reports.BankAsync(query, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Api.Authorization;
|
||||
using NTP.Application.Access;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.Variables;
|
||||
|
||||
namespace NTP.Api.Controllers.V1.Refinery;
|
||||
|
||||
/// <summary>
|
||||
/// Refinery pricing periods (تسعير عطاء النفط الخام): port of refinery_variables*.cfc. Thin controller; access is by permission keys only
|
||||
/// (SU / REFINERY_MGR through GRAINS_SCREEN_PERMISSIONS), the legacy REFINERY_MGR / REFINERY_AC role branches are not ported.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/refinery/variables")]
|
||||
[Produces("application/json")]
|
||||
public sealed class VariablesController(IVariablesService variables) : ControllerBase
|
||||
{
|
||||
/// <summary>search: periods newest first. Filters: startDate (+ endDate = range of start dates) or endDate alone.</summary>
|
||||
[HttpGet]
|
||||
[RequirePermission(PermissionKeys.RefineryVariables)]
|
||||
public Task<PagedResult<VariablesSetRow>> Search([FromQuery] DateOnly? startDate, [FromQuery] DateOnly? endDate,
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 16, CancellationToken ct = default) =>
|
||||
variables.SearchAsync(new VariablesQuery(startDate, endDate), new PageRequest(page, pageSize), ct);
|
||||
|
||||
/// <summary>Excel of the periods grid (legacy REFINERY_VARIABLES_report).</summary>
|
||||
[HttpGet("export")]
|
||||
[RequirePermission(PermissionKeys.RefineryVariablesReport)]
|
||||
public async Task<IActionResult> Export([FromQuery] DateOnly? startDate, [FromQuery] DateOnly? endDate, CancellationToken ct)
|
||||
{
|
||||
var f = await variables.ExportAsync(new VariablesQuery(startDate, endDate), ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
/// <summary>refineryRemainingBalanceReport: previous balances per truck.</summary>
|
||||
[HttpGet("remaining-balance/export")]
|
||||
[RequirePermission(PermissionKeys.RefineryVariablesRemainingBalanceReport)]
|
||||
public async Task<IActionResult> ExportRemainingBalance(CancellationToken ct)
|
||||
{
|
||||
var f = await variables.ExportRemainingBalanceAsync(ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
/// <summary>getrefinery_variables: one period (by group id) and what may still be done with it.</summary>
|
||||
[HttpGet("{groupId:long}")]
|
||||
[RequirePermission(PermissionKeys.RefineryVariables)]
|
||||
public Task<VariablesSetDetail> Get(long groupId, CancellationToken ct) => variables.GetAsync(groupId, ct);
|
||||
|
||||
[HttpPost]
|
||||
[RequirePermission(PermissionKeys.RefineryVariablesCreate)]
|
||||
public Task<VariablesResult> Create([FromBody] SaveVariablesRequest request, CancellationToken ct) => variables.CreateAsync(request, ct);
|
||||
|
||||
[HttpPut("{groupId:long}")]
|
||||
[RequirePermission(PermissionKeys.RefineryVariablesUpdate)]
|
||||
public Task<VariablesResult> Update(long groupId, [FromBody] SaveVariablesRequest request, CancellationToken ct) =>
|
||||
variables.UpdateAsync(groupId, request, ct);
|
||||
|
||||
/// <summary>UPDATE_TON_PRICE_CORRECTION (once per period).</summary>
|
||||
[HttpPost("{groupId:long}/ton-price-correction")]
|
||||
[RequirePermission(PermissionKeys.RefineryVariablesTonPriceCorrection)]
|
||||
public Task<VariablesResult> TonPriceCorrection(long groupId, [FromBody] TonPriceCorrectionRequest request, CancellationToken ct) =>
|
||||
variables.SetTonPriceCorrectionAsync(groupId, request, ct);
|
||||
}
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Api.Authorization;
|
||||
using NTP.Application.Access;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.WageClaims;
|
||||
|
||||
namespace NTP.Api.Controllers.V1.Refinery;
|
||||
|
||||
/// <summary>
|
||||
/// Refinery wage claims (مطالبة الأجور): port of backend\entities\refinery_wage_claim (factory / factoryweb). Thin controller; the rules are in
|
||||
/// <see cref="IWageClaimService"/>. Search / view / log need the screen key, every action its own key (see PermissionKeys.Refinery.WageClaims.cs).
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/refinery/wage-claims")]
|
||||
[Produces("application/json")]
|
||||
public sealed class WageClaimsController(IWageClaimService claims) : ControllerBase
|
||||
{
|
||||
private string? Ip => HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
/// <summary>The grid: WAGE_CLAIM_NO, WAGE_CLAIM_DATE, STATUS_CODE (comma list), COMMISSION_CLAIM_NO, HAS_COMMISSION_CLAIM (0 / 1).</summary>
|
||||
[HttpGet]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaims)]
|
||||
public Task<PagedResult<WageClaimRowDto>> Search(
|
||||
[FromQuery] string? wageClaimNo, [FromQuery] DateOnly? wageClaimDate, [FromQuery] string? statusCode, [FromQuery] string? commissionClaimNo,
|
||||
[FromQuery] string? hasCommissionClaim, [FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) =>
|
||||
claims.SearchAsync(new WageClaimQuery(
|
||||
wageClaimNo, wageClaimDate, Split(statusCode), commissionClaimNo,
|
||||
string.IsNullOrWhiteSpace(hasCommissionClaim) ? null : hasCommissionClaim.Trim() is "1" or "true"),
|
||||
new PageRequest(page, pageSize), ct);
|
||||
|
||||
[HttpGet("{id:long}")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaims)]
|
||||
public Task<WageClaimRowDto> Get(long id, CancellationToken ct) => claims.GetAsync(id, ct);
|
||||
|
||||
/// <summary>The trips attached to the claim (legacy REFINERYTRIP.searchClaimTrips with WAGE_CLAIM_ID).</summary>
|
||||
[HttpGet("{id:long}/trips")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaims)]
|
||||
public Task<PagedResult<ClaimTripRowDto>> Trips(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) =>
|
||||
claims.TripsAsync(id, new PageRequest(page, pageSize), ct);
|
||||
|
||||
/// <summary>Preview of the create dialog: trips of the statuses (default: all three) without a wage claim, optionally in a loading date range.</summary>
|
||||
[HttpGet("candidate-trips")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaimsCreate)]
|
||||
public Task<PagedResult<ClaimTripRowDto>> CandidateTrips(
|
||||
[FromQuery] string? statusCode, [FromQuery] DateOnly? loadingDateFrom, [FromQuery] DateOnly? loadingDateTo,
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 10, CancellationToken ct = default) =>
|
||||
claims.CandidateTripsAsync(Split(statusCode), loadingDateFrom, loadingDateTo, new PageRequest(page, pageSize), ct);
|
||||
|
||||
[HttpGet("{id:long}/log")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaims)]
|
||||
public Task<PagedResult<ClaimLogRowDto>> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 5, CancellationToken ct = default) =>
|
||||
claims.LogAsync(id, new PageRequest(page, pageSize), ct);
|
||||
|
||||
/// <summary>create: attaches the trips of the statuses and loading dates that have no wage claim to a new claim.</summary>
|
||||
[HttpPost]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaimsCreate)]
|
||||
public Task<ClaimResult> Create(CreateWageClaimRequest request, CancellationToken ct) => claims.CreateAsync(request, Ip, ct);
|
||||
|
||||
/// <summary>CLAIM_CLOSE (تسديد).</summary>
|
||||
[HttpPost("{id:long}/close")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaimsClose)]
|
||||
public Task<ClaimResult> Close(long id, CancellationToken ct) => claims.CloseAsync(id, Ip, ct);
|
||||
|
||||
/// <summary>Grid status change NEW -> CLOSE: only the claim record, trips untouched. Same permission as the close.</summary>
|
||||
[HttpPost("{id:long}/status-close")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaimsClose)]
|
||||
public Task<ClaimResult> StatusClose(long id, CancellationToken ct) => claims.SetClosedAsync(id, Ip, ct);
|
||||
|
||||
/// <summary>Reopen (CLOSE -> NEW): new action of this system, same permission as the close.</summary>
|
||||
[HttpPost("{id:long}/reopen")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaimsClose)]
|
||||
public Task<ClaimResult> Reopen(long id, CancellationToken ct) => claims.ReopenAsync(id, Ip, ct);
|
||||
|
||||
/// <summary>TRANSFER (ترحيل): sends the claim to Jopetrol; refused with a message when the integration is disabled.</summary>
|
||||
[HttpPost("{id:long}/transfer")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaimsTransfer)]
|
||||
public Task<ClaimResult> Transfer(long id, CancellationToken ct) => claims.TransferAsync(id, Ip, ct);
|
||||
|
||||
/// <summary>REPORT: Excel of the trips of the claim.</summary>
|
||||
[HttpGet("{id:long}/export")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaimsReport)]
|
||||
public async Task<IActionResult> Export(long id, CancellationToken ct)
|
||||
{
|
||||
var f = await claims.ExportAsync(id, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
/// <summary>تقرير الملخص: one row of totals of the claim (legacy createCFRReport).</summary>
|
||||
[HttpGet("{id:long}/export-summary")]
|
||||
[RequirePermission(PermissionKeys.RefineryWageClaimsReport)]
|
||||
public async Task<IActionResult> ExportSummary(long id, CancellationToken ct)
|
||||
{
|
||||
var f = await claims.ExportSummaryAsync(id, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string> Split(string? s) =>
|
||||
(s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Api.Authorization;
|
||||
using NTP.Application.Access;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.Wallets;
|
||||
|
||||
namespace NTP.Api.Controllers.V1.Refinery;
|
||||
|
||||
/// <summary>Refinery payment methods (شاشة طرق الدفع): port of refinery_wallet*.cfc. Access by permission keys only (SU / REFINERY_MGR). The Dinarak API is not called.</summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/refinery/wallets")]
|
||||
[Produces("application/json")]
|
||||
public sealed class WalletsController(IWalletsService wallets) : ControllerBase
|
||||
{
|
||||
private string? Ip => HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
private static WalletsQuery Q(string? tn, string? walletNumber, string? ownerName, string? bankAccount, string? paymentMethod, string? statusCode, string? nnpn) =>
|
||||
new(tn, walletNumber, ownerName, bankAccount, paymentMethod, statusCode, nnpn);
|
||||
|
||||
/// <summary>search. paymentMethod: BANK, EWALLET or DRAIVER_WALLET; ownerName is a contains match.</summary>
|
||||
[HttpGet]
|
||||
[RequirePermission(PermissionKeys.RefineryWallets)]
|
||||
public Task<PagedResult<WalletRow>> Search([FromQuery] string? tn, [FromQuery] string? walletNumber, [FromQuery] string? ownerName,
|
||||
[FromQuery] string? bankAccount, [FromQuery] string? paymentMethod, [FromQuery] string? statusCode, [FromQuery] string? nnpn,
|
||||
[FromQuery] int page = 1, [FromQuery] int pageSize = 16, CancellationToken ct = default) =>
|
||||
wallets.SearchAsync(Q(tn, walletNumber, ownerName, bankAccount, paymentMethod, statusCode, nnpn), new PageRequest(page, pageSize), ct);
|
||||
|
||||
[HttpGet("export")]
|
||||
[RequirePermission(PermissionKeys.RefineryWalletsReport)]
|
||||
public async Task<IActionResult> Export([FromQuery] string? tn, [FromQuery] string? walletNumber, [FromQuery] string? ownerName,
|
||||
[FromQuery] string? bankAccount, [FromQuery] string? paymentMethod, [FromQuery] string? statusCode, [FromQuery] string? nnpn, CancellationToken ct)
|
||||
{
|
||||
var f = await wallets.ExportAsync(Q(tn, walletNumber, ownerName, bankAccount, paymentMethod, statusCode, nnpn), ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
[HttpGet("{id:long}")]
|
||||
[RequirePermission(PermissionKeys.RefineryWallets)]
|
||||
public Task<WalletDetail> Get(long id, CancellationToken ct) => wallets.GetAsync(id, ct);
|
||||
|
||||
[HttpGet("{id:long}/log")]
|
||||
[RequirePermission(PermissionKeys.RefineryWallets)]
|
||||
public Task<PagedResult<WalletLogRow>> Log(long id, [FromQuery] int page = 1, [FromQuery] int pageSize = 5, CancellationToken ct = default) =>
|
||||
wallets.GetLogAsync(id, new PageRequest(page, pageSize), ct);
|
||||
|
||||
[HttpPost]
|
||||
[RequirePermission(PermissionKeys.RefineryWalletsCreate)]
|
||||
public Task<WalletsResult> Create([FromBody] SaveWalletRequest request, CancellationToken ct) => wallets.CreateAsync(request, Ip, ct);
|
||||
|
||||
/// <summary>Deactivates the record and creates a new ACTIVE one with the new data; the answer carries the NEW id.</summary>
|
||||
[HttpPut("{id:long}")]
|
||||
[RequirePermission(PermissionKeys.RefineryWalletsUpdate)]
|
||||
public Task<WalletsResult> Update(long id, [FromBody] SaveWalletRequest request, CancellationToken ct) => wallets.UpdateAsync(id, request, Ip, ct);
|
||||
|
||||
[HttpPost("{id:long}/activate")]
|
||||
[RequirePermission(PermissionKeys.RefineryWalletsActivate)]
|
||||
public Task<WalletsResult> Activate(long id, CancellationToken ct) => wallets.ActivateAsync(id, Ip, ct);
|
||||
|
||||
[HttpPost("{id:long}/deactivate")]
|
||||
[RequirePermission(PermissionKeys.RefineryWalletsDeactivate)]
|
||||
public Task<WalletsResult> Deactivate(long id, CancellationToken ct) => wallets.DeactivateAsync(id, Ip, ct);
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -57,7 +57,7 @@ internal sealed class GlobalExceptionHandler(
|
|||
private static (int Status, string Title, string? Detail, IDictionary<string, string[]>? Errors) Map(Exception ex) =>
|
||||
ex switch
|
||||
{
|
||||
ValidationException v when v.Errors.Any() => (400, "Validation failed", null,
|
||||
ValidationException v when v.Errors.Any() => (400, "Validation failed", string.Join(" - ", v.Errors.Select(e => e.ErrorMessage).Distinct()),
|
||||
v.Errors.GroupBy(e => e.PropertyName)
|
||||
.ToDictionary(g => g.Key, g => g.Select(e => e.ErrorMessage).ToArray())),
|
||||
ValidationException v => (400, "Validation failed", v.Message, null),
|
||||
|
|
|
|||
|
|
@ -33,7 +33,8 @@
|
|||
"Permits": {
|
||||
"Notifications": {
|
||||
"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,
|
||||
"Sms": { "Enabled": false, "Provider": "JORMALL", "SenderId": "Nafith" }
|
||||
}
|
||||
|
|
@ -61,5 +62,39 @@
|
|||
"ConnectionTimeoutSeconds": 15,
|
||||
"StatementCacheSize": 50,
|
||||
"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).
|
||||
// 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
|
||||
// (Refinery__Dinarak__BaseUrl). MaxPaymentAmount is the largest net wage a payment action accepts (UNVERIFIED legacy value, caption says 500).
|
||||
"Refinery": {
|
||||
"Dinarak": { "Enabled": false, "BaseUrl": "", "TimeoutSeconds": 30 },
|
||||
// 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.
|
||||
"Jopetrol": { "Enabled": false, "Url": "http://fueltrans.jopetrol.com.jo:6060/TransportPmt/TransportPaymentWS.asmx", "TimeoutSeconds": 30 },
|
||||
"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": [] }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -4,7 +4,7 @@ namespace NTP.Application.Access;
|
|||
/// Stable resource keys the front end and the API agree on. A key is a menu entry (module/screen) or an action
|
||||
/// inside a screen. The front end uses the menu <c>key</c> of each entry (see web/src/features/*/routes.tsx).
|
||||
/// </summary>
|
||||
public static class PermissionKeys
|
||||
public static partial class PermissionKeys
|
||||
{
|
||||
// Screens (menu keys)
|
||||
public const string OrdersList = "grains.orders.list";
|
||||
|
|
@ -47,6 +47,11 @@ public static class PermissionKeys
|
|||
public const string RegistryTrucksEdit = "grains.registry.trucks.edit";
|
||||
public const string RegistryTrailersEdit = "grains.registry.trailers.edit";
|
||||
|
||||
// Actions: Excel export of the trucks / trailers / drivers lists. Granted ONLY by rows in GRAINS_SCREEN_PERMISSIONS (SU always).
|
||||
public const string RegistryTrucksExport = "grains.registry.trucks.export";
|
||||
public const string RegistryTrailersExport = "grains.registry.trailers.export";
|
||||
public const string RegistryDriversExport = "grains.registry.drivers.export";
|
||||
|
||||
// Actions / sub-screens of the permits module that have no menu entry of their own
|
||||
public const string PermitsClose = "grains.permits.close"; // legacy arrivalTruck.cfm
|
||||
public const string PermitsTruckOrder = "grains.permits.truckOrder"; // legacy processOpenPermit.cfm
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
}
|
||||
|
|
@ -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";
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
namespace NTP.Application.Access;
|
||||
|
||||
/// <summary>Refinery diesel cards (بطاقات الديزل) action keys. The screen itself (search / view / log) is <see cref="RefineryCards"/>.</summary>
|
||||
public static partial class PermissionKeys
|
||||
{
|
||||
/// <summary>Legacy CREATE (REFINERY_CARDS_CREATE): define a card.</summary>
|
||||
public const string RefineryCardsCreate = "refinery.cards.create";
|
||||
/// <summary>Legacy CHSTAT INACTIVE -> ACTIVE (REFINERY_CARDS_ACTIVE).</summary>
|
||||
public const string RefineryCardsActivate = "refinery.cards.activate";
|
||||
/// <summary>Legacy CHSTAT ACTIVE -> INACTIVE (REFINERY_CARDS_DEACTIVE).</summary>
|
||||
public const string RefineryCardsDeactivate = "refinery.cards.deactivate";
|
||||
/// <summary>Excel of the cards grid (legacy REFINERY_CARDS_report).</summary>
|
||||
public const string RefineryCardsReport = "refinery.cards.report";
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
namespace NTP.Application.Access;
|
||||
|
||||
/// <summary>
|
||||
/// Action keys of the refinery commission claims screen (مطالبة العمولة), object REFINERY_COMMISSION_CLAIM of STATUS_ACTION_MATRIX;
|
||||
/// search / view / log use the screen key <see cref="RefineryCommissionClaims"/>.
|
||||
/// </summary>
|
||||
public static partial class PermissionKeys
|
||||
{
|
||||
public const string RefineryCommissionClaimsCreate = "refinery.commissionClaims.create"; // CREATE
|
||||
public const string RefineryCommissionClaimsComplete = "refinery.commissionClaims.complete"; // CLAIM_CLOSE / CLAIM_COMPLETE
|
||||
public const string RefineryCommissionClaimsReport = "refinery.commissionClaims.report"; // REPORT (invoice)
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
namespace NTP.Application.Access;
|
||||
|
||||
/// <summary>
|
||||
/// Action keys of the refinery trips screen (legacy REFINERYTRIP actions). The screen key itself is
|
||||
/// <see cref="RefineryTrips"/> (list, view, log). Granted only by GRAINS_SCREEN_PERMISSIONS rows (SU always, REFINERY_MGR by script).
|
||||
/// </summary>
|
||||
public static partial class PermissionKeys
|
||||
{
|
||||
public const string RefineryTripsFirstAdvance = "refinery.trips.firstAdvance"; // FIRST_ADVANCED_PAYMENT
|
||||
public const string RefineryTripsSecondAdvance = "refinery.trips.secondAdvance"; // SECOND_ADVANCED_PAYMENT
|
||||
public const string RefineryTripsFirstAdvanceReverse = "refinery.trips.firstAdvanceReverse"; // FIRST_ADVANCED_PAYMENT_REVERSE
|
||||
public const string RefineryTripsSecondAdvanceReverse = "refinery.trips.secondAdvanceReverse"; // SECOND_ADVANCED_PAYMENT_REVERSE
|
||||
public const string RefineryTripsExchange = "refinery.trips.exchange"; // EXCHANGE (e-wallet through Dinarak)
|
||||
public const string RefineryTripsExchangeAudit = "refinery.trips.exchangeAudit"; // EXCHANGE_AUDIT
|
||||
public const string RefineryTripsReceipt = "refinery.trips.receipt"; // RECEIPT
|
||||
public const string RefineryTripsPayment = "refinery.trips.payment"; // PAYMENT (bank transfer)
|
||||
public const string RefineryTripsActivateWalletExchange = "refinery.trips.activateWalletExchange"; // ACTIVATE_WALLET_EXCHANGE
|
||||
public const string RefineryTripsOrangePayment = "refinery.trips.orangePayment"; // ORANGE_PAYMENT
|
||||
public const string RefineryTripsCashPayment = "refinery.trips.cashPayment"; // CACH_PAYMENT
|
||||
public const string RefineryTripsConfirmExchange = "refinery.trips.confirmExchange"; // CONFIRM_EXCHANGE
|
||||
public const string RefineryTripsPrint = "refinery.trips.print"; // print (cash voucher)
|
||||
public const string RefineryTripsReport = "refinery.trips.report"; // report (trips excel)
|
||||
public const string RefineryTripsOperatorReport = "refinery.trips.operatorReport"; // report(), REFINERY_OP column set
|
||||
public const string RefineryTripsExchangeReport = "refinery.trips.exchangeReport"; // report(), EXCHANGE_OP column set
|
||||
public const string RefineryTripsDieselReport = "refinery.trips.dieselReport"; // REFINERY_DIESEL_REPORT_VIEW report
|
||||
public const string RefineryTripsCardsReport = "refinery.trips.cardsReport"; // refineryCardsReport
|
||||
public const string RefineryTripsBankReport = "refinery.trips.bankReport"; // refineryBankReport
|
||||
public const string RefineryTripsRecalculateBalance = "refinery.trips.recalculateBalance"; // calculateRemainigBalance
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
namespace NTP.Application.Access;
|
||||
|
||||
/// <summary>Refinery variables (تسعير عطاء النفط الخام) action keys. The screen itself (search / view) is <see cref="RefineryVariables"/>.</summary>
|
||||
public static partial class PermissionKeys
|
||||
{
|
||||
/// <summary>Legacy STATUS_ACTION_MATRIX CREATE (REFINERY_VARIABLES_CREATE): new pricing period.</summary>
|
||||
public const string RefineryVariablesCreate = "refinery.variables.create";
|
||||
/// <summary>Legacy UPDATE: edit a pricing period (only while no trip was loaded inside it).</summary>
|
||||
public const string RefineryVariablesUpdate = "refinery.variables.update";
|
||||
/// <summary>Legacy UPDATE_TON_PRICE_CORRECTION: set the actual ton price once.</summary>
|
||||
public const string RefineryVariablesTonPriceCorrection = "refinery.variables.tonPriceCorrection";
|
||||
/// <summary>Excel of the pricing periods grid (legacy REFINERY_VARIABLES_report).</summary>
|
||||
public const string RefineryVariablesReport = "refinery.variables.report";
|
||||
/// <summary>Excel of the previous balances per truck (legacy refineryRemainingBalanceReport).</summary>
|
||||
public const string RefineryVariablesRemainingBalanceReport = "refinery.variables.remainingBalanceReport";
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
namespace NTP.Application.Access;
|
||||
|
||||
/// <summary>
|
||||
/// Action keys of the refinery wage claims screen (مطالبة الأجور). One key per legacy action of STATUS_ACTION_MATRIX
|
||||
/// (object REFINERY_WAGE_CLAIM); search / view / log use the screen key <see cref="RefineryWageClaims"/>.
|
||||
/// </summary>
|
||||
public static partial class PermissionKeys
|
||||
{
|
||||
public const string RefineryWageClaimsCreate = "refinery.wageClaims.create"; // CREATE
|
||||
public const string RefineryWageClaimsClose = "refinery.wageClaims.close"; // CLAIM_CLOSE (تسديد)
|
||||
public const string RefineryWageClaimsTransfer = "refinery.wageClaims.transfer"; // TRANSFER (ترحيل)
|
||||
public const string RefineryWageClaimsReport = "refinery.wageClaims.report"; // REPORT (excel of the trips of a claim)
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
namespace NTP.Application.Access;
|
||||
|
||||
/// <summary>Refinery payment methods (شاشة طرق الدفع: e-wallet, bank transfer, driver tip wallet) action keys. The screen itself is <see cref="RefineryWallets"/>.</summary>
|
||||
public static partial class PermissionKeys
|
||||
{
|
||||
/// <summary>Legacy CREATE (REFINERY_WALLET_CREATE).</summary>
|
||||
public const string RefineryWalletsCreate = "refinery.wallets.create";
|
||||
/// <summary>Legacy UPDATE (REFINERY_WALLET_update): ACTIVE records only; the old record is deactivated and a new one created.</summary>
|
||||
public const string RefineryWalletsUpdate = "refinery.wallets.update";
|
||||
/// <summary>Legacy CHSTAT INACTIVE -> ACTIVE (REFINERY_WALLET_ACTIVATE).</summary>
|
||||
public const string RefineryWalletsActivate = "refinery.wallets.activate";
|
||||
/// <summary>Legacy DEACTIVATE (REFINERY_WALLET_DEACTIVATE).</summary>
|
||||
public const string RefineryWalletsDeactivate = "refinery.wallets.deactivate";
|
||||
/// <summary>Legacy REPORT (REFINERY_WALLET_report): Excel of the filtered grid.</summary>
|
||||
public const string RefineryWalletsReport = "refinery.wallets.report";
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
namespace NTP.Application.Access;
|
||||
|
||||
/// <summary>
|
||||
/// Refinery (المصفاة) module keys, ported from the AqabaTCS app. Granted ONLY by rows in GRAINS_SCREEN_PERMISSIONS (see
|
||||
/// db/refinery-permissions.sql: SU is always allowed, REFINERY_MGR gets every key); none of them is in <see cref="PermissionDefaults"/>.
|
||||
/// Action keys of one module live in that module's own partial file (PermissionKeys.Refinery.<Module>.cs).
|
||||
/// </summary>
|
||||
public static partial class PermissionKeys
|
||||
{
|
||||
// Screens (menu keys), one per legacy menu entry (customtags/Menu.cfm)
|
||||
public const string RefineryTrips = "refinery.trips"; // REFINERYTRIPGRID
|
||||
public const string RefineryWageClaims = "refinery.wageClaims"; // REFINERY_WAGE_CLAIMGRID
|
||||
public const string RefineryCommissionClaims = "refinery.commissionClaims"; // REFINERY_COMMISSION_CLAIMGRID
|
||||
public const string RefineryWallets = "refinery.wallets"; // REFINERY_WALLETGRID
|
||||
public const string RefineryVariables = "refinery.variables"; // REFINERY_VARIABLESGRID
|
||||
public const string RefineryCards = "refinery.cards"; // REFINERY_CARDSGRID
|
||||
}
|
||||
|
|
@ -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";
|
||||
}
|
||||
|
|
@ -45,7 +45,8 @@ public sealed class AuthService(
|
|||
{
|
||||
await loginValidator.ValidateAndThrowAsync(request, ct);
|
||||
|
||||
var throttleKey = request.UserName.Trim().ToLowerInvariant();
|
||||
// one budget per account, however the name is typed (login alone, or with a legacy DOMAIN. prefix, spaces and dots included)
|
||||
var throttleKey = LoginName.Parse(request.UserName).Login;
|
||||
if (throttle.BlockedFor(throttleKey, client.IpAddress) is { } wait)
|
||||
throw new TooManyAttemptsException("TOO_MANY_ATTEMPTS", string.Format(TooManyAttemptsMessage, Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes))));
|
||||
|
||||
|
|
@ -64,16 +65,23 @@ public sealed class AuthService(
|
|||
|
||||
private async Task<LoginResponse> SignInAsync(LoginRequest request, ClientInfo client, CancellationToken ct)
|
||||
{
|
||||
var parts = request.UserName.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
if (parts.Length != 2)
|
||||
throw Invalid();
|
||||
// the user types just the login: its domain is the one of the active user (a typed "DOMAIN.login" is still honoured). The password
|
||||
// hash depends on the domain, so every active domain of the login is tried until the password matches.
|
||||
var (typedDomain, login) = LoginName.Parse(request.UserName);
|
||||
if (login.Length == 0) throw Invalid();
|
||||
IReadOnlyList<string> domains = typedDomain is not null ? [typedDomain] : await repository.GetActiveDomainsAsync(login, ct);
|
||||
|
||||
var domain = parts[0];
|
||||
var login = parts[1].ToLowerInvariant();
|
||||
|
||||
var candidates = PasswordHasher.Candidates(domain, login, request.Password);
|
||||
var found = await repository.FindActiveUserByPasswordAsync(login, domain, candidates,
|
||||
requireActiveCompany: PasswordHasher.IsAseza(domain), ct) ?? throw Invalid();
|
||||
UserLoginRow? found = null;
|
||||
var domain = string.Empty;
|
||||
foreach (var candidateDomain in domains)
|
||||
{
|
||||
found = await repository.FindActiveUserByPasswordAsync(login, candidateDomain, PasswordHasher.Candidates(candidateDomain, login, request.Password),
|
||||
requireActiveCompany: PasswordHasher.IsAseza(candidateDomain), ct);
|
||||
if (found is null) continue;
|
||||
domain = candidateDomain;
|
||||
break;
|
||||
}
|
||||
if (found is null) throw Invalid();
|
||||
|
||||
var roleCode = found.RoleCode ?? string.Empty;
|
||||
|
||||
|
|
|
|||
|
|
@ -15,9 +15,9 @@ public sealed class ChangePasswordRequestValidator : AbstractValidator<ChangePas
|
|||
{
|
||||
public ChangePasswordRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.OldPassword).NotEmpty().MaximumLength(200);
|
||||
RuleFor(x => x.OldPassword).NotEmpty().WithMessage("الرجاء إدخال كلمة السر الحالية").MaximumLength(200);
|
||||
// login keeps accepting every existing password; only a NEW password has to be reasonably strong
|
||||
RuleFor(x => x.NewPassword).NotEmpty().MaximumLength(200)
|
||||
RuleFor(x => x.NewPassword).NotEmpty().WithMessage("الرجاء إدخال كلمة السر الجديدة").MaximumLength(200)
|
||||
.MinimumLength(8).WithMessage("كلمة السر يجب ألا تقل عن 8 خانات")
|
||||
.Must(p => p is not null && p.Any(char.IsLetter) && p.Any(char.IsDigit)).WithMessage("كلمة السر يجب أن تحتوي على أحرف وأرقام")
|
||||
.Must((r, p) => p != r.OldPassword).WithMessage("كلمة السر الجديدة يجب أن تختلف عن القديمة");
|
||||
|
|
|
|||
|
|
@ -48,6 +48,9 @@ public interface IAuthRepository
|
|||
Task<UserLoginRow?> FindActiveUserByPasswordAsync(string login, string domain, IReadOnlyList<string> passwordCandidates,
|
||||
bool requireActiveCompany, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The domains (NTPUSERS.DOMAINNAME) of the ACTIVE users with this login: lets a user sign in with the login alone.</summary>
|
||||
Task<IReadOnlyList<string>> GetActiveDomainsAsync(string login, CancellationToken ct = default);
|
||||
|
||||
/// <summary>GateEventsFactory.CheckAuthorization: active UTT (booth) row for the login.</summary>
|
||||
Task<bool> HasActiveBoothAsync(string login, CancellationToken ct = default);
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,19 @@
|
|||
namespace NTP.Application.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// The user name typed on the sign-in page. Users type just their login; the legacy "DOMAIN.login" spelling (for example ASEZA.50034)
|
||||
/// is still accepted, in which case the domain is taken from it instead of being looked up.
|
||||
/// </summary>
|
||||
public static class LoginName
|
||||
{
|
||||
/// <summary>
|
||||
/// <c>Domain</c> is null when only a login was typed. <c>Login</c> is lower case and trimmed. A name with exactly two dot-separated
|
||||
/// parts is "DOMAIN.login"; anything else is one login (no login in NTPUSERS contains a dot).
|
||||
/// </summary>
|
||||
public static (string? Domain, string Login) Parse(string userName)
|
||||
{
|
||||
var text = (userName ?? string.Empty).Trim();
|
||||
var parts = text.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
return parts.Length == 2 ? (parts[0], parts[1].ToLowerInvariant()) : (null, text.ToLowerInvariant());
|
||||
}
|
||||
}
|
||||
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
|
@ -7,7 +7,8 @@ namespace NTP.Application.Grains.Orders;
|
|||
public interface IOrderReportService
|
||||
{
|
||||
Task<TenderOrderReportDto> GetTenderOrderReportAsync(DateTime orderDate, CancellationToken ct);
|
||||
Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct);
|
||||
/// <summary>The legacy tenderOrderReport_xls.cfm Excel (an HTML table opened by Excel).</summary>
|
||||
Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, CancellationToken ct);
|
||||
|
||||
Task<FinancialBillingPage> GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct);
|
||||
/// <summary>The legacy FinancialBilling.cfm Excel (an HTML table opened by Excel), byte for byte the same layout.</summary>
|
||||
|
|
@ -62,30 +63,40 @@ public sealed class OrderReportService(IOrderReportRepository repository, ICurre
|
|||
destRows.Sum(x => x.Individuals), destRows.Sum(x => x.Companies));
|
||||
}
|
||||
|
||||
public async Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct)
|
||||
/// <summary>Legacy tenderOrderReport_xls.cfm: an HTML table opened by Excel, same layout and texts.</summary>
|
||||
public async Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, CancellationToken ct)
|
||||
{
|
||||
var r = await GetTenderOrderReportAsync(orderDate, ct);
|
||||
string TypeLabel(string? t) => t switch
|
||||
{
|
||||
TenderOrderType.Individuals => L("افراد", "Individuals"),
|
||||
TenderOrderType.Company => L("شركات", "Companies"),
|
||||
_ => string.Empty
|
||||
};
|
||||
static string E(object? v) => System.Net.WebUtility.HtmlEncode(Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty);
|
||||
static string TypeLabel(string? t) => t switch { TenderOrderType.Individuals => "افراد", TenderOrderType.Company => "شركات", _ => string.Empty };
|
||||
|
||||
var title = new[] { L("شركة نافذ للخدمات اللوجستية", "Nafith Logistics Services"), L("نسب التوزيع في طلبيات السائب", "Distribution ratios of bulk orders"), $"{L("تاريخ الطلبية", "Order date")}: {r.OrderDate}" };
|
||||
var t1 = new ExportTable(title,
|
||||
[L("افراد \\ شركات", "Individuals / Companies"), L("العدد", "Count"), L("النسبة", "Ratio")],
|
||||
r.ByType.Select(x => (IReadOnlyList<object?>)new object?[] { TypeLabel(x.Type), x.Quantity, x.Percent }).ToList(),
|
||||
[L("المجموع", "Total"), r.TypeTotal, "100%"]);
|
||||
var h = new System.Text.StringBuilder();
|
||||
h.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
|
||||
h.Append("<style>.header{font-weight:bold;font-size:28px;}");
|
||||
h.Append(".sub_header{font-weight:bold;font-size:14px;text-align:right;width:80px;background-color:#034878;color:#FFFFFF;text-align:center;}");
|
||||
h.Append(".footer{background-color:#034878;color:#FFFFFF;font-weight:bold;}</style>");
|
||||
h.Append("<table border=\"2\" bordercolor=\"#034878\"><tr><td><table align=\"center\" dir=\"rtl\" border=\"1\">");
|
||||
h.Append("<tr align=\"center\" dir=\"rtl\"><td colspan=\"6\" align=\"center\" class=\"header\">شركة نافذ للخدمات اللوجستية</td></tr>");
|
||||
h.Append("<tr align=\"center\" dir=\"rtl\"><td colspan=\"6\" align=\"center\" class=\"header\"> نسب التوزيع في طلبيات السائب</td></tr>");
|
||||
h.Append("<tr align=\"center\" dir=\"rtl\"><td class=\"sub_header\">افراد \\ شركات</td><td class=\"sub_header\">العدد</td><td class=\"sub_header\">النسبة</td></tr>");
|
||||
foreach (var x in r.ByType)
|
||||
h.Append($"<tr align=\"center\" dir=\"rtl\"><td>{TypeLabel(x.Type)}</td><td>{E(x.Quantity)}</td><td>{E(x.Percent)}</td></tr>");
|
||||
h.Append($"<tr align=\"center\" dir=\"rtl\"><td>المجموع</td><td>{E(r.TypeTotal)}</td><td>100%</td></tr>");
|
||||
h.Append("<tr><td colspan=\"6\"></td></tr>");
|
||||
h.Append("<tr align=\"center\" dir=\"rtl\">");
|
||||
foreach (var c in new[] { "الوجهة", "عدد الافراد", "نسبة الافراد", "عدد الشركات", "نسبة الشركات", "المجموع" })
|
||||
h.Append($"<td class=\"sub_header\">{c}</td>");
|
||||
h.Append("</tr>");
|
||||
foreach (var x in r.ByDestination)
|
||||
h.Append($"<tr align=\"center\" dir=\"rtl\"><td>{E(x.Destination)}</td><td>{E(x.Individuals)}</td><td>{E(x.IndividualsPercent)}%</td><td>{E(x.Companies)}</td><td>{E(x.CompaniesPercent)}%</td><td>{E(x.Total)}</td></tr>");
|
||||
h.Append("<tr><td colspan=\"6\"></td></tr>");
|
||||
if (r.ByDestination.Count == 0) h.Append("<tr><td colspan=\"6\">لايوجد معلومات</td></tr>");
|
||||
h.Append($"<tr><td colspan=\"2\">بتاريخ : {DateTime.Now:dd/MM/yyyy HH:mm}</td><td colspan=\"2\">جميع الحقوق محفوظة لشركة نافذ للخدمات اللوجستية</td>");
|
||||
h.Append($"<td colspan=\"2\" align=\"left\">طبع التقرير بواسطة : {E(user.UserId)}</td></tr>");
|
||||
h.Append("</table></td></tr></table></body></html>");
|
||||
|
||||
var t2 = new ExportTable([],
|
||||
[L("الوجهة", "Destination"), L("عدد الافراد", "Individuals"), L("نسبة الافراد", "Individuals %"),
|
||||
L("عدد الشركات", "Companies"), L("نسبة الشركات", "Companies %"), L("المجموع", "Total")],
|
||||
r.ByDestination.Select(x => (IReadOnlyList<object?>)new object?[]
|
||||
{ x.Destination, x.Individuals, x.IndividualsPercent + "%", x.Companies, x.CompaniesPercent + "%", x.Total }).ToList(),
|
||||
[L("المجموع", "Total"), r.TotalIndividuals, null, r.TotalCompanies, null, r.TotalIndividuals + r.TotalCompanies]);
|
||||
|
||||
return Build([t1, t2], format, $"ordersReport_{r.OrderDate}");
|
||||
var bytes = new System.Text.UTF8Encoding(true).GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(h.ToString())).ToArray();
|
||||
return new ExportFile(bytes, "application/vnd.ms-excel", "ordersReport.xls");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ financial billing
|
||||
|
|
|
|||
|
|
@ -47,14 +47,14 @@ public sealed record TenderOrderDto(
|
|||
bool? MobileShow,
|
||||
bool CanDelete);
|
||||
|
||||
// Shift: Mobile shift: 1 morning, 2 evening, 3 night (legacy form field SHIFT).
|
||||
// Shift (optional): Mobile shift: 1 morning, 2 evening, 3 night (legacy form field SHIFT).
|
||||
// Type: AHALE or COMP (required unless cargo type is 41).
|
||||
public sealed record CreateTenderOrderRequest(
|
||||
long CargoType,
|
||||
long Location,
|
||||
long Destination,
|
||||
DateTime OrderDate,
|
||||
int Shift,
|
||||
int? Shift,
|
||||
int Quantity,
|
||||
bool IsTipper,
|
||||
string? Type);
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ public static class OrdersErrors
|
|||
new("BILLING_DNW_MISSING", "الوزن المستلم مطلوب");
|
||||
|
||||
public static BusinessException SentWeightRange() =>
|
||||
new("BILLING_LNW_RANGE", "يجب أن يكون الوزن بين 0 - 50000");
|
||||
new("BILLING_LNW_RANGE", "يجب أن يكون الوزن بين 0 - 60000");
|
||||
|
||||
public static BusinessException PriceNotDefined() =>
|
||||
new("BILLING_PRICE_NOT_DEFINED", "لا تسطيع الإضافة - السعر لهذه الوجهة غير معرف");
|
||||
|
|
@ -176,8 +176,8 @@ public static class BillingCalculator
|
|||
/// <summary>Page JS checkDate: discharge date must not be before load date.</summary>
|
||||
public static bool IsDischargeAfterLoad(DateTime load, DateTime discharge) => discharge.Date >= load.Date;
|
||||
|
||||
/// <summary>Page JS checkNumber: sent weight between 0 and 50000.</summary>
|
||||
public static bool IsSentWeightInRange(decimal lnw) => lnw >= 0 && lnw <= 50000;
|
||||
/// <summary>Page JS checkNumber: sent weight between 0 and 60000 (legacy limit was 50000).</summary>
|
||||
public static bool IsSentWeightInRange(decimal lnw) => lnw >= 0 && lnw <= 60000;
|
||||
}
|
||||
|
||||
public static class GrainsWeightRules
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ public sealed class CreateTenderOrderValidator : AbstractValidator<CreateTenderO
|
|||
RuleFor(x => x.Location).GreaterThan(0).WithMessage("موقع التحميل مطلوب");
|
||||
RuleFor(x => x.Destination).GreaterThan(0).WithMessage("الوجهه مطلوبة");
|
||||
RuleFor(x => x.OrderDate).NotEmpty().WithMessage("تاريخ الطلبية مطلوب");
|
||||
RuleFor(x => x.Shift).InclusiveBetween(1, 3).WithMessage("الفترة مطلوبة");
|
||||
RuleFor(x => x.Shift).InclusiveBetween(1, 3).When(x => x.Shift.HasValue).WithMessage("الفترة غير صحيحة");
|
||||
RuleFor(x => x.Quantity)
|
||||
.Must(TenderOrderRules.IsQuantityValid).WithMessage("عدد السيارات يجب ان يكون بين 1 - 200");
|
||||
RuleFor(x => x.Type)
|
||||
|
|
|
|||
|
|
@ -367,7 +367,8 @@ public sealed class DistributionService(
|
|||
? await destinations.GetTruckDestinationsAsync(tn, ct)
|
||||
: company is long c ? await destinations.GetCompanyLocationsAsync(c, ct) : [];
|
||||
var names = await repo.GetLocationNamesAsync(locations, ct);
|
||||
result.CompanyLocations = string.Concat(names.Select(n => " - " + n.Name));
|
||||
// legacy loops the allowed ids in list order and appends " - " + name (empty when the location is unknown)
|
||||
result.CompanyLocations = string.Concat(locations.Select(id => " - " + names.FirstOrDefault(n => n.Id == id).Name));
|
||||
|
||||
var orders = await repo.GetActiveOrdersInWindowAsync(new ShiftWindow
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>?wsdl address of the legacy push web service (backend/common/MobileNotification.cfc, operation SendFromCF9). It sends the push
|
||||
/// (OneSignal) and writes MOBILENOTIFICATIONSLOG itself, so V2 only has to call it with the same arguments as legacy.</summary>
|
||||
public string PushUrl { get; set; } = string.Empty;
|
||||
/// <summary>OneSignal account the push goes to (legacy MobileNotification.cfc SendNotificationToOneSignal). V2 calls the OneSignal REST API itself;
|
||||
/// the legacy web service is no longer used. AppId and ApiKey come from the environment (Grains__Permits__Notifications__OneSignal__AppId / __ApiKey).</summary>
|
||||
public OneSignalOptions OneSignal { get; set; } = new();
|
||||
|
||||
public int TimeoutSeconds { get; set; } = 15;
|
||||
|
||||
|
|
@ -107,6 +107,20 @@ public sealed class NotificationOptions
|
|||
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>
|
||||
public sealed class SmsOptions
|
||||
{
|
||||
|
|
|
|||
|
|
@ -30,8 +30,8 @@ public interface INotificationRepository
|
|||
{
|
||||
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>
|
||||
Task<IReadOnlyList<long>> FindUserIdsAsync(string roleCode, string? mobile, string? login, string? loginContains, CancellationToken ct = default);
|
||||
/// <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<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>
|
||||
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,
|
||||
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
|
||||
{
|
||||
Task<bool> SendAsync(PushMessage message, CancellationToken ct = default);
|
||||
|
|
|
|||
|
|
@ -14,6 +14,49 @@ public static class NotificationRules
|
|||
public const string PhoneReject = "PHONE_REJECT";
|
||||
public const string DelayPn = "DELAY_PN";
|
||||
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>
|
||||
public static readonly string[] PhoneRoles = ["DRVR", "TRKOWNER"];
|
||||
|
|
|
|||
|
|
@ -0,0 +1,92 @@
|
|||
using System.Net;
|
||||
using System.Text;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Grains.Registry;
|
||||
|
||||
public interface IRegistryExportService
|
||||
{
|
||||
Task<ExportFile> ExportTrucksAsync(TruckListQuery query, CancellationToken ct);
|
||||
Task<ExportFile> ExportTrailersAsync(TrailerListQuery query, CancellationToken ct);
|
||||
Task<ExportFile> ExportDriversAsync(DriverListQuery query, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Excel of the filtered registry grids (legacy truckGrid.cfm openTruckReportExcel / driverGrid.cfm openDriversReportExcel: the buttons
|
||||
/// were shown to GTO, GOO, GNAC / GTO, GOO). Who may export is decided only by the permission keys *.export (GRAINS_SCREEN_PERMISSIONS, see
|
||||
/// the controller); there is no role list in code.
|
||||
/// </summary>
|
||||
public sealed class RegistryExportService(
|
||||
ITruckRegistryService trucks, ITrailerRegistryService trailers, IDriverRegistryService drivers, ICurrentUser user) : IRegistryExportService
|
||||
{
|
||||
private const int MaxRows = 20000;
|
||||
private static async Task<List<T>> AllAsync<T>(Func<PageRequest, Task<PagedResult<T>>> fetch)
|
||||
{
|
||||
var all = new List<T>();
|
||||
for (var p = 1; all.Count < MaxRows; p++)
|
||||
{
|
||||
var r = await fetch(new PageRequest(p, PageRequest.MaxPageSize));
|
||||
all.AddRange(r.Items);
|
||||
if (r.Items.Count == 0 || all.Count >= r.TotalCount) break;
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
public async Task<ExportFile> ExportTrucksAsync(TruckListQuery query, CancellationToken ct)
|
||||
{
|
||||
var rows = await AllAsync(p => trucks.SearchAsync(query, p, ct));
|
||||
var label = query.SearchType == "TRN" ? "المقطورة" : "القاطرة";
|
||||
return Build("شاشة القاطرات/ المقطورات المسجلة", "TruckReport",
|
||||
[label, "رقم الشاصي", "الشركة", "انتهاء الترخيص", "تاريخ الإنشاء", "أنشئ بواسطة", "الحالة"],
|
||||
rows.Select(r => new object?[] { r.Tn, r.ChasesNumber, r.CompName, D(r.RegDate), D(r.CreateTimestamp, true), r.CreateUserId, r.StatusCaption }));
|
||||
}
|
||||
|
||||
public async Task<ExportFile> ExportTrailersAsync(TrailerListQuery query, CancellationToken ct)
|
||||
{
|
||||
var rows = await AllAsync(p => trailers.SearchAsync(query, p, ct));
|
||||
return Build("شاشة المقطورات المسجلة", "TrailerReport",
|
||||
["رقم المقطورة", "رقم الشاصي", "الشركة", "المالك", "انتهاء الترخيص", "تاريخ الإنشاء", "أنشئ بواسطة", "الحالة"],
|
||||
rows.Select(r => new object?[] { r.Tn, r.ChasesNumber, r.CompName, r.OwnerName, D(r.RegDate), D(r.CreateTimestamp, true), r.CreateUserId, r.StatusCaption }));
|
||||
}
|
||||
|
||||
public async Task<ExportFile> ExportDriversAsync(DriverListQuery query, CancellationToken ct)
|
||||
{
|
||||
var rows = await AllAsync(p => drivers.SearchAsync(query, p, ct));
|
||||
return Build("شاشة السائقين المسجلين", "DriversReport",
|
||||
["الرقم الوطني", "الاسم", "رقم الرخصة", "انتهاء الرخصة", "الشركة", "تاريخ الإنشاء", "أنشئ بواسطة", "الحالة"],
|
||||
rows.Select(r => new object?[] { r.Nnpn, r.Name, r.Dln, D(r.Dled), r.CompName, D(r.CreateTimestamp, true), r.CreateUserId, r.StatusCaption }));
|
||||
}
|
||||
|
||||
private static string D(DateTime? d, bool time = false) => d is null ? string.Empty : d.Value.ToString(time ? "dd/MM/yyyy HH:mm" : "dd/MM/yyyy");
|
||||
|
||||
private ExportFile Build(string title, string fileName, string[] headers, IEnumerable<object?[]> rows)
|
||||
{
|
||||
static string E(object? v) => WebUtility.HtmlEncode(Convert.ToString(v, System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty);
|
||||
var n = headers.Length;
|
||||
var h = new StringBuilder();
|
||||
h.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
|
||||
h.Append("<style>.header{font-weight:bold;font-size:28px;}");
|
||||
h.Append(".sub_header{font-weight:bold;font-size:14px;width:80px;background-color:#034878;color:#FFFFFF;text-align:center;}</style>");
|
||||
h.Append("<table border=\"2\" bordercolor=\"#034878\"><tr><td><table align=\"center\" dir=\"rtl\" border=\"1\">");
|
||||
h.Append($"<tr align=\"center\" dir=\"rtl\"><td colspan=\"{n}\" align=\"center\" class=\"header\">شركة نافذ للخدمات اللوجستية</td></tr>");
|
||||
h.Append($"<tr align=\"center\" dir=\"rtl\"><td colspan=\"{n}\" align=\"center\" class=\"header\">{E(title)}</td></tr>");
|
||||
h.Append("<tr align=\"center\" dir=\"rtl\">");
|
||||
foreach (var c in headers) h.Append($"<td class=\"sub_header\">{E(c)}</td>");
|
||||
h.Append("</tr>");
|
||||
var count = 0;
|
||||
foreach (var r in rows)
|
||||
{
|
||||
count++;
|
||||
h.Append("<tr align=\"center\" dir=\"rtl\">");
|
||||
foreach (var v in r) h.Append($"<td>{E(v)}</td>");
|
||||
h.Append("</tr>");
|
||||
}
|
||||
if (count == 0) h.Append($"<tr><td colspan=\"{n}\">لايوجد معلومات</td></tr>");
|
||||
h.Append($"<tr><td colspan=\"{n}\">بتاريخ : {DateTime.Now:dd/MM/yyyy HH:mm} - عدد النتائج : {count} - طبع التقرير بواسطة : {E(user.UserId)}</td></tr>");
|
||||
h.Append("</table></td></tr></table></body></html>");
|
||||
var bytes = new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(h.ToString())).ToArray();
|
||||
return new ExportFile(bytes, "application/vnd.ms-excel", fileName + ".xls");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,6 @@
|
|||
using NTP.Application.ExternalIntegration;
|
||||
using NTP.Application.Grains.Permits;
|
||||
using NTP.Application.Refinery.Sync;
|
||||
|
||||
namespace NTP.Application.Jobs;
|
||||
|
||||
|
|
@ -41,6 +43,41 @@ public static class JobCatalog
|
|||
var n = await Get<IQueueService>(sp).FillCompanySharesAsync(ct);
|
||||
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));
|
||||
|
|
|
|||
|
|
@ -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.<table> 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, string? ip = null);
|
||||
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);
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,182 @@
|
|||
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; }
|
||||
/// <summary>The grains (GN) permit number of the truck, "رقم الارسالية" (column GNPN, db/receipts-gn-permit.sql).</summary>
|
||||
public long? GnPn { 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? GnPn { 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";
|
||||
}
|
||||
|
|
@ -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: PAID (owner decision; the legacy made cash RECEIVED and claims UNPAID).</summary>
|
||||
public static string StatusForNew(int credit) => ReceiptStatus.Paid;
|
||||
|
||||
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);
|
||||
}
|
||||
|
|
@ -0,0 +1,338 @@
|
|||
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, string? ip = null)
|
||||
{
|
||||
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("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);
|
||||
|
||||
// a receipt is created already paid (owner decision); the creation is logged like the legacy CREATE log
|
||||
var status = ReceiptRules.StatusForNew(request.Credit);
|
||||
var id = await unitOfWork.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var newId = await repository.InsertAsync(request, type.Fees ?? 0, status, user.UserId, c);
|
||||
var (old, @new) = ReceiptRules.CreateLog(status);
|
||||
await repository.AddLogAsync(newId, "CREATE", old, @new, user.Id, ip, null, c);
|
||||
return newId;
|
||||
}, 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", "المبلغ", "Amount"), 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", "المبلغ", "Amount"),
|
||||
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);
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
namespace NTP.Application.Refinery.Cards;
|
||||
|
||||
/// <summary>Row of REFINERY_CARDS (a Jopetrol diesel card of a truck). Class with settable properties (Dapper + Oracle NUMBER).</summary>
|
||||
public class CardRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long Tn { get; set; }
|
||||
public string? CardNumber { get; set; }
|
||||
public long? BoxNo { get; set; }
|
||||
public decimal CurrentBalance { get; set; }
|
||||
public DateTime? CreationDate { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTime? UpdateDate { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
public string? StatusCode { get; set; }
|
||||
public long? LastTripId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Row of REFINERY_CARDS_LOG (legacy REFINERY_CARDS_LOG_VIEW). METHOD_NAME is the raw code, the screen translates it.</summary>
|
||||
public class CardLogRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long EntityId { get; set; }
|
||||
public string? MethodName { get; set; }
|
||||
public decimal BalanceBefore { get; set; }
|
||||
public decimal BalanceAfter { get; set; }
|
||||
public decimal Amount { get; set; }
|
||||
public string? Pn { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
public DateTime? LastUpdateDate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Grid filters (legacy TN, CARD_NUMBER exact match, STATUS_CODE multi select).</summary>
|
||||
public sealed record CardsQuery(string? Tn, string? CardNumber, IReadOnlyList<string> StatusCodes);
|
||||
|
||||
public sealed class CreateCardRequest
|
||||
{
|
||||
public long Tn { get; set; }
|
||||
public string? CardNumber { get; set; }
|
||||
public decimal CurrentBalance { get; set; }
|
||||
}
|
||||
|
||||
public sealed record CardsResult(string Message, long? Id = null);
|
||||
|
||||
public static class CardValues
|
||||
{
|
||||
public const string Active = "ACTIVE";
|
||||
public const string Inactive = "INACTIVE";
|
||||
public const string MethodCreate = "CREATE";
|
||||
public const string MethodActive = "ACTIVE";
|
||||
public const string MethodDeactive = "DEACTIVE";
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
namespace NTP.Application.Refinery.Cards;
|
||||
|
||||
/// <summary>User-facing texts (legacy captions verbatim; * = no row in LT_CAPTION, new wording).</summary>
|
||||
public static class CardsMessages
|
||||
{
|
||||
public const string CardExists = "هذه البطاقة معرفة سابقاً"; // ERROR.REINERY_CARDS_IS_EXIST
|
||||
public const string TruckHasActiveCard = "الشاحنة له بطاقة ديزل فعالة معرفة مسبقاً"; // ERROR.REINERY_CARDS_TN_HAS_ACTIVE_CARD
|
||||
public const string BalanceNotEqualPrevious = "رصيد البطاقة الجديدة غير مطابق للبطاقة السابقة"; // ERROR.CURRENT_BALANCE_IS_NOT_EQ_PERVIOS_CARD
|
||||
public const string CardNotFound = "بطاقة تعبئة الديزل غير معرفة"; // ERROR.THE_REFINERY_CARD_IS_NOT_EXIST
|
||||
public const string StatusNotAllowed = "لا يمكن تنفيذ هذا الإجراء على البطاقة في حالتها الحالية"; // * (legacy: STATUS_ACTION_MATRIX refusal)
|
||||
public const string Required = "الرجاء ادخال جميع الحقول"; // REPORT.VALIDATION
|
||||
public const string Done = "";
|
||||
}
|
||||
|
||||
public static class CardsErrors
|
||||
{
|
||||
public const string CardExists = "REINERY_CARDS_IS_EXIST";
|
||||
public const string TruckHasActiveCard = "REINERY_CARDS_TN_HAS_ACTIVE_CARD";
|
||||
public const string BalanceNotEqualPrevious = "CURRENT_BALANCE_IS_NOT_EQ_PERVIOS_CARD";
|
||||
public const string CardNotFound = "THE_REFINERY_CARD_IS_NOT_EXIST";
|
||||
public const string StatusNotAllowed = "REFINERY_CARD_STATUS_NOT_ALLOWED";
|
||||
}
|
||||
|
||||
/// <summary>Pure rules of refinery_cardsfactory.cfc.</summary>
|
||||
public static class CardsRules
|
||||
{
|
||||
/// <summary>REFINERY_CARDS.CARD_NUMBER is VARCHAR2(10).</summary>
|
||||
public const int CardNumberMaxLength = 10;
|
||||
/// <summary>The balance is also copied into REFINERY_CARDS_LOG (NUMBER(10,3)).</summary>
|
||||
public const decimal BalanceLimit = 10_000_000m;
|
||||
|
||||
/// <summary>Legacy matrix: only INACTIVE -> ACTIVE (CHSTAT, REFINERY_CARDS_ACTIVE) ...</summary>
|
||||
public static bool CanActivate(string? status) => string.Equals(status, CardValues.Inactive, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>... and ACTIVE -> INACTIVE (REFINERY_CARDS_DEACTIVE). There is no other transition and no card update.</summary>
|
||||
public static bool CanDeactivate(string? status) => string.Equals(status, CardValues.Active, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// refinery_cardsfactory.cfc:154-165: a truck that already had (inactive) cards may only get a new card with the balance of the
|
||||
/// previous one (the balance travels with the truck). <paramref name="previousInactiveBalance"/> = balance of its latest inactive card.
|
||||
/// </summary>
|
||||
public static bool BalanceMatchesPrevious(decimal? previousInactiveBalance, decimal newBalance) =>
|
||||
previousInactiveBalance is null || previousInactiveBalance.Value == newBalance;
|
||||
}
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
using FluentValidation;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
using NTP.Application.Grains.Reports;
|
||||
|
||||
namespace NTP.Application.Refinery.Cards;
|
||||
|
||||
/// <summary>
|
||||
/// Port of refinery_cardsfactory.cfc / refinery_cardsfactoryweb.cfc (screen REFINERY_CARDS, بطاقات الديزل). Access is by permission keys only
|
||||
/// (legacy REFINERY_MGR / REFINERY_AC branches not ported). There is no card update: the legacy update is broken (it reads a variable that does
|
||||
/// not exist and updates variable columns) and STATUS_ACTION_MATRIX has no usable UPDATE row for cards.
|
||||
/// </summary>
|
||||
public sealed class CardsService(
|
||||
ICardsRepository repository,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user,
|
||||
IReportExcelService excel,
|
||||
IValidator<CreateCardRequest> createValidator) : ICardsService
|
||||
{
|
||||
public Task<PagedResult<CardRow>> SearchAsync(CardsQuery query, PageRequest page, CancellationToken ct) =>
|
||||
repository.SearchAsync(query, page, ct);
|
||||
|
||||
public async Task<CardRow> GetAsync(long id, CancellationToken ct) =>
|
||||
await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery card", id);
|
||||
|
||||
public async Task<PagedResult<CardLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
_ = await GetAsync(id, ct);
|
||||
return await repository.GetLogAsync(id, page, ct);
|
||||
}
|
||||
|
||||
public async Task<CardsResult> CreateAsync(CreateCardRequest request, CancellationToken ct)
|
||||
{
|
||||
await createValidator.ValidateAndThrowAsync(request, ct);
|
||||
var number = request.CardNumber!.Trim();
|
||||
|
||||
if (await repository.CardNumberExistsAsync(number, ct))
|
||||
throw new BusinessException(CardsErrors.CardExists, CardsMessages.CardExists);
|
||||
|
||||
var cards = await repository.GetByTruckAsync(request.Tn, ct);
|
||||
if (cards.Any(c => string.Equals(c.StatusCode, CardValues.Active, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new BusinessException(CardsErrors.TruckHasActiveCard, CardsMessages.TruckHasActiveCard);
|
||||
var previous = cards.Where(c => string.Equals(c.StatusCode, CardValues.Inactive, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderByDescending(c => c.Id).FirstOrDefault();
|
||||
if (!CardsRules.BalanceMatchesPrevious(previous?.CurrentBalance, request.CurrentBalance))
|
||||
throw new BusinessException(CardsErrors.BalanceNotEqualPrevious, CardsMessages.BalanceNotEqualPrevious);
|
||||
|
||||
var id = await unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
var newId = await repository.InsertAsync(request.Tn, number, request.CurrentBalance, user.UserId, token);
|
||||
// refinery_cardsfactory.cfc:176: CREATE log row, balance 0 -> opening balance
|
||||
await repository.InsertLogAsync(newId, CardValues.MethodCreate, 0, request.CurrentBalance, request.CurrentBalance, user.UserId, token);
|
||||
return newId;
|
||||
}, ct);
|
||||
return new CardsResult(CardsMessages.Done, id);
|
||||
}
|
||||
|
||||
public async Task<CardsResult> ActivateAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var card = await repository.GetAsync(id, ct) ?? throw new BusinessException(CardsErrors.CardNotFound, CardsMessages.CardNotFound);
|
||||
if (!CardsRules.CanActivate(card.StatusCode))
|
||||
throw new BusinessException(CardsErrors.StatusNotAllowed, CardsMessages.StatusNotAllowed);
|
||||
// a truck keeps one active card (refinery_cardsfactory.cfc:250)
|
||||
var cards = await repository.GetByTruckAsync(card.Tn, ct);
|
||||
if (cards.Any(c => string.Equals(c.StatusCode, CardValues.Active, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new BusinessException(CardsErrors.TruckHasActiveCard, CardsMessages.TruckHasActiveCard);
|
||||
|
||||
await ChangeStatusAsync(card, CardValues.Active, CardValues.MethodActive, ct);
|
||||
return new CardsResult(CardsMessages.Done, id);
|
||||
}
|
||||
|
||||
public async Task<CardsResult> DeactivateAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var card = await repository.GetAsync(id, ct) ?? throw new BusinessException(CardsErrors.CardNotFound, CardsMessages.CardNotFound);
|
||||
if (!CardsRules.CanDeactivate(card.StatusCode))
|
||||
throw new BusinessException(CardsErrors.StatusNotAllowed, CardsMessages.StatusNotAllowed);
|
||||
|
||||
await ChangeStatusAsync(card, CardValues.Inactive, CardValues.MethodDeactive, ct);
|
||||
return new CardsResult(CardsMessages.Done, id);
|
||||
}
|
||||
|
||||
/// <summary>Status change + log row (balance before = after = the card balance, amount 0, PN '0'), like the legacy ACTIVE / DEACTIVE.</summary>
|
||||
private Task ChangeStatusAsync(CardRow card, string status, string method, CancellationToken ct) =>
|
||||
unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await repository.ChangeStatusAsync(card.Id, status, user.UserId, token);
|
||||
await repository.InsertLogAsync(card.Id, method, card.CurrentBalance, card.CurrentBalance, 0, user.UserId, token);
|
||||
return true;
|
||||
}, ct);
|
||||
|
||||
public async Task<ExportFile> ExportAsync(CardsQuery query, CancellationToken ct)
|
||||
{
|
||||
var rows = new List<CardRow>();
|
||||
for (var p = 1; rows.Count < 20000; p++)
|
||||
{
|
||||
var r = await repository.SearchAsync(query, new PageRequest(p, PageRequest.MaxPageSize), ct);
|
||||
rows.AddRange(r.Items);
|
||||
if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break;
|
||||
}
|
||||
var cols = new List<ReportColumn>
|
||||
{
|
||||
new("tn", "رقم الشاحنة", "Truck"), new("cardNumber", "رقم بطاقة جوبترول", "Card number"),
|
||||
new("currentBalance", "الرصيد الحالي", "Current balance"), new("status", "الحالة", "Status"),
|
||||
};
|
||||
var data = rows.Select(r => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
|
||||
{
|
||||
["tn"] = r.Tn, ["cardNumber"] = r.CardNumber, ["currentBalance"] = r.CurrentBalance,
|
||||
["status"] = string.Equals(r.StatusCode, CardValues.Active, StringComparison.OrdinalIgnoreCase) ? "فعال" : "غير فعال",
|
||||
}).ToList();
|
||||
var table = new ReportTable { Key = "REFINERY_CARDS", TitleAr = "بطاقات الديزل", TitleEn = "Diesel cards", Columns = cols, Rows = data };
|
||||
return new ExportFile(excel.Build(table, user.UserId, DateTime.Now, true),
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "REFINERY_CARDS.xlsx");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
using FluentValidation;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Refinery.Cards;
|
||||
|
||||
public interface ICardsRepository
|
||||
{
|
||||
/// <summary>Newest first (legacy sort ID DESC).</summary>
|
||||
Task<PagedResult<CardRow>> SearchAsync(CardsQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<CardRow?> GetAsync(long id, CancellationToken ct = default);
|
||||
Task<bool> CardNumberExistsAsync(string cardNumber, CancellationToken ct = default);
|
||||
/// <summary>All cards of a truck (newest first).</summary>
|
||||
Task<IReadOnlyList<CardRow>> GetByTruckAsync(long tn, CancellationToken ct = default);
|
||||
Task<long> InsertAsync(long tn, string cardNumber, decimal balance, string createdBy, CancellationToken ct = default);
|
||||
Task ChangeStatusAsync(long id, string status, string userId, CancellationToken ct = default);
|
||||
Task InsertLogAsync(long cardId, string method, decimal balanceBefore, decimal balanceAfter, decimal amount, string userId, CancellationToken ct = default);
|
||||
Task<PagedResult<CardLogRow>> GetLogAsync(long cardId, PageRequest page, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface ICardsService
|
||||
{
|
||||
Task<PagedResult<CardRow>> SearchAsync(CardsQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<CardRow> GetAsync(long id, CancellationToken ct);
|
||||
Task<PagedResult<CardLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct);
|
||||
Task<CardsResult> CreateAsync(CreateCardRequest request, CancellationToken ct);
|
||||
Task<CardsResult> ActivateAsync(long id, CancellationToken ct);
|
||||
Task<CardsResult> DeactivateAsync(long id, CancellationToken ct);
|
||||
Task<ExportFile> ExportAsync(CardsQuery query, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>The create form: truck, card number and opening balance are required (legacy HTML required + bean length check).</summary>
|
||||
public sealed class CreateCardValidator : AbstractValidator<CreateCardRequest>
|
||||
{
|
||||
public CreateCardValidator()
|
||||
{
|
||||
RuleFor(x => x.Tn).GreaterThan(0).LessThan(1_000_000_000_000L).WithMessage(CardsMessages.Required);
|
||||
RuleFor(x => x.CardNumber).NotEmpty().MaximumLength(CardsRules.CardNumberMaxLength).WithMessage(CardsMessages.Required);
|
||||
RuleFor(x => x.CurrentBalance).GreaterThanOrEqualTo(0).LessThan(CardsRules.BalanceLimit).WithMessage(CardsMessages.Required);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
using NTP.Application.Refinery.WageClaims;
|
||||
|
||||
namespace NTP.Application.Refinery.CommissionClaims;
|
||||
|
||||
/// <summary>REFINERY_COMMISSION_CLAIM_VIEW row. <see cref="TripCnt"/> is the number of wage claims (the legacy column name and grid caption "عدد مطالبات الاجور").</summary>
|
||||
public sealed class CommissionClaimRowDto
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long? CommissionClaimNo { get; set; }
|
||||
public DateTime? CommissionClaimDate { get; set; }
|
||||
public long TripCnt { get; set; }
|
||||
/// <summary>NEW / COMPLETE (old rows may hold CLOSE).</summary>
|
||||
public string StatusCode { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>Filters of the legacy grid (COMMISSION_CLAIM_NO, COMMISSION_CLAIM_DATE, STATUS_CODE).</summary>
|
||||
public sealed record CommissionClaimQuery(string? CommissionClaimNo, DateOnly? CommissionClaimDate, IReadOnlyList<string> StatusCodes);
|
||||
|
||||
/// <summary>Body of POST commission-claims: the wage claims to group (legacy IDS_ARR).</summary>
|
||||
public sealed record CreateCommissionClaimRequest(IReadOnlyList<long>? WageClaimIds);
|
||||
|
||||
/// <summary>Data the invoice report needs (legacy factory.report).</summary>
|
||||
public sealed class CommissionInvoiceSource
|
||||
{
|
||||
public long CommissionClaimNo { get; set; }
|
||||
/// <summary>WAGE_CLAIM_DATE of the newest wage claim (ORDER BY ID DESC) of the commission claim; null when it has no wage claim.</summary>
|
||||
public DateTime? NewestWageClaimDate { get; set; }
|
||||
public long TripsCount { get; set; }
|
||||
}
|
||||
|
||||
public sealed record InvoiceLine(string Label, long Quantity, decimal PriceWithTax, decimal TotalBeforeTax, decimal TotalWithTax);
|
||||
|
||||
public sealed record CommissionInvoice(
|
||||
string InvoiceNumber, DateOnly InvoiceDate, DateOnly PeriodStart, DateOnly PeriodEnd, IReadOnlyList<InvoiceLine> Lines,
|
||||
decimal TotalBeforeTax, decimal Tax, decimal GrandTotal);
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.WageClaims;
|
||||
|
||||
namespace NTP.Application.Refinery.CommissionClaims;
|
||||
|
||||
/// <summary>Pure rules of the commission claim screen (refinery_commission_claimfactory.cfc).</summary>
|
||||
public static class CommissionClaimRules
|
||||
{
|
||||
/// <summary>"العمولة الثابتة": fixed commission per trip, price including tax (factory.report, fixeComission).</summary>
|
||||
public const decimal FixedCommission = 2.00m;
|
||||
/// <summary>The prices include the 16% sales tax (invoice formula =ROUND(total/1.16,3)).</summary>
|
||||
public const decimal TaxDivisor = 1.16m;
|
||||
|
||||
public const string FixedLabel = "العمولة الثابتة";
|
||||
public const string CompetitiveLabel = "العمولة التنافسية";
|
||||
|
||||
/// <summary>factory.create: at least one wage claim chosen.</summary>
|
||||
public static IReadOnlyList<long> NormalizeIds(IEnumerable<long>? ids)
|
||||
{
|
||||
var list = (ids ?? []).Where(i => i > 0).Distinct().ToList();
|
||||
if (list.Count == 0) throw new BusinessException("PLEASE_SELECT_CLAIM", ClaimMessages.PleaseSelectClaim);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>factory.CLAIM_COMPLETE: every wage claim of the commission claim must be CLOSE (paid).</summary>
|
||||
public static bool AllWageClaimsPaid(IEnumerable<string> wageClaimStatuses) => wageClaimStatuses.All(s => s == WageClaimRules.Close);
|
||||
|
||||
/// <summary>
|
||||
/// Billing period of the invoice: the month BEFORE the date of the newest wage claim (legacy: monthValue = month(date) - 1, January gives
|
||||
/// December of the previous year); the invoice is dated the last day of that month.
|
||||
/// </summary>
|
||||
public static (DateOnly Start, DateOnly End) BillingPeriod(DateTime newestWageClaimDate)
|
||||
{
|
||||
var first = new DateOnly(newestWageClaimDate.Year, newestWageClaimDate.Month, 1).AddMonths(-1);
|
||||
return (first, first.AddMonths(1).AddDays(-1));
|
||||
}
|
||||
|
||||
/// <summary>Invoice line: total = quantity x price (with tax); before tax = ROUND(total / 1.16, 3) (Excel rounds halves away from zero).</summary>
|
||||
public static InvoiceLine Line(string label, long quantity, decimal priceWithTax)
|
||||
{
|
||||
var total = quantity * priceWithTax;
|
||||
return new InvoiceLine(label, quantity, priceWithTax, Math.Round(total / TaxDivisor, 3, MidpointRounding.AwayFromZero), total);
|
||||
}
|
||||
|
||||
/// <summary>Totals row of the invoice: sum before tax, tax = grand total - sum before tax, grand total = sum of the line totals.</summary>
|
||||
public static CommissionInvoice BuildInvoice(long commissionClaimNo, DateTime newestWageClaimDate, long tripsCount, decimal competitiveCommission)
|
||||
{
|
||||
var (start, end) = BillingPeriod(newestWageClaimDate);
|
||||
var lines = new[] { Line(FixedLabel, tripsCount, FixedCommission), Line(CompetitiveLabel, tripsCount, competitiveCommission) };
|
||||
var before = lines.Sum(l => l.TotalBeforeTax);
|
||||
var grand = lines.Sum(l => l.TotalWithTax);
|
||||
return new CommissionInvoice($"INV {commissionClaimNo}", end, start, end, lines, before, grand - before, grand);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
using System.Globalization;
|
||||
using System.Text;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
using NTP.Application.Refinery.WageClaims;
|
||||
using static NTP.Application.Refinery.WageClaims.ClaimExcel;
|
||||
|
||||
namespace NTP.Application.Refinery.CommissionClaims;
|
||||
|
||||
public interface ICommissionClaimService
|
||||
{
|
||||
Task<PagedResult<CommissionClaimRowDto>> SearchAsync(CommissionClaimQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<CommissionClaimRowDto> GetAsync(long id, CancellationToken ct);
|
||||
Task<IReadOnlyList<WageClaimRowDto>> WageClaimsAsync(long id, CancellationToken ct);
|
||||
Task<IReadOnlyList<WageClaimRowDto>> CandidateWageClaimsAsync(IReadOnlyList<string>? statusCodes, CancellationToken ct);
|
||||
Task<PagedResult<ClaimLogRowDto>> LogAsync(long id, PageRequest page, CancellationToken ct);
|
||||
Task<ClaimResult> CreateAsync(CreateCommissionClaimRequest request, string? ip, CancellationToken ct);
|
||||
Task<ClaimResult> CompleteAsync(long id, string? ip, CancellationToken ct);
|
||||
Task<ExportFile> ReportAsync(long id, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Port of refinery_commission_claimfactory.cfc. Not ported: the no-op "UPDATE REFINERY_WAGE_CLAIM ... status_Code in ('NEW,CLOSE')" after the create
|
||||
/// (a single quoted string never matches) and the TRIP_COMPLETE call of CLAIM_COMPLETE that passed the COMMISSION claim id as a trip id.
|
||||
/// </summary>
|
||||
public sealed class CommissionClaimService(ICommissionClaimRepository repo, IUnitOfWork unit, ICurrentUser user) : ICommissionClaimService
|
||||
{
|
||||
/// <summary>Statuses of the wage claims the create dialog offers by default (REFINERY_COMMISSION_CLAIMMain.html: NEW and CLOSE selected).</summary>
|
||||
private static readonly string[] CandidateStatuses = [WageClaimRules.New, WageClaimRules.Close];
|
||||
|
||||
public Task<PagedResult<CommissionClaimRowDto>> SearchAsync(CommissionClaimQuery query, PageRequest page, CancellationToken ct) => repo.SearchAsync(query, page, ct);
|
||||
|
||||
public async Task<CommissionClaimRowDto> GetAsync(long id, CancellationToken ct) =>
|
||||
await repo.GetAsync(id, ct) ?? throw new NotFoundException("REFINERY_COMMISSION_CLAIM", id);
|
||||
|
||||
public async Task<IReadOnlyList<WageClaimRowDto>> WageClaimsAsync(long id, CancellationToken ct)
|
||||
{
|
||||
await GetAsync(id, ct);
|
||||
return await repo.WageClaimsOfAsync(id, ct);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<WageClaimRowDto>> CandidateWageClaimsAsync(IReadOnlyList<string>? statusCodes, CancellationToken ct)
|
||||
{
|
||||
var wanted = (statusCodes ?? [])
|
||||
.SelectMany(s => (s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
.Select(s => s.ToUpperInvariant()).Where(s => s is WageClaimRules.New or WageClaimRules.Close).Distinct().ToList();
|
||||
return repo.CandidateWageClaimsAsync(wanted.Count == 0 ? CandidateStatuses : wanted, ct);
|
||||
}
|
||||
|
||||
public async Task<PagedResult<ClaimLogRowDto>> LogAsync(long id, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
await GetAsync(id, ct);
|
||||
return await repo.LogAsync(id, page, ct);
|
||||
}
|
||||
|
||||
/// <summary>factory.create: groups the chosen wage claims that have no commission claim yet under a new NEW commission claim.</summary>
|
||||
public async Task<ClaimResult> CreateAsync(CreateCommissionClaimRequest request, string? ip, CancellationToken ct)
|
||||
{
|
||||
var ids = CommissionClaimRules.NormalizeIds(request.WageClaimIds);
|
||||
var id = await unit.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
if (await repo.CountAttachableAsync(ids, c) == 0) throw new BusinessException("NO_WAGES", ClaimMessages.NoWages);
|
||||
var claimId = await repo.InsertAsync(user.UserId, c);
|
||||
await repo.AttachWageClaimsAsync(claimId, ids, c);
|
||||
await repo.AddLogAsync(claimId, "CREATE", "{}", ClaimLogJson.Status(WageClaimRules.New), user.Id, ip, c);
|
||||
return claimId;
|
||||
}, ct);
|
||||
return new ClaimResult(ClaimMessages.Success, id);
|
||||
}
|
||||
|
||||
/// <summary>factory.CLAIM_COMPLETE: NEW claim, every wage claim CLOSE -> wage claims COMPLETE (+ their log), commission claim COMPLETE (+ log CLAIM_CLOSE).</summary>
|
||||
public async Task<ClaimResult> CompleteAsync(long id, string? ip, CancellationToken ct)
|
||||
{
|
||||
var claim = await GetAsync(id, ct);
|
||||
if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority);
|
||||
// legacy returned the error in the middle of the loop; nothing is changed here unless all wage claims are paid
|
||||
if (!CommissionClaimRules.AllWageClaimsPaid(await repo.WageClaimStatusesAsync(id, ct)))
|
||||
throw new BusinessException("WAGE_CLAIM_NOT_CLOSE", ClaimMessages.WageClaimNotClose);
|
||||
|
||||
await unit.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
await repo.CompleteWageClaimsAsync(id, user.UserId, user.Id, ip, c);
|
||||
await repo.SetStatusAsync(id, WageClaimRules.Complete, user.UserId, c);
|
||||
await repo.AddLogAsync(id, "CLAIM_CLOSE", ClaimLogJson.Status(ClaimMessages.StatusNew), ClaimLogJson.Status(ClaimMessages.StatusComplete), user.Id, ip, c);
|
||||
return 0;
|
||||
}, ct);
|
||||
return new ClaimResult(ClaimMessages.Success, id);
|
||||
}
|
||||
|
||||
/// <summary>factory.report: the monthly invoice of the commissions (fixed commission and competitive commission per trip, 16% tax included).</summary>
|
||||
public async Task<ExportFile> ReportAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var src = await repo.InvoiceSourceAsync(id, ct) ?? throw new NotFoundException("REFINERY_COMMISSION_CLAIM", id);
|
||||
if (src.NewestWageClaimDate is null) throw new BusinessException("NO_TRIPS", ClaimMessages.NoTripsIssue);
|
||||
var (start, _) = CommissionClaimRules.BillingPeriod(src.NewestWageClaimDate.Value);
|
||||
var competitive = await repo.CommissionVariableAsync(start.Month, start.Year, ct)
|
||||
?? throw new BusinessException("COMMISSION_VARIABLE", ClaimMessages.CommissionVariableIssue);
|
||||
var inv = CommissionClaimRules.BuildInvoice(src.CommissionClaimNo, src.NewestWageClaimDate.Value, src.TripsCount, competitive);
|
||||
return RenderInvoice(inv, src.CommissionClaimNo);
|
||||
}
|
||||
|
||||
private static string Money(decimal v) => v.ToString("#,##0.000", CultureInfo.InvariantCulture);
|
||||
private static string Day(DateOnly d) => d.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Texts of the legacy invoice template (company, customer, columns, totals). Opened by Excel as an HTML table.</summary>
|
||||
internal static ExportFile RenderInvoice(CommissionInvoice inv, long commissionClaimNo)
|
||||
{
|
||||
var h = new StringBuilder();
|
||||
h.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
|
||||
h.Append("<table dir=\"rtl\" border=\"1\" align=\"center\" cellpadding=\"4\">");
|
||||
h.Append("<tr><td colspan=\"4\" align=\"center\"><b>شركة نافذ للخدمات اللوجستية</b></td><td colspan=\"3\" align=\"center\"><b>الفاتورة الشهرية -عمولات صرف اجور النقل</b></td></tr>");
|
||||
h.Append($"<tr><td>التاريخ :</td><td>{Day(inv.InvoiceDate)}</td><td colspan=\"3\"></td><td>رقم الضريبي :</td><td>16669690</td></tr>");
|
||||
h.Append($"<tr><td>رقم الفاتورة :</td><td>{E(inv.InvoiceNumber)}</td><td colspan=\"5\"></td></tr>");
|
||||
h.Append($"<tr><td>من / إلى</td><td>{Day(inv.PeriodStart)}</td><td>/</td><td>{Day(inv.PeriodEnd)}</td><td colspan=\"3\"></td></tr>");
|
||||
h.Append("<tr><td>رقم الشركة :</td><td>03-100002</td><td colspan=\"5\"></td></tr>");
|
||||
h.Append("<tr><td>اسم الشركة :</td><td colspan=\"6\">السادة شركة مصفاة البترول الأردنية المساهمة المحدودة</td></tr>");
|
||||
h.Append("<tr><td>العنوان :</td><td colspan=\"6\">الادارة العامة - عمان , الدوار الاول ,شارع الرينبو</td></tr>");
|
||||
h.Append("<tr><td colspan=\"2\">رقم الهاتف : 4630151-06</td><td colspan=\"2\">الفاكس : 4657939-06</td><td colspan=\"3\">البريد الالكتروني:Addewan@Jopetrol.com.jo</td></tr>");
|
||||
h.Append("<tr align=\"center\" bgcolor=\"#034878\"><td><font color=\"#FFFFFF\">البيان</font></td><td colspan=\"4\"></td>");
|
||||
h.Append("<td><font color=\"#FFFFFF\">عدد الارساليات</font></td><td><font color=\"#FFFFFF\">السعر شامل الضريبة</font></td>");
|
||||
h.Append("<td><font color=\"#FFFFFF\">المجموع قبل الضريبة</font></td><td><font color=\"#FFFFFF\">المجموع شامل الضريبة</font></td></tr>");
|
||||
foreach (var l in inv.Lines)
|
||||
h.Append($"<tr align=\"center\"><td>{E(l.Label)}</td><td colspan=\"4\"></td><td>{l.Quantity}</td><td>{Money(l.PriceWithTax)}</td><td>{Money(l.TotalBeforeTax)}</td><td>{Money(l.TotalWithTax)}</td></tr>");
|
||||
h.Append($"<tr><td colspan=\"5\"></td><td colspan=\"3\">المجموع قبل الضريبة</td><td>{Money(inv.TotalBeforeTax)}</td></tr>");
|
||||
h.Append($"<tr><td colspan=\"5\"></td><td colspan=\"2\">ضريبة المبيعات</td><td>0.16</td><td>{Money(inv.Tax)}</td></tr>");
|
||||
h.Append($"<tr><td colspan=\"5\"></td><td colspan=\"3\"><b>المجموع الأجمالي بالدينار الاردني</b></td><td><b>{Money(inv.GrandTotal)}</b></td></tr>");
|
||||
h.Append("<tr><td>اسم المستلم:</td><td colspan=\"3\"></td><td colspan=\"2\">شركة نافذ للخدمات اللوجستية</td><td colspan=\"2\"></td></tr>");
|
||||
h.Append("<tr><td>تاريخ الاستلام:</td><td colspan=\"3\"></td><td colspan=\"4\"></td></tr>");
|
||||
h.Append("<tr><td>الختم والتوقيع:</td><td colspan=\"3\"></td><td colspan=\"2\">الختم والتوقيع:</td><td colspan=\"2\"></td></tr>");
|
||||
h.Append("<tr align=\"center\"><td colspan=\"8\">مكتب الادارة - أبراج الحجاز، شارع مكة 158، مكتب 401 - ص.ب 995، عمان 11821، الأردن - هـ 6553629 962 - موقع www.nafith.com</td></tr>");
|
||||
h.Append("</table></body></html>");
|
||||
var bytes = new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(h.ToString())).ToArray();
|
||||
return new ExportFile(bytes, "application/vnd.ms-excel", $"refinery_commission_claim_{commissionClaimNo}.xls");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.WageClaims;
|
||||
|
||||
namespace NTP.Application.Refinery.CommissionClaims;
|
||||
|
||||
/// <summary>
|
||||
/// SQL of refinery_commission_claimdao.cfc and the writes of refinery_commission_claimfactory.cfc. Besides its own tables it writes
|
||||
/// REFINERY_WAGE_CLAIM (COMMISSION_CLAIM_ID when grouping; STATUS_CODE COMPLETE + REFINERY_WAGE_CLAIM_LOG when completing).
|
||||
/// </summary>
|
||||
public interface ICommissionClaimRepository
|
||||
{
|
||||
Task<PagedResult<CommissionClaimRowDto>> SearchAsync(CommissionClaimQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<CommissionClaimRowDto?> GetAsync(long id, CancellationToken ct = default);
|
||||
/// <summary>Wage claims grouped by the commission claim (legacy searchWageClaim with COMMISSION_CLAIM_ID).</summary>
|
||||
Task<IReadOnlyList<WageClaimRowDto>> WageClaimsOfAsync(long commissionClaimId, CancellationToken ct = default);
|
||||
/// <summary>Wage claims without a commission claim in the given statuses (legacy searchWageClaim, create dialog).</summary>
|
||||
Task<IReadOnlyList<WageClaimRowDto>> CandidateWageClaimsAsync(IReadOnlyList<string> statuses, CancellationToken ct = default);
|
||||
|
||||
Task<int> CountAttachableAsync(IReadOnlyList<long> wageClaimIds, CancellationToken ct = default);
|
||||
/// <summary>Takes the next claim number (legacy GenerateSerialNumber) and inserts the claim as NEW; returns its id. Run inside a transaction.</summary>
|
||||
Task<long> InsertAsync(string createdBy, CancellationToken ct = default);
|
||||
Task<int> AttachWageClaimsAsync(long commissionClaimId, IReadOnlyList<long> wageClaimIds, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<string>> WageClaimStatusesAsync(long commissionClaimId, CancellationToken ct = default);
|
||||
/// <summary>Every wage claim of the commission claim -> COMPLETE with a REFINERY_WAGE_CLAIM_LOG row (method COMPLETE, CLOSE -> COMPLETE).</summary>
|
||||
Task<int> CompleteWageClaimsAsync(long commissionClaimId, string userLogin, long userId, string? ip, CancellationToken ct = default);
|
||||
Task SetStatusAsync(long id, string status, string userLogin, CancellationToken ct = default);
|
||||
|
||||
Task AddLogAsync(long id, string method, string? oldData, string? newData, long userId, string? ip, CancellationToken ct = default);
|
||||
Task<PagedResult<ClaimLogRowDto>> LogAsync(long id, PageRequest page, CancellationToken ct = default);
|
||||
|
||||
Task<CommissionInvoiceSource?> InvoiceSourceAsync(long id, CancellationToken ct = default);
|
||||
/// <summary>REFINERY_VARIABLES COMMISSION valid for the month / year (legacy month and year range test); null when not defined.</summary>
|
||||
Task<decimal?> CommissionVariableAsync(int month, int year, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
namespace NTP.Application.Refinery.Integrations;
|
||||
|
||||
/// <summary>
|
||||
/// Companion of <see cref="IDinarakGateway"/> (whose signatures are fixed): REFINERY_TRIPS.DINARAK_REFERENCE_ID is a decimal (352.1, 352.11 ...)
|
||||
/// because ACTIVATE_WALLET_EXCHANGE adds 0.01 to it, so the status lookup by message id needs a decimal parameter.
|
||||
/// The same class implements both interfaces.
|
||||
/// </summary>
|
||||
public interface IDinarakReferenceGateway
|
||||
{
|
||||
/// <summary>
|
||||
/// Legacy getTransferByMessageID. <c>StatusName</c> is the Dinarak status ("Success", "Processing", "New", ...), "DISABLED" when the
|
||||
/// integration is switched off (nothing is called) and "ERROR" when the answer could not be obtained or read.
|
||||
/// </summary>
|
||||
Task<DinarakTransferStatus> GetTransferByReferenceAsync(decimal reference, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
namespace NTP.Application.Refinery.Integrations;
|
||||
|
||||
/// <summary>Result of a Dinarak e-wallet transfer. Codes as legacy RefinaryDinarakApi.ProcessTransfer: 000 ok, 101 amount mismatch,
|
||||
/// 102 refused by Dinarak, 103 HTTP error, 104 invalid wallet / system error, 105 already paid, 106 integration disabled by configuration.</summary>
|
||||
public sealed record DinarakTransferResult(string Code, string Message)
|
||||
{
|
||||
public bool Success => Code == "000";
|
||||
}
|
||||
|
||||
/// <summary>State of a transfer looked up by message id (legacy getTransferByMessageID): Success / Processing / New count as accepted.</summary>
|
||||
public sealed record DinarakTransferStatus(bool Accepted, string? StatusName, string? RawResponse);
|
||||
|
||||
/// <summary>
|
||||
/// Dinarak payment API (legacy backend/common/RefinaryDinarakApi.cfc). The implementation lives in NTP.Infrastructure, is OFF unless
|
||||
/// configuration enables it (Refinery:Dinarak:Enabled) and takes URL / user / password only from configuration (server .env).
|
||||
/// Every call writes REFINERY_DINARAK_API_LOG like the legacy code. When disabled it returns code 106 and calls nothing.
|
||||
/// </summary>
|
||||
public interface IDinarakGateway
|
||||
{
|
||||
Task<DinarakTransferResult> TransferAsync(long tripId, string walletNumber, string nnpn, decimal amount, string receiverName, CancellationToken ct = default);
|
||||
Task<DinarakTransferStatus> GetTransferByMessageIdAsync(long messageId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Jopetrol claim web service (legacy refinery_wage_claimfactory.callRefinaryUpdateStatusTo7, SOAP sendClaimandUpdateStatusTo7).
|
||||
/// OFF unless configuration enables it (Refinery:Jopetrol:Enabled); URL / user / password only from configuration. Returns the text of
|
||||
/// the service answer, or null when the integration is disabled.
|
||||
/// </summary>
|
||||
public interface IJopetrolGateway
|
||||
{
|
||||
Task<string?> SendClaimAndUpdateStatusTo7Async(string pn, string claimNo, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.Trips;
|
||||
|
||||
namespace NTP.Application.Refinery.RemainingBalance;
|
||||
|
||||
/// <summary>One truck's carried-over balance (REFINERY_REMAINING_BALANCE).</summary>
|
||||
public sealed class RemainingBalanceRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long Tn { get; set; }
|
||||
public decimal RemainingBalance { get; set; }
|
||||
public decimal? BeforeRemainingBalance { get; set; }
|
||||
}
|
||||
|
||||
public interface IRemainingBalanceRepository
|
||||
{
|
||||
Task<RemainingBalanceRow?> GetByTruckAsync(string tn, CancellationToken ct = default);
|
||||
/// <summary>Sets REMAINING_BALANCE to 0 and keeps the old value in BEFORE_REMAINING_BALANCE (legacy Zeroing).</summary>
|
||||
Task ZeroAsync(string tn, string userId, CancellationToken ct = default);
|
||||
/// <summary>Adds <paramref name="delta"/> to the balance (BEFORE_REMAINING_BALANCE = old value); false when the truck has no row.</summary>
|
||||
Task<bool> AddAsync(string tn, decimal delta, string userId, CancellationToken ct = default);
|
||||
Task CreateAsync(string tn, decimal balance, string userId, CancellationToken ct = default);
|
||||
/// <summary>REFINERY_REMAINING_BALANCE_LOG row (variableGroupId only when the change comes from a re-pricing).</summary>
|
||||
Task InsertLogAsync(long balanceId, decimal amount, decimal balanceBefore, long tripId, long? variableGroupId, string loginId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IRemainingBalanceService
|
||||
{
|
||||
/// <summary>Balance carried by the truck, or null when it has no row (legacy getByTN).</summary>
|
||||
Task<decimal?> GetAsync(string tn, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Legacy refinerytripfactory.setRemainigBalance: after a trip is paid, the balance it consumed is set back to 0 and logged
|
||||
/// (nothing when the truck has no balance row). Runs in the caller's transaction.
|
||||
/// </summary>
|
||||
Task ResetAfterPaymentAsync(string tn, long tripId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Legacy refinery_remaining_balanceDAO.setRemainingBalance: adds <paramref name="delta"/> to the truck's balance (creates the row
|
||||
/// when missing) and writes the log row. Runs in the caller's transaction.
|
||||
/// </summary>
|
||||
Task AddAsync(string tn, decimal delta, long tripId, long variableGroupId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Legacy refinerytripfactory.calculateRemainigBalance: after the ton price (penalty price) of a period was corrected, the
|
||||
/// difference of every penalised trip of the period is added to its truck's balance. The variables screen calls it after
|
||||
/// saving a corrected price; also available as POST refinery/trips/remaining-balance/recalculate.
|
||||
/// </summary>
|
||||
Task<TripsResult> RecalculateForPeriodAsync(DateTime startDate, DateTime endDate, long variableGroupId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Port of refinery_remaining_balanceDAO.cfc plus setRemainigBalance / calculateRemainigBalance of refinerytripfactory.cfc.</summary>
|
||||
public sealed class RemainingBalanceService(
|
||||
IRemainingBalanceRepository balances,
|
||||
ITripRepository trips,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user) : IRemainingBalanceService
|
||||
{
|
||||
public async Task<decimal?> GetAsync(string tn, CancellationToken ct = default) =>
|
||||
(await balances.GetByTruckAsync(tn, ct))?.RemainingBalance;
|
||||
|
||||
// refinerytripfactory.cfc:1246-1267. The legacy call sites guard it with len(x gt 0), which is always true: the balance is
|
||||
// reset after every payment whenever the truck has a balance row.
|
||||
public async Task ResetAfterPaymentAsync(string tn, long tripId, CancellationToken ct = default)
|
||||
{
|
||||
var row = await balances.GetByTruckAsync(tn, ct);
|
||||
if (row is null) return;
|
||||
await balances.ZeroAsync(tn, user.Id.ToString(), ct);
|
||||
// log: AMOUNT 0, balance before = what it was; CREATED_BY = login (legacy sessionstruct.userid)
|
||||
await balances.InsertLogAsync(row.Id, 0, row.RemainingBalance, tripId, null, user.UserId, ct);
|
||||
}
|
||||
|
||||
// refinery_remaining_balanceDAO.cfc:67-98 (the legacy create() was broken for a missing row; here the row is created and logged)
|
||||
public async Task AddAsync(string tn, decimal delta, long tripId, long variableGroupId, CancellationToken ct = default)
|
||||
{
|
||||
var userId = user.Id.ToString();
|
||||
var updated = await balances.AddAsync(tn, delta, userId, ct);
|
||||
if (!updated) await balances.CreateAsync(tn, delta, userId, ct);
|
||||
var row = await balances.GetByTruckAsync(tn, ct)
|
||||
?? throw new InvalidOperationException($"Remaining balance row of truck {tn} was not found after update.");
|
||||
await balances.InsertLogAsync(row.Id, row.RemainingBalance, row.BeforeRemainingBalance ?? 0, tripId, variableGroupId, user.UserId, ct);
|
||||
}
|
||||
|
||||
// refinerytripfactory.cfc:1269-1315
|
||||
public async Task<TripsResult> RecalculateForPeriodAsync(DateTime startDate, DateTime endDate, long variableGroupId, CancellationToken ct = default)
|
||||
{
|
||||
var list = await trips.GetTripsOfPeriodAsync(startDate.Date, endDate.Date, ct);
|
||||
if (list.Count == 0) throw TripErrors.NoTripsInPeriod();
|
||||
if (list.Any(t => t.StatusCode is not null && TripStatus.BlockRepricing.Contains(t.StatusCode)))
|
||||
throw TripErrors.NotAllExchanged();
|
||||
|
||||
return await unitOfWork.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
foreach (var t in list.Where(t => t.PenaltyAmount > 0))
|
||||
{
|
||||
if (t.LoadingDate is null || t.Tn is null) continue;
|
||||
var vars = TripVariables.FromPairs(await trips.GetVariablesAsync(t.LoadingDate.Value.Date, c));
|
||||
var weights = new TripWeights(t.NetLoadingWeight ?? 0, t.NetDischargeWeight ?? 0, t.WaterAmount ?? 0, await trips.GetWaterFlagAsync(t.Id, c));
|
||||
var corrected = TripCalculator.Calculate(weights, vars, null, useTonPriceCorrection: true);
|
||||
// legacy: calculatedAmounts.NET_WAGE neq trip.NET_WAGE, then delta = corrected NET_WAGE - TRIP_NET_WAGE
|
||||
if (corrected.NetWage != (t.NetWage ?? 0))
|
||||
await AddAsync(t.Tn, corrected.NetWage - (t.TripNetWage ?? 0), t.Id, variableGroupId, c);
|
||||
}
|
||||
return new TripsResult(TripErrors.Ok);
|
||||
}, ct);
|
||||
}
|
||||
}
|
||||
|
|
@ -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",
|
||||
};
|
||||
}
|
||||
|
|
@ -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;">® Nafith {year}</h3></td>
|
||||
<td width="75%" style="text-align:right;padding-top:10px;font-family:Arial,sans-serif;"><h3 style="color:white;">{year} نافذ ®</h3></td>
|
||||
</tr></table></td></tr>
|
||||
</table></body>
|
||||
""";
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -0,0 +1,343 @@
|
|||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Security;
|
||||
using System.Text;
|
||||
using NTP.Application.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Refinery.Trips;
|
||||
|
||||
/// <summary>
|
||||
/// One report in the layout of the legacy AqabaTCS reports (backend/common/report.cfc): company name and title on the first row,
|
||||
/// the applied filters as label / value pairs, a spacer row, the column captions, then the rows. The first column is the counter
|
||||
/// (متسلسل). <see cref="WidthsPt"/> are the legacy column widths in points.
|
||||
/// </summary>
|
||||
public sealed record LegacyReport(
|
||||
string CompanyName,
|
||||
string Title,
|
||||
IReadOnlyList<(string Label, string Value)> Filters,
|
||||
IReadOnlyList<string> Headers,
|
||||
IReadOnlyList<int> WidthsPt,
|
||||
IReadOnlyList<IReadOnlyList<object?>> Rows);
|
||||
|
||||
/// <summary>
|
||||
/// The legacy الحوالات list (refineryBankReport, companyreport.cfr): a banner with the company and the list title, a block with the
|
||||
/// account details and the total, then the trips table. <see cref="Info"/> are the label / value rows of the block; <see cref="WidthsChars"/>
|
||||
/// are the column widths in characters.
|
||||
/// </summary>
|
||||
public sealed record TransfersReport(
|
||||
string CompanyName,
|
||||
string Title,
|
||||
IReadOnlyList<(string Label, object? Value)> Info,
|
||||
IReadOnlyList<string> Headers,
|
||||
IReadOnlyList<double> WidthsChars,
|
||||
IReadOnlyList<IReadOnlyList<object?>> Rows);
|
||||
|
||||
/// <summary>
|
||||
/// The legacy one-row summary of a wage claim (refinerytripsxls.cfr): company and title banner, a navy row with three facts (claim number,
|
||||
/// tender, month) merged over A:E, F:L and M:O, the column captions and one row of totals. <see cref="WidthsChars"/> are in characters.
|
||||
/// </summary>
|
||||
public sealed record SummaryReport(
|
||||
string CompanyName,
|
||||
string Title,
|
||||
string Left,
|
||||
string Middle,
|
||||
string Right,
|
||||
IReadOnlyList<string> Headers,
|
||||
IReadOnlyList<double> WidthsChars,
|
||||
IReadOnlyList<object?> Values);
|
||||
|
||||
/// <summary>
|
||||
/// Writes legacy-style reports as .xlsx workbooks (right-to-left sheet, Arial Unicode MS 11, centred and wrapped cells, navy #003366 header
|
||||
/// cells with white text, thin borders). Strings are written as inline strings, so cell text can never be evaluated as a formula.
|
||||
/// </summary>
|
||||
public static class LegacyReportWorkbook
|
||||
{
|
||||
private const string Font = "Arial Unicode MS";
|
||||
|
||||
// cellXfs indexes of the report.cfc style sheet below
|
||||
private const int Company = 1, Title = 2, Header = 3, FilterValue = 4, Data = 5;
|
||||
// cellXfs indexes of the transfers style sheet
|
||||
private const int TBanner = 1, TLabel = 2, TValue = 3, THeader = 4, TData = 5;
|
||||
|
||||
/// <summary>Legacy widths are points (ss:Width); the sheet needs characters: ((pt * 4/3) - 5) / 7.</summary>
|
||||
public static double Chars(int points) => Math.Round((points * 4.0 / 3.0 - 5) / 7, 2);
|
||||
|
||||
public static byte[] ToXlsx(LegacyReport r) => Package(r.Title, Styles(), Sheet(r));
|
||||
|
||||
public static byte[] ToTransfersXlsx(TransfersReport r) => Package(r.Title, TransfersStyles(), TransfersSheet(r));
|
||||
|
||||
/// <summary>Same style sheet as the الحوالات list; layout read from a legacy output file (rows 1-2 banner height 30, rows 3-5 height 20).</summary>
|
||||
public static byte[] ToSummaryXlsx(SummaryReport r) => Package(r.Title, TransfersStyles(), SummarySheet(r));
|
||||
|
||||
private static string SummarySheet(SummaryReport r)
|
||||
{
|
||||
var cols = r.Headers.Count;
|
||||
var last = TabularExport.ColumnName(cols - 1);
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
|
||||
sb.Append("<sheetViews><sheetView rightToLeft=\"1\" workbookViewId=\"0\"/></sheetViews><sheetFormatPr defaultRowHeight=\"12.75\"/><cols>");
|
||||
for (var c = 0; c < cols; c++) Col(sb, c, c < r.WidthsChars.Count ? r.WidthsChars[c] : 20);
|
||||
sb.Append("</cols><sheetData>");
|
||||
void Banner(int row, string text)
|
||||
{
|
||||
sb.Append("<row r=\"").Append(row).Append("\" ht=\"30\" customHeight=\"1\">");
|
||||
Text(sb, 0, row, text, TBanner);
|
||||
for (var c = 1; c < cols; c++) Blank(sb, c, row, TBanner);
|
||||
sb.Append("</row>");
|
||||
}
|
||||
Banner(1, r.CompanyName);
|
||||
Banner(2, r.Title);
|
||||
sb.Append("<row r=\"3\" ht=\"20\" customHeight=\"1\">");
|
||||
for (var c = 0; c < cols; c++)
|
||||
{
|
||||
if (c == 0) Text(sb, c, 3, r.Left, TLabel);
|
||||
else if (c == 5) Text(sb, c, 3, r.Middle, TLabel);
|
||||
else if (c == 12) Text(sb, c, 3, r.Right, TLabel);
|
||||
else Blank(sb, c, 3, TLabel);
|
||||
}
|
||||
sb.Append("</row><row r=\"4\" ht=\"20\" customHeight=\"1\">");
|
||||
for (var c = 0; c < cols; c++) Text(sb, c, 4, r.Headers[c], THeader);
|
||||
sb.Append("</row><row r=\"5\" ht=\"20\" customHeight=\"1\">");
|
||||
for (var c = 0; c < cols && c < r.Values.Count; c++) Value(sb, c, 5, r.Values[c], TData);
|
||||
sb.Append("</row></sheetData><mergeCells count=\"5\"><mergeCell ref=\"A1:").Append(last).Append("1\"/><mergeCell ref=\"A2:").Append(last)
|
||||
.Append("2\"/><mergeCell ref=\"A3:E3\"/><mergeCell ref=\"F3:L3\"/><mergeCell ref=\"M3:").Append(last).Append("3\"/></mergeCells></worksheet>");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static byte[] Package(string title, string styles, string sheet)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
Add(zip, "[Content_Types].xml",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\"><Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/><Default Extension=\"xml\" ContentType=\"application/xml\"/><Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"/><Override PartName=\"/xl/worksheets/sheet1.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\"/><Override PartName=\"/xl/styles.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\"/></Types>");
|
||||
Add(zip, "_rels/.rels",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"><Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"xl/workbook.xml\"/></Relationships>");
|
||||
Add(zip, "xl/workbook.xml",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><workbook xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><sheets><sheet name=\""
|
||||
+ Esc(SheetName(title)) + "\" sheetId=\"1\" r:id=\"rId1\"/></sheets></workbook>");
|
||||
Add(zip, "xl/_rels/workbook.xml.rels",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"><Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\" Target=\"worksheets/sheet1.xml\"/><Relationship Id=\"rId2\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles\" Target=\"styles.xml\"/></Relationships>");
|
||||
Add(zip, "xl/styles.xml", styles);
|
||||
Add(zip, "xl/worksheets/sheet1.xml", sheet);
|
||||
}
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ report.cfc layout
|
||||
/// <summary>Style sheet: fonts 0 normal, 1 navy 14, 2 white 11, 3 black 12; fills 2 navy, 3 grey; borders 1 all thin black, 2 data row.</summary>
|
||||
internal static string Styles()
|
||||
{
|
||||
static string F(int size, string color) => $"<font><sz val=\"{size}\"/><color rgb=\"{color}\"/><name val=\"{Font}\"/></font>";
|
||||
static string B(string l, string r, string t, string b) =>
|
||||
$"<border><left style=\"thin\"><color rgb=\"{l}\"/></left><right style=\"thin\"><color rgb=\"{r}\"/></right><top style=\"{(t.Length > 0 ? "thin" : "none")}\">{(t.Length > 0 ? $"<color rgb=\"{t}\"/>" : "")}</top><bottom style=\"thin\"><color rgb=\"{b}\"/></bottom><diagonal/></border>";
|
||||
static string X(int font, int fill, int border, string h, string v) =>
|
||||
$"<xf numFmtId=\"0\" fontId=\"{font}\" fillId=\"{fill}\" borderId=\"{border}\" xfId=\"0\" applyFont=\"1\" applyFill=\"1\" applyBorder=\"1\" applyAlignment=\"1\"><alignment horizontal=\"{h}\" vertical=\"{v}\" wrapText=\"1\"/></xf>";
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><styleSheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
|
||||
sb.Append("<fonts count=\"4\">").Append(F(11, "FF000000")).Append(F(14, "FF003366")).Append(F(11, "FFFFFFFF")).Append(F(12, "FF000000")).Append("</fonts>");
|
||||
sb.Append("<fills count=\"4\"><fill><patternFill patternType=\"none\"/></fill><fill><patternFill patternType=\"gray125\"/></fill>")
|
||||
.Append("<fill><patternFill patternType=\"solid\"><fgColor rgb=\"FF003366\"/><bgColor indexed=\"64\"/></patternFill></fill>")
|
||||
.Append("<fill><patternFill patternType=\"solid\"><fgColor rgb=\"FFC0C0C0\"/><bgColor indexed=\"64\"/></patternFill></fill></fills>");
|
||||
sb.Append("<borders count=\"3\"><border><left/><right/><top/><bottom/><diagonal/></border>")
|
||||
.Append(B("FF000000", "FF000000", "FF000000", "FF000000")) // header: black box
|
||||
.Append(B("FF666699", "FF666699", "", "FF000000")) // data: violet sides, black bottom
|
||||
.Append("</borders>");
|
||||
sb.Append("<cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>");
|
||||
sb.Append("<cellXfs count=\"6\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\" xfId=\"0\" applyFont=\"1\"/>")
|
||||
.Append(X(1, 0, 0, "right", "top")) // 1 company name
|
||||
.Append(X(1, 0, 0, "center", "center")) // 2 title
|
||||
.Append(X(2, 2, 1, "center", "top")) // 3 header / filter label
|
||||
.Append(X(3, 3, 0, "center", "top")) // 4 filter value
|
||||
.Append(X(0, 0, 2, "center", "top")) // 5 data
|
||||
.Append("</cellXfs></styleSheet>");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string Sheet(LegacyReport r)
|
||||
{
|
||||
var cols = r.Headers.Count;
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
|
||||
sb.Append("<sheetViews><sheetView rightToLeft=\"1\" workbookViewId=\"0\"/></sheetViews><sheetFormatPr defaultRowHeight=\"15\"/>");
|
||||
sb.Append("<cols>");
|
||||
for (var c = 0; c < cols; c++)
|
||||
Col(sb, c, Chars(c < r.WidthsPt.Count ? r.WidthsPt[c] : 150));
|
||||
sb.Append("</cols><sheetData>");
|
||||
|
||||
// row 1: company name over the first three columns, title over columns E:F (legacy cell layout)
|
||||
sb.Append("<row r=\"1\" ht=\"30\" customHeight=\"1\">");
|
||||
Text(sb, 0, 1, r.CompanyName, Company);
|
||||
Blank(sb, 1, 1, Company); Blank(sb, 2, 1, Company);
|
||||
Text(sb, 4, 1, r.Title, Title);
|
||||
Blank(sb, 5, 1, Title);
|
||||
sb.Append("</row>");
|
||||
|
||||
// row 2: filters as label / value pairs
|
||||
sb.Append("<row r=\"2\" ht=\"20\" customHeight=\"1\">");
|
||||
var fc = 0;
|
||||
foreach (var (label, value) in r.Filters)
|
||||
{
|
||||
Text(sb, fc++, 2, label, Header);
|
||||
Text(sb, fc++, 2, value, FilterValue);
|
||||
}
|
||||
sb.Append("</row>");
|
||||
|
||||
// row 3: spacer, row 4: column captions
|
||||
sb.Append("<row r=\"3\" ht=\"9.94\" customHeight=\"1\"/>");
|
||||
sb.Append("<row r=\"4\" ht=\"20.06\" customHeight=\"1\">");
|
||||
for (var c = 0; c < cols; c++) Text(sb, c, 4, r.Headers[c], Header);
|
||||
sb.Append("</row>");
|
||||
|
||||
var rowNo = 5;
|
||||
foreach (var row in r.Rows)
|
||||
{
|
||||
sb.Append("<row r=\"").Append(rowNo).Append("\" ht=\"24.06\">");
|
||||
for (var c = 0; c < cols && c < row.Count; c++) Value(sb, c, rowNo, row[c], Data);
|
||||
sb.Append("</row>");
|
||||
rowNo++;
|
||||
}
|
||||
sb.Append("</sheetData><mergeCells count=\"2\"><mergeCell ref=\"A1:C1\"/><mergeCell ref=\"E1:F1\"/></mergeCells></worksheet>");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ الحوالات layout (companyreport.cfr output)
|
||||
/// <summary>
|
||||
/// Style sheet read from a legacy output file: fonts 1 Arial bold 21 (banner), 2 bold white 11 (labels), 3 bold black 11 (values), 4 white 11
|
||||
/// (column captions), 0 black 11 (data); navy #003366 fills; thin borders, violet (#666699) sides on the data rows.
|
||||
/// </summary>
|
||||
internal static string TransfersStyles()
|
||||
{
|
||||
static string Fn(string name, int size, string color, bool bold) =>
|
||||
$"<font>{(bold ? "<b/>" : "")}<sz val=\"{size}\"/><color rgb=\"{color}\"/><name val=\"{name}\"/></font>";
|
||||
static string X(int font, int fill, int border, string h) =>
|
||||
$"<xf numFmtId=\"0\" fontId=\"{font}\" fillId=\"{fill}\" borderId=\"{border}\" xfId=\"0\" applyFont=\"1\" applyFill=\"1\" applyBorder=\"1\" applyAlignment=\"1\"><alignment horizontal=\"{h}\" vertical=\"center\" wrapText=\"1\"/></xf>";
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><styleSheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
|
||||
sb.Append("<fonts count=\"5\">").Append(Fn(Font, 11, "FF000000", false)).Append(Fn("Arial", 21, "FF000000", true))
|
||||
.Append(Fn(Font, 11, "FFFFFFFF", true)).Append(Fn(Font, 11, "FF000000", true)).Append(Fn(Font, 11, "FFFFFFFF", false)).Append("</fonts>");
|
||||
sb.Append("<fills count=\"4\"><fill><patternFill patternType=\"none\"/></fill><fill><patternFill patternType=\"gray125\"/></fill>")
|
||||
.Append("<fill><patternFill patternType=\"solid\"><fgColor rgb=\"FF003366\"/><bgColor indexed=\"64\"/></patternFill></fill>")
|
||||
.Append("<fill><patternFill patternType=\"solid\"><fgColor rgb=\"FFFFFFFF\"/><bgColor indexed=\"64\"/></patternFill></fill></fills>");
|
||||
sb.Append("<borders count=\"3\"><border><left/><right/><top/><bottom/><diagonal/></border>")
|
||||
.Append("<border><left style=\"thin\"><color rgb=\"FF000000\"/></left><right style=\"thin\"><color rgb=\"FF000000\"/></right><top style=\"thin\"><color rgb=\"FF000000\"/></top><bottom style=\"thin\"><color rgb=\"FF000000\"/></bottom><diagonal/></border>")
|
||||
.Append("<border><left style=\"thin\"><color rgb=\"FF666699\"/></left><right style=\"thin\"><color rgb=\"FF666699\"/></right><top/><bottom style=\"thin\"><color rgb=\"FF000000\"/></bottom><diagonal/></border>")
|
||||
.Append("</borders>");
|
||||
sb.Append("<cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>");
|
||||
sb.Append("<cellXfs count=\"6\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\" xfId=\"0\" applyFont=\"1\"/>")
|
||||
.Append(X(1, 0, 0, "center")) // 1 banner (company, title)
|
||||
.Append(X(2, 2, 1, "center")) // 2 label of the account block
|
||||
.Append(X(3, 3, 1, "right")) // 3 value of the account block
|
||||
.Append(X(4, 2, 1, "center")) // 4 column caption
|
||||
.Append(X(0, 3, 2, "center")) // 5 data
|
||||
.Append("</cellXfs></styleSheet>");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string TransfersSheet(TransfersReport r)
|
||||
{
|
||||
var cols = r.Headers.Count;
|
||||
var last = TabularExport.ColumnName(cols - 1);
|
||||
var merges = new List<string>();
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
|
||||
sb.Append("<sheetViews><sheetView rightToLeft=\"1\" workbookViewId=\"0\"/></sheetViews><sheetFormatPr defaultRowHeight=\"12.75\"/>");
|
||||
sb.Append("<cols>");
|
||||
for (var c = 0; c < cols; c++) Col(sb, c, c < r.WidthsChars.Count ? r.WidthsChars[c] : 14);
|
||||
sb.Append("</cols><sheetData>");
|
||||
|
||||
// rows 1-3: company, title, blank banner row, each merged over the whole table width
|
||||
void Banner(int row, string? text)
|
||||
{
|
||||
sb.Append("<row r=\"").Append(row).Append("\" ht=\"27.75\" customHeight=\"1\">");
|
||||
if (text is null) Blank(sb, 0, row, TBanner); else Text(sb, 0, row, text, TBanner);
|
||||
for (var c = 1; c < cols; c++) Blank(sb, c, row, TBanner);
|
||||
sb.Append("</row>");
|
||||
merges.Add($"A{row}:{last}{row}");
|
||||
}
|
||||
Banner(1, r.CompanyName);
|
||||
Banner(2, r.Title);
|
||||
Banner(3, null);
|
||||
|
||||
// account block: label over A:B, value over C:last
|
||||
var rowNo = 4;
|
||||
foreach (var (label, value) in r.Info)
|
||||
{
|
||||
sb.Append("<row r=\"").Append(rowNo).Append("\" ht=\"28.5\" customHeight=\"1\">");
|
||||
Text(sb, 0, rowNo, label, TLabel);
|
||||
Blank(sb, 1, rowNo, TLabel);
|
||||
Value(sb, 2, rowNo, value, TValue);
|
||||
for (var c = 3; c < cols; c++) Blank(sb, c, rowNo, TValue);
|
||||
sb.Append("</row>");
|
||||
merges.Add($"A{rowNo}:B{rowNo}");
|
||||
merges.Add($"C{rowNo}:{last}{rowNo}");
|
||||
rowNo++;
|
||||
}
|
||||
// blank row, then the column captions (height 45)
|
||||
sb.Append("<row r=\"").Append(rowNo).Append("\" ht=\"28.5\" customHeight=\"1\"/>");
|
||||
merges.Add($"A{rowNo}:{last}{rowNo}");
|
||||
rowNo++;
|
||||
sb.Append("<row r=\"").Append(rowNo).Append("\" ht=\"45\" customHeight=\"1\">");
|
||||
for (var c = 0; c < cols; c++) Text(sb, c, rowNo, r.Headers[c], THeader);
|
||||
sb.Append("</row>");
|
||||
rowNo++;
|
||||
foreach (var row in r.Rows)
|
||||
{
|
||||
sb.Append("<row r=\"").Append(rowNo).Append("\" ht=\"24\" customHeight=\"1\">");
|
||||
for (var c = 0; c < cols && c < row.Count; c++) Value(sb, c, rowNo, row[c], TData);
|
||||
sb.Append("</row>");
|
||||
rowNo++;
|
||||
}
|
||||
sb.Append("</sheetData><mergeCells count=\"").Append(merges.Count).Append("\">");
|
||||
foreach (var m in merges) sb.Append("<mergeCell ref=\"").Append(m).Append("\"/>");
|
||||
sb.Append("</mergeCells></worksheet>");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ shared pieces
|
||||
private static void Col(StringBuilder sb, int c, double width) =>
|
||||
sb.Append("<col min=\"").Append(c + 1).Append("\" max=\"").Append(c + 1).Append("\" width=\"")
|
||||
.Append(width.ToString(CultureInfo.InvariantCulture)).Append("\" customWidth=\"1\"/>");
|
||||
|
||||
private static string Ref(int col, int row) => TabularExport.ColumnName(col) + row.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private static void Blank(StringBuilder sb, int col, int row, int style) =>
|
||||
sb.Append("<c r=\"").Append(Ref(col, row)).Append("\" s=\"").Append(style).Append("\"/>");
|
||||
|
||||
private static void Text(StringBuilder sb, int col, int row, string text, int style) =>
|
||||
sb.Append("<c r=\"").Append(Ref(col, row)).Append("\" s=\"").Append(style).Append("\" t=\"inlineStr\"><is><t xml:space=\"preserve\">")
|
||||
.Append(Esc(text)).Append("</t></is></c>");
|
||||
|
||||
private static void Value(StringBuilder sb, int col, int row, object? v, int style)
|
||||
{
|
||||
if (v is null) { Blank(sb, col, row, style); return; }
|
||||
if (v is sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal)
|
||||
sb.Append("<c r=\"").Append(Ref(col, row)).Append("\" s=\"").Append(style).Append("\"><v>")
|
||||
.Append(Convert.ToString(v, CultureInfo.InvariantCulture)).Append("</v></c>");
|
||||
else Text(sb, col, row, TabularExport.FormatCell(v), style);
|
||||
}
|
||||
|
||||
/// <summary>Sheet names: at most 31 characters and none of : \ / ? * [ ].</summary>
|
||||
public static string SheetName(string title)
|
||||
{
|
||||
var s = new string(title.Where(ch => ":\\/?*[]".IndexOf(ch) < 0).ToArray()).Trim();
|
||||
if (s.Length == 0) s = "Report";
|
||||
return s.Length > 31 ? s[..31] : s;
|
||||
}
|
||||
|
||||
private static void Add(ZipArchive zip, string name, string content)
|
||||
{
|
||||
var entry = zip.CreateEntry(name, CompressionLevel.Fastest);
|
||||
using var s = entry.Open();
|
||||
var bytes = new UTF8Encoding(false).GetBytes(content);
|
||||
s.Write(bytes, 0, bytes.Length);
|
||||
}
|
||||
|
||||
private static string Esc(string s)
|
||||
{
|
||||
var clean = new StringBuilder(s.Length);
|
||||
foreach (var ch in s)
|
||||
if (ch == '\t' || ch == '\n' || ch == '\r' || ch >= 0x20 && ch != 0xFFFE && ch != 0xFFFF) clean.Append(ch);
|
||||
return SecurityElement.Escape(clean.ToString()) ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,322 @@
|
|||
using System.Globalization;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.Integrations;
|
||||
using NTP.Application.Refinery.RemainingBalance;
|
||||
|
||||
namespace NTP.Application.Refinery.Trips;
|
||||
|
||||
public interface ITripActionService
|
||||
{
|
||||
Task<TripsResult> FirstAdvanceAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> SecondAdvanceAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> FirstAdvanceReverseAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> SecondAdvanceReverseAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> ExchangeAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> ExchangeAuditAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> ReceiptAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> PaymentAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> ActivateWalletExchangeAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> OrangePaymentAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> CashPaymentAsync(long id, CancellationToken ct);
|
||||
Task<TripsResult> ConfirmExchangeAsync(long id, CancellationToken ct);
|
||||
Task<TripVoucherDto> PrintAsync(long id, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Port of the actions of refinerytripFactory.cfc (diesel card advances and their reversals, receipt / payment / exchange of the wage,
|
||||
/// audit, cash and Orange payments, confirm / activate wallet exchange, print of the cash voucher).
|
||||
/// Role-specific branches of the legacy code are gone: the permission key of each endpoint decides who may act. The status rules the
|
||||
/// legacy STATUS_ACTION_MATRIX enforced per action are kept (WrongStatus = legacy ERROR.NO_AUTHORITY). Mobile push notifications of the
|
||||
/// legacy actions are not sent.
|
||||
/// </summary>
|
||||
public sealed class TripActionService(
|
||||
ITripRepository trips,
|
||||
ITripAmountsService amountsService,
|
||||
IRemainingBalanceService balances,
|
||||
IDinarakGateway dinarak,
|
||||
IDinarakReferenceGateway dinarakReference,
|
||||
IVoucherSerialRepository voucherSerial,
|
||||
IUnitOfWork uow,
|
||||
ICurrentUser user,
|
||||
ITripSettingsService settings) : ITripActionService
|
||||
{
|
||||
private string UserId => user.Id.ToString(CultureInfo.InvariantCulture);
|
||||
private static TripsResult Ok(long id) => new(TripErrors.Ok, id);
|
||||
|
||||
// ------------------------------------------------------------------ helpers
|
||||
private async Task<TripRecord> LoadAsync(long id, CancellationToken ct) =>
|
||||
await trips.GetAsync(id, ct) ?? throw new NotFoundException("RefineryTrip", id);
|
||||
|
||||
/// <summary>Locks the trip row (inside the transaction) and reads it again, so two operators cannot act on the same trip together.</summary>
|
||||
private async Task<TripRecord> LockAndLoadAsync(long id, CancellationToken ct)
|
||||
{
|
||||
if (await trips.LockAsync(id, ct) is null) throw new NotFoundException("RefineryTrip", id);
|
||||
return await LoadAsync(id, ct);
|
||||
}
|
||||
|
||||
private static (bool Exists, object? Value) OldValue(TripRecord t, string key) => key switch
|
||||
{
|
||||
"STATUS_CODE" => (true, t.StatusCode),
|
||||
"REMARKS" => (true, t.Remarks ?? string.Empty),
|
||||
"CURRENT_BALANCE" => (true, t.CurrentBalance),
|
||||
"DINARAK_REFERENCE_ID" => (true, t.DinarakReferenceId),
|
||||
_ => (false, null)
|
||||
};
|
||||
|
||||
/// <summary>REFINERY_TRIPS_LOG row like legacy logs.saveLog (nothing when no argument changed).</summary>
|
||||
private async Task LogAsync(string method, TripRecord old, IReadOnlyDictionary<string, object?> args, CancellationToken ct)
|
||||
{
|
||||
var built = TripLogBuilder.Build(method, k => OldValue(old, k), args);
|
||||
if (built is { } b) await trips.InsertLogAsync(old.Id, method, UserId, b.OldJson, b.NewJson, ct);
|
||||
}
|
||||
|
||||
private static void EnsureStatus(TripRecord t, params string[] allowed)
|
||||
{
|
||||
if (t.StatusCode is null || !allowed.Contains(t.StatusCode)) throw TripErrors.WrongStatus();
|
||||
}
|
||||
|
||||
private static string RequireTn(TripRecord t) => t.Tn ?? throw TripErrors.CardNotFound();
|
||||
|
||||
// ------------------------------------------------------------------ diesel card advances
|
||||
// refinerytripfactory.cfc:215-279 + dao FIRST_ADVANCED_PAYMENT
|
||||
public Task<TripsResult> FirstAdvanceAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var t = await LockAndLoadAsync(id, c);
|
||||
if (t.DieselCharge != 0) throw TripErrors.FirstAdvanceExists();
|
||||
var card = await trips.GetActiveCardAsync(RequireTn(t), c) ?? throw TripErrors.CardNotFound();
|
||||
var calc = await trips.CalculateDieselAsync(id, c) ?? throw TripErrors.PriceNotDeclared();
|
||||
|
||||
await trips.InsertCardLogAsync(card.Id, "FIRST_ADVANCED_PAYMENT", card.CurrentBalance, calc, calc - card.CurrentBalance, UserId, t.Pn ?? string.Empty, c);
|
||||
await trips.MarkFirstAdvanceAsync(id, UserId, c);
|
||||
await trips.UpdateCardBalanceAsync(card.Id, calc, UserId, id, c);
|
||||
await LogAsync("FIRST_ADVANCED_PAYMENT", t, new Dictionary<string, object?> { ["CURRENT_BALANCE"] = calc }, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
|
||||
// refinerytripfactory.cfc:285-351 + dao SECOND_ADVANCED_PAYMENT
|
||||
public Task<TripsResult> SecondAdvanceAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var t = await LockAndLoadAsync(id, c);
|
||||
if (t.DieselCharge != 1) throw TripErrors.SecondAdvanceExists();
|
||||
var calc = await trips.CalculateDieselAsync(id, c) ?? throw TripErrors.WrongLoadingDate();
|
||||
var card = await trips.GetActiveCardAsync(RequireTn(t), c) ?? throw TripErrors.CardNotFound();
|
||||
|
||||
await trips.InsertCardLogAsync(card.Id, "SECOND_ADVANCED_PAYMENT", card.CurrentBalance, calc, calc - card.CurrentBalance, UserId, t.Pn ?? string.Empty, c);
|
||||
await trips.MarkSecondAdvanceAsync(id, UserId, calc, c);
|
||||
await trips.UpdateCardBalanceAsync(card.Id, calc, UserId, id, c);
|
||||
await LogAsync("SECOND_ADVANCED_PAYMENT", t, new Dictionary<string, object?> { ["CURRENT_BALANCE"] = calc }, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
|
||||
// refinerytripfactory.cfc:358-412 + dao FIRST_ADVANCED_PAYMENT_REVERSE
|
||||
public Task<TripsResult> FirstAdvanceReverseAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var t = await LockAndLoadAsync(id, c);
|
||||
if (t.DieselCharge == 0) throw TripErrors.FirstAdvanceReverseExists();
|
||||
if (t.DieselCharge != 1) throw TripErrors.CannotReverseAdvance();
|
||||
await ReverseAsync(t, "FIRST_ADVANCED_PAYMENT", "FIRST_ADVANCED_PAYMENT_REVERSE", 0, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
|
||||
// refinerytripfactory.cfc:418-477 + dao SECOND_ADVANCED_PAYMENT_REVERSE
|
||||
public Task<TripsResult> SecondAdvanceReverseAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var t = await LockAndLoadAsync(id, c);
|
||||
if (t.DieselCharge == 1) throw TripErrors.SecondAdvanceExists();
|
||||
if (t.DieselCharge != 2) throw TripErrors.CannotReverseAdvance();
|
||||
if (await trips.CalculateDieselAsync(id, c) is null) throw TripErrors.WrongLoadingDate();
|
||||
await ReverseAsync(t, "SECOND_ADVANCED_PAYMENT", "SECOND_ADVANCED_PAYMENT_REVERSE", 1, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
|
||||
/// <summary>Takes back the amount of the last card log row of the advance: card balance - amount, a negative log row, the trip goes back one step.</summary>
|
||||
private async Task ReverseAsync(TripRecord t, string advanceMethod, string reverseMethod, int newDieselCharge, CancellationToken c)
|
||||
{
|
||||
var card = await trips.GetActiveCardAsync(RequireTn(t), c) ?? throw TripErrors.CardNotFound();
|
||||
var previous = await trips.GetLastCardLogAmountAsync(t.Pn ?? string.Empty, advanceMethod, c) ?? throw TripErrors.CannotReverseAdvance();
|
||||
var balance = card.CurrentBalance - previous;
|
||||
|
||||
await trips.MarkAdvanceReversedAsync(t.Id, UserId, newDieselCharge, c);
|
||||
await trips.InsertCardLogAsync(card.Id, reverseMethod, card.CurrentBalance, balance, -previous, UserId, t.Pn ?? string.Empty, c);
|
||||
await trips.UpdateCardBalanceAsync(card.Id, balance, UserId, t.Id, c);
|
||||
await LogAsync(reverseMethod, t, new Dictionary<string, object?> { ["CURRENT_BALANCE"] = balance }, c);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ wage payment
|
||||
// refinerytripfactory.cfc:494-595 (e-wallet through Dinarak)
|
||||
public async Task<TripsResult> ExchangeAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var t = await LoadAsync(id, ct);
|
||||
EnsureStatus(t, TripStatus.Discharged, TripStatus.PendingExchange);
|
||||
var amounts = await amountsService.ComputeAsync(t, ct);
|
||||
TripPaymentRules.EnsurePayable(amounts.NetWage, settings.Value.MaxPaymentAmount);
|
||||
|
||||
var wallet = await trips.GetActiveWalletByTruckAsync(RequireTn(t), ct);
|
||||
TripPaymentRules.EnsureWalletReady(wallet is not null, wallet?.Epayment, wallet?.WalletNumber, wallet?.OwnerNnpn?.ToString(CultureInfo.InvariantCulture), wallet?.OwnerName);
|
||||
|
||||
// the legacy action stored the figures before it called Dinarak (and they stay when the call fails)
|
||||
await trips.SaveAmountsAsync(id, UserId, amounts, ct);
|
||||
|
||||
// outside any transaction on purpose: the Dinarak log rows must survive a failed payment (legacy kept them too)
|
||||
var res = await dinarak.TransferAsync(id, wallet!.WalletNumber!, wallet.OwnerNnpn!.Value.ToString(CultureInfo.InvariantCulture),
|
||||
amounts.NetWage, wallet.OwnerName!, ct);
|
||||
|
||||
if (!res.Success)
|
||||
{
|
||||
await LogAsync("EXCHANGE", t, new Dictionary<string, object?> { ["REMARKS"] = res.Message }, ct);
|
||||
if (res.Code == "106") throw new BusinessException("DINARAK_DISABLED", "خدمة دينارك غير مفعلة في الإعدادات");
|
||||
throw TripErrors.DinarakRefused(res.Message);
|
||||
}
|
||||
|
||||
return await uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
// the money is already sent: record it whatever the status became meanwhile
|
||||
await trips.MarkExchangedAsync(id, UserId, "SUCCESSFULL_EXCHANGE_OPERATION", null, true, wallet.Id, c);
|
||||
await balances.ResetAfterPaymentAsync(RequireTn(t), id, c);
|
||||
await LogAsync("EXCHANGE", t, new Dictionary<string, object?>
|
||||
{
|
||||
["STATUS_CODE"] = TripStatus.Exchanged, ["REMARKS"] = "SUCCESSFULL_EXCHANGE_OPERATION"
|
||||
}, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
}
|
||||
|
||||
// refinerytripfactory.cfc:598-648
|
||||
public async Task<TripsResult> ReceiptAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var first = await LoadAsync(id, ct);
|
||||
var wallet = await trips.GetActiveWalletByTruckAsync(RequireTn(first), ct);
|
||||
if (wallet is null) throw TripErrors.NoPaymentMethod();
|
||||
if (wallet.Epayment == 1) throw TripErrors.ReloadForm();
|
||||
EnsureStatus(first, TripStatus.Discharged);
|
||||
|
||||
return await uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var t = await LockAndLoadAsync(id, c);
|
||||
EnsureStatus(t, TripStatus.Discharged);
|
||||
var amounts = await amountsService.ComputeAsync(t, c);
|
||||
if (amounts.NetWage == 0) throw TripErrors.PriceNotDeclared();
|
||||
await trips.SetStatusReceivedAsync(id, UserId, TripStatus.ReadyToPay, c);
|
||||
await trips.SaveAmountsAsync(id, UserId, amounts, c);
|
||||
await LogAsync("RECEIPT", t, new Dictionary<string, object?> { ["STATUS_CODE"] = TripStatus.ReadyToPay }, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
}
|
||||
|
||||
// refinerytripfactory.cfc:701-734
|
||||
public Task<TripsResult> ExchangeAuditAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var t = await LockAndLoadAsync(id, c);
|
||||
EnsureStatus(t, TripStatus.Discharged);
|
||||
var amounts = await amountsService.ComputeAsync(t, c);
|
||||
if (amounts.NetWage == 0) throw TripErrors.PriceNotDeclared();
|
||||
await trips.SetStatusReceivedAsync(id, UserId, TripStatus.PendingExchange, c);
|
||||
await trips.SaveAmountsAsync(id, UserId, amounts, c);
|
||||
await LogAsync("EXCHANGE_AUDIT", t, new Dictionary<string, object?> { ["STATUS_CODE"] = TripStatus.PendingExchange }, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
|
||||
// refinerytripfactory.cfc:651-698 (bank transfer paid by the accountant)
|
||||
public Task<TripsResult> PaymentAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var t = await LockAndLoadAsync(id, c);
|
||||
EnsureStatus(t, TripStatus.ReadyToPay);
|
||||
var wallet = await trips.GetActiveWalletByTruckAsync(RequireTn(t), c) ?? throw TripErrors.NoPaymentMethod();
|
||||
var amounts = await amountsService.ComputeAsync(t, c);
|
||||
TripPaymentRules.EnsurePayable(amounts.NetWage, settings.Value.MaxPaymentAmount);
|
||||
|
||||
await trips.MarkExchangedAsync(id, UserId, null, null, false, wallet.Id, c);
|
||||
await trips.SaveAmountsAsync(id, UserId, amounts, c);
|
||||
await balances.ResetAfterPaymentAsync(RequireTn(t), id, c);
|
||||
await LogAsync("PAYMENT", t, new Dictionary<string, object?> { ["STATUS_CODE"] = TripStatus.Exchanged }, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
|
||||
// refinerytripfactory.cfc:991-1085
|
||||
public Task<TripsResult> CashPaymentAsync(long id, CancellationToken ct) => WalletPaymentAsync(id, "CACH_PAYMENT", resetBalance: true, checkSign: true, ct);
|
||||
|
||||
// refinerytripfactory.cfc:885-965 (no legacy screen can reach it: there is no STATUS_ACTION_MATRIX row; no sign / size check, no balance reset)
|
||||
public Task<TripsResult> OrangePaymentAsync(long id, CancellationToken ct) => WalletPaymentAsync(id, "ORANGE_PAYMENT", resetBalance: false, checkSign: false, ct);
|
||||
|
||||
private Task<TripsResult> WalletPaymentAsync(long id, string method, bool resetBalance, bool checkSign, CancellationToken ct) =>
|
||||
uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var t = await LockAndLoadAsync(id, c);
|
||||
var amounts = await amountsService.ComputeAsync(t, c);
|
||||
TripPaymentRules.EnsurePayable(amounts.NetWage, settings.Value.MaxPaymentAmount, checkSign);
|
||||
EnsureStatus(t, TripStatus.Discharged);
|
||||
|
||||
var wallet = await trips.GetActiveWalletByTruckAsync(RequireTn(t), c);
|
||||
TripPaymentRules.EnsureWalletReady(wallet is not null, wallet?.Epayment, wallet?.WalletNumber, wallet?.OwnerNnpn?.ToString(CultureInfo.InvariantCulture), wallet?.OwnerName);
|
||||
|
||||
await trips.SaveAmountsAsync(id, UserId, amounts, c);
|
||||
await trips.MarkExchangedAsync(id, UserId, "SUCCESSFULL_EXCHANGE_OPERATION", method, true, wallet!.Id, c);
|
||||
if (resetBalance) await balances.ResetAfterPaymentAsync(RequireTn(t), id, c);
|
||||
await LogAsync(method, t, new Dictionary<string, object?>
|
||||
{
|
||||
["STATUS_CODE"] = TripStatus.Exchanged, ["REMARKS"] = "SUCCESSFULL_EXCHANGE_OPERATION"
|
||||
}, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
|
||||
// refinerytripfactory.cfc:737-781: asks Dinarak first whether the transfer already went through, then moves the message id by 0.01
|
||||
public async Task<TripsResult> ActivateWalletExchangeAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var t = await LoadAsync(id, ct);
|
||||
EnsureStatus(t, TripStatus.PendingExchange, TripStatus.Discharged);
|
||||
|
||||
if (t.DinarakReferenceId is { } reference)
|
||||
{
|
||||
var status = await dinarakReference.GetTransferByReferenceAsync(reference, ct);
|
||||
if (status.StatusName == "ERROR") throw TripErrors.DinarakStatusUnknown();
|
||||
if (status.Accepted) throw TripErrors.PaymentAlreadySent();
|
||||
}
|
||||
|
||||
return await uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var locked = await LockAndLoadAsync(id, c);
|
||||
var next = await trips.BumpDinarakReferenceAsync(id, UserId, c);
|
||||
await LogAsync("ACTIVATE_WALLET_EXCHANGE", locked, new Dictionary<string, object?> { ["DINARAK_REFERENCE_ID"] = next }, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
}
|
||||
|
||||
// refinerytripfactory.cfc:967-984 + dao CONFIRM_EXCHANGE
|
||||
public async Task<TripsResult> ConfirmExchangeAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var t = await LoadAsync(id, ct);
|
||||
EnsureStatus(t, TripStatus.Discharged, TripStatus.PendingExchange);
|
||||
if (!await trips.HasTransferLogAsync(id, ct)) throw TripErrors.NoFailedTransfer();
|
||||
|
||||
return await uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
await LockAndLoadAsync(id, c);
|
||||
await trips.ConfirmExchangeAsync(id, UserId, c);
|
||||
// not in the legacy action (it left the truck balance applied twice); the trip was paid, so the balance is consumed
|
||||
await balances.ResetAfterPaymentAsync(RequireTn(t), id, c);
|
||||
await LogAsync("CONFIRM_EXCHANGE", t, new Dictionary<string, object?> { ["STATUS_CODE"] = TripStatus.Exchanged }, c);
|
||||
return Ok(id);
|
||||
}, ct);
|
||||
}
|
||||
|
||||
// refinerytripfactory.cfc:1112-1243: voucher serial stored on first print, amount from CalculateRefinaryAmount
|
||||
public Task<TripVoucherDto> PrintAsync(long id, CancellationToken ct) => uow.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
var t = await LoadAsync(id, c);
|
||||
EnsureStatus(t, TripStatus.Discharged);
|
||||
|
||||
long serial;
|
||||
if (t.VoucherSerialNumber is { } existing) serial = existing;
|
||||
else
|
||||
{
|
||||
serial = await voucherSerial.NextAsync(c);
|
||||
await trips.SetVoucherSerialAsync(id, serial, c);
|
||||
}
|
||||
var amount = await trips.CalculateAmountAsync(id, c) ?? throw TripErrors.PriceNotDeclared();
|
||||
await LogAsync("PRINT", t, new Dictionary<string, object?> { ["NOTES"] = string.Empty }, c);
|
||||
|
||||
return new TripVoucherDto(id, t.Pn ?? string.Empty, serial.ToString(CultureInfo.InvariantCulture),
|
||||
DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), amount, t.DischargeAuthNo, t.OwnerName);
|
||||
}, ct);
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
using NTP.Application.Refinery.RemainingBalance;
|
||||
|
||||
namespace NTP.Application.Refinery.Trips;
|
||||
|
||||
public interface ITripAmountsService
|
||||
{
|
||||
/// <summary>Legacy calculateAmounts for a trip record (variables of the loading date, weights, remaining balance of the truck).</summary>
|
||||
Task<TripAmounts> ComputeAsync(TripRecord trip, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class TripAmountsService(ITripRepository trips, IRemainingBalanceRepository balances) : ITripAmountsService
|
||||
{
|
||||
public async Task<TripAmounts> ComputeAsync(TripRecord t, CancellationToken ct)
|
||||
{
|
||||
if (t.LoadingDate is null) return TripAmounts.Zero;
|
||||
var pairs = await trips.GetVariablesAsync(t.LoadingDate.Value.Date, ct);
|
||||
if (pairs.Count == 0) return TripAmounts.Zero;
|
||||
var weights = new TripWeights(t.NetLoadingWeight ?? 0, t.NetDischargeWeight ?? 0, t.WaterAmount ?? 0, await trips.GetWaterFlagAsync(t.Id, ct));
|
||||
decimal? remaining = t.Tn is null ? null : (await balances.GetByTruckAsync(t.Tn, ct))?.RemainingBalance;
|
||||
return TripCalculator.Calculate(weights, TripVariables.FromPairs(pairs), remaining);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
using System.Globalization;
|
||||
|
||||
namespace NTP.Application.Refinery.Trips;
|
||||
|
||||
/// <summary>Variables of REFINERY_VARIABLES valid on a loading date (one value per KEY_NAME; absent key = 0).</summary>
|
||||
public sealed record TripVariables(
|
||||
decimal TonWage,
|
||||
decimal TonPrice,
|
||||
decimal TonPriceCorrection,
|
||||
decimal DriverTip,
|
||||
decimal PermitDispatch,
|
||||
decimal WaybillFee,
|
||||
decimal Commission,
|
||||
decimal TolerancePercentage,
|
||||
decimal FirstAdvancePayment,
|
||||
decimal DieselLiterPrice)
|
||||
{
|
||||
/// <summary>Builds the record from KEY_NAME -> KEY_VALUE pairs (first value of a key wins, like legacy query-of-queries row 1).</summary>
|
||||
public static TripVariables FromPairs(IEnumerable<KeyValuePair<string, string?>> pairs)
|
||||
{
|
||||
var d = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var (k, v) in pairs)
|
||||
if (!d.ContainsKey(k)) d[k] = Parse(v);
|
||||
decimal Get(string k) => d.TryGetValue(k, out var x) ? x : 0m;
|
||||
return new TripVariables(Get("TON_WAGE"), Get("TON_PRICE"), Get("TON_PRICE_CORRECTION"), Get("DRIVER_TIP"),
|
||||
Get("PERMIT_DISPATCH"), Get("WAYBILL_FEE"), Get("COMMISSION"), Get("TOLERANCE_PERCENTAGE"),
|
||||
Get("FIRST_ADVANCE_PAYMENT"), Get("DIESEL_LITER_PRICE"));
|
||||
}
|
||||
|
||||
private static decimal Parse(string? v) =>
|
||||
decimal.TryParse(v?.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var x) ? x : 0m;
|
||||
}
|
||||
|
||||
/// <summary>Weights of a trip that the wage calculation needs.</summary>
|
||||
public sealed record TripWeights(decimal NetLoadingWeight, decimal NetDischargeWeight, decimal WaterAmount, int? WaterFlag);
|
||||
|
||||
/// <summary>Result of the legacy refinerytripFactory.calculateAmounts (all money values rounded to 3 decimals like numberFormat '_.000').</summary>
|
||||
public sealed record TripAmounts(
|
||||
decimal TripNetWage,
|
||||
decimal NetWage,
|
||||
decimal RemainingBalance,
|
||||
decimal PenaltyAmount,
|
||||
decimal PenaltyQuantity,
|
||||
decimal QuantityWage,
|
||||
decimal ToleranceQuantity,
|
||||
decimal TonWage,
|
||||
decimal TonPrice,
|
||||
decimal DriverTip,
|
||||
decimal PermitDispatch,
|
||||
decimal WaybillFee,
|
||||
decimal Commission,
|
||||
decimal TolerancePercentage,
|
||||
decimal FirstAdvancePayment,
|
||||
decimal SecondAdvancePayment,
|
||||
decimal DieselLiterPrice,
|
||||
decimal CalculatedQuantityTon)
|
||||
{
|
||||
/// <summary>No price variables for the loading date: every figure is 0 (legacy returned the zero struct).</summary>
|
||||
public static TripAmounts Zero { get; } = new(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
/// <summary>Pure port of refinerytripFactory.calculateAmounts (refinerytripfactory.cfc:785-881).</summary>
|
||||
public static class TripCalculator
|
||||
{
|
||||
/// <summary>Liters of diesel of a trip (350) priced in the wage deduction (legacy literal).</summary>
|
||||
public const decimal DieselLiters = 350m;
|
||||
|
||||
private static decimal R3(decimal v) => Math.Round(v, 3, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <param name="useTonPriceCorrection">legacy calculateMode 'TON_PRICE_CORRECTION': penalty priced with TON_PRICE_CORRECTION and the truck's remaining balance is not added.</param>
|
||||
/// <param name="remainingBalance">REFINERY_REMAINING_BALANCE of the truck (null = no row); ignored in correction mode.</param>
|
||||
public static TripAmounts Calculate(TripWeights w, TripVariables v, decimal? remainingBalance, bool useTonPriceCorrection = false)
|
||||
{
|
||||
// ToleranceQuantity = Floor(NET_LOADING_WEIGHT * TOLERANCE_PERCENTAGE)
|
||||
var toleranceQuantity = Math.Floor(w.NetLoadingWeight * v.TolerancePercentage);
|
||||
var water = w.WaterAmount;
|
||||
var allow = toleranceQuantity;
|
||||
|
||||
// water that is not accompanying (flag 1) is ignored and gets no tolerance (factory 816-819)
|
||||
if (w.WaterFlag == 1 && water > 0)
|
||||
{
|
||||
water = 0;
|
||||
allow = 0;
|
||||
}
|
||||
|
||||
var penaltyQuantity = w.NetLoadingWeight - w.NetDischargeWeight - water;
|
||||
var penaltyAmount = 0m;
|
||||
if (penaltyQuantity <= allow)
|
||||
{
|
||||
penaltyQuantity = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
penaltyQuantity = R3(penaltyQuantity - allow);
|
||||
var tonPrice = useTonPriceCorrection ? v.TonPriceCorrection : v.TonPrice;
|
||||
penaltyAmount = R3(penaltyQuantity / 1000m * tonPrice);
|
||||
}
|
||||
|
||||
var calculatedQuantityTon = water >= (w.NetLoadingWeight - w.NetDischargeWeight)
|
||||
? w.NetLoadingWeight / 1000m
|
||||
: (w.NetDischargeWeight + water) / 1000m;
|
||||
|
||||
var quantityWage = R3(calculatedQuantityTon * v.TonWage);
|
||||
var diesel = DieselLiters * v.DieselLiterPrice;
|
||||
var secondAdvance = diesel - v.FirstAdvancePayment;
|
||||
|
||||
var trip = R3(quantityWage - penaltyAmount - v.DriverTip - v.PermitDispatch - v.WaybillFee - diesel - v.Commission);
|
||||
var net = trip;
|
||||
var remaining = 0m;
|
||||
if (!useTonPriceCorrection && remainingBalance.HasValue)
|
||||
{
|
||||
net = trip + remainingBalance.Value;
|
||||
remaining = remainingBalance.Value;
|
||||
}
|
||||
|
||||
return new TripAmounts(
|
||||
TripNetWage: trip,
|
||||
NetWage: R3(net),
|
||||
RemainingBalance: R3(remaining),
|
||||
PenaltyAmount: penaltyAmount,
|
||||
PenaltyQuantity: penaltyQuantity,
|
||||
QuantityWage: quantityWage,
|
||||
ToleranceQuantity: toleranceQuantity,
|
||||
TonWage: R3(v.TonWage),
|
||||
TonPrice: R3(v.TonPrice),
|
||||
DriverTip: R3(v.DriverTip),
|
||||
PermitDispatch: R3(v.PermitDispatch),
|
||||
WaybillFee: R3(v.WaybillFee),
|
||||
Commission: R3(v.Commission),
|
||||
TolerancePercentage: R3(v.TolerancePercentage),
|
||||
FirstAdvancePayment: v.FirstAdvancePayment,
|
||||
SecondAdvancePayment: secondAdvance,
|
||||
DieselLiterPrice: R3(v.DieselLiterPrice),
|
||||
CalculatedQuantityTon: calculatedQuantityTon);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
using NTP.Application.Common;
|
||||
using NTP.Application.Refinery.RemainingBalance;
|
||||
|
||||
namespace NTP.Application.Refinery.Trips;
|
||||
|
||||
public interface ITripQueryService
|
||||
{
|
||||
Task<PagedResult<TripGridDto>> SearchAsync(TripQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<TripDetailDto> GetAsync(long id, CancellationToken ct);
|
||||
Task<PagedResult<TripLogDto>> LogAsync(long id, PageRequest page, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of refinerytripFactory.search / getREFINERYTRIP / log (grid, trip form, history popup).</summary>
|
||||
public sealed class TripQueryService(
|
||||
ITripRepository trips,
|
||||
ITripAmountsService amounts) : ITripQueryService
|
||||
{
|
||||
public static void ValidateRanges(TripQuery q)
|
||||
{
|
||||
if (q.LoadingDateFrom > q.LoadingDateTo || q.PaymentedDateFrom > q.PaymentedDateTo) throw TripErrors.FromAfterTo();
|
||||
}
|
||||
|
||||
public async Task<PagedResult<TripGridDto>> SearchAsync(TripQuery query, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
ValidateRanges(query);
|
||||
var r = await trips.SearchAsync(query, page, ct);
|
||||
var items = r.Items.Select(x => new TripGridDto(
|
||||
x.Id, x.Pn, x.DispatchDate, x.LoadingNo, x.DischargeAuthNo, x.DischargeEntryDate, x.Tn, x.Trn, x.Nnpn,
|
||||
x.WageClaimId, x.WageClaimNo, x.StatusCode, x.DieselCharge, x.HavePaymentMethod != "0",
|
||||
(x.WaterAmount ?? 0) != 0, x.ReversePayment == 1, x.NetWage)).ToList();
|
||||
return new PagedResult<TripGridDto>(items, r.Page, r.PageSize, r.TotalCount);
|
||||
}
|
||||
|
||||
public async Task<TripDetailDto> GetAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var t = await trips.GetAsync(id, ct) ?? throw new NotFoundException("RefineryTrip", id);
|
||||
var status = t.StatusCode ?? string.Empty;
|
||||
|
||||
// DISCHARGED / READY_TO_PAY: figures are recomputed from today's variables (factory 129-134)
|
||||
decimal? netWage = t.NetWage, tripNetWage = t.TripNetWage, remaining = t.RemainingBalance;
|
||||
if (TripStatus.RecalculateAmounts.Contains(status) && t.LoadingDate is not null)
|
||||
{
|
||||
var a = await amounts.ComputeAsync(t, ct);
|
||||
netWage = a.NetWage;
|
||||
tripNetWage = a.TripNetWage;
|
||||
remaining = a.RemainingBalance;
|
||||
}
|
||||
|
||||
// CalculateRefinaryDiesel is both the "new balance" and, for the late statuses, the second payment value shown on the form
|
||||
var newBalance = await trips.CalculateDieselAsync(id, ct);
|
||||
var second = TripStatus.ShowSecondPayment.Contains(status) ? newBalance : null;
|
||||
var first = await trips.GetFirstPaymentValueAsync(ct);
|
||||
var audit = await trips.GetAuditModeAsync(ct);
|
||||
|
||||
var wallet = t.Tn is null ? null : await trips.GetActiveWalletByTruckAsync(t.Tn, ct);
|
||||
// a trip that was already paid shows the wallet it was paid to (factory 172-182)
|
||||
if (t.RefineryWalletId is { } wid) wallet = await trips.GetWalletAsync(wid, ct) ?? wallet;
|
||||
var walletDto = wallet is null
|
||||
? new TripWalletDto(null, null, null, null, null, null, null, t.DriverWalletNumber)
|
||||
: new TripWalletDto(wallet.Epayment, wallet.WalletNumber, wallet.OwnerNnpn?.ToString(), wallet.OwnerName,
|
||||
wallet.BankAccount, wallet.Iban, wallet.BankName, t.DriverWalletNumber);
|
||||
|
||||
var hasTransfer = (status is TripStatus.Discharged or TripStatus.PendingExchange) && await trips.HasTransferLogAsync(id, ct);
|
||||
var actions = TripActionRules.Available(status, t.DieselCharge, wallet?.Epayment, audit, hasTransfer);
|
||||
|
||||
return new TripDetailDto(
|
||||
t.Id, t.Pn, t.StatusCode, t.DispatchDate, t.ActualLoadingDate, t.ClientName, t.Tn, t.Trn, t.Nnpn, t.Drvr, t.LoadingNo,
|
||||
t.GrossWeight, t.EmptyWeight, t.NetLoadingWeight, t.LitersWeight, t.DischargeAuthNo, t.DischargeEntryDate,
|
||||
t.ActualGrossWeight, t.ActualEmptyWeight, t.NetDischargeWeight, t.WaterAmount, t.SedimentAmount, t.WeightDifference,
|
||||
netWage, tripNetWage, remaining, t.DieselCharge, t.ReversePayment == 1, t.CardNumber, t.CurrentBalance, newBalance,
|
||||
first, second, t.WageClaimId, t.WageClaimNo, t.Remarks, t.ReceivedByName,
|
||||
t.ReceivedDate?.ToString("yyyy-MM-dd HH:mm"), t.PaymentedDate?.ToString("yyyy-MM-dd HH:mm"), t.PaymentOptions,
|
||||
t.VoucherSerialNumber, audit, walletDto, actions);
|
||||
}
|
||||
|
||||
public async Task<PagedResult<TripLogDto>> LogAsync(long id, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
var r = await trips.SearchLogAsync(id, page, ct);
|
||||
return new PagedResult<TripLogDto>(
|
||||
r.Items.Select(x => new TripLogDto(x.Id, x.MethodName, x.LogDate, x.Login, x.OldData, x.NewData)).ToList(),
|
||||
r.Page, r.PageSize, r.TotalCount);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,218 @@
|
|||
using System.Globalization;
|
||||
using NTP.Application.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Refinery.Trips;
|
||||
|
||||
public interface ITripReportService
|
||||
{
|
||||
Task<TripExportFile> TripsAsync(TripQuery query, CancellationToken ct);
|
||||
Task<TripExportFile> OperatorAsync(TripQuery query, CancellationToken ct);
|
||||
Task<TripExportFile> ExchangeAsync(TripQuery query, CancellationToken ct);
|
||||
Task<TripExportFile> DieselAsync(DieselReportQuery query, CancellationToken ct);
|
||||
Task<TripExportFile> CardsAsync(string? tn, CancellationToken ct);
|
||||
Task<TripExportFile> BankAsync(BankReportQuery query, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Excel reports of the trips screen: trips (factoryweb.report, manager column set), diesel card movements (REFINERY_DIESEL_REPORT_VIEW),
|
||||
/// diesel balances of the cards (refineryCardsReport) and the bank report (refineryBankReport; its layout lives in a binary ColdFusion
|
||||
/// report template that cannot be read, so the columns here are a reasonable set, see the module notes).
|
||||
/// </summary>
|
||||
public sealed class TripReportService(ITripRepository trips) : ITripReportService
|
||||
{
|
||||
private static string Stamp => DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
|
||||
|
||||
private static TripExportFile Xlsx(string name, ExportTable table) =>
|
||||
new(TabularExport.ToXlsx([table], rightToLeft: true), $"{name}-{Stamp}.xlsx", TabularExport.XlsxContentType);
|
||||
|
||||
private static string Day(DateTime? d) => d?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) ?? string.Empty;
|
||||
|
||||
// ---- legacy report layout (aqabaTCSBCommon.report.create): the trips, exchange and diesel-balance reports use it
|
||||
private const string CompanyName = "شركة نافذ للخدمات اللوجستية"; // caption PUBLIC.NAFITH_NAME
|
||||
private const string TripsTitle = "شاشة الارساليات"; // caption MENU.REFINERYTRIPS
|
||||
private const string CardsTitle = "أرصدة الديزل"; // caption PUBLIC.CARD_REPORT
|
||||
|
||||
// column widths in points, as set in the legacy factory: report() manager set (650-820), refineryCardsReport (559-576)
|
||||
private static readonly int[] TripsWidths =
|
||||
[100, 150, 150, 150, 200, 200, 200, 200, 150, 150, 150, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 220, 200, 200, 200, 200, 200, 200, 200, 150];
|
||||
private static readonly int[] CardsWidths = [100, 150, 150, 150];
|
||||
|
||||
private static TripExportFile Legacy(
|
||||
string name, string title, IReadOnlyList<(string Label, string Value)> filters, string[] headers, int[] widths,
|
||||
IReadOnlyList<IReadOnlyList<object?>> data) =>
|
||||
new(LegacyReportWorkbook.ToXlsx(new LegacyReport(CompanyName, title, filters, headers, widths, data)),
|
||||
$"{name}-{Stamp}.xlsx", TabularExport.XlsxContentType);
|
||||
|
||||
/// <summary>The filters row of the legacy report: the text filters in a fixed order (status shown with its caption), then the dates, oldest first.</summary>
|
||||
public static IReadOnlyList<(string Label, string Value)> Filters(TripQuery q)
|
||||
{
|
||||
var f = new List<(string Label, string Value)>();
|
||||
void Add(string label, string? v) { if (!string.IsNullOrWhiteSpace(v)) f.Add((label, v.Trim())); }
|
||||
Add("رقم الارسالية", q.Pn);
|
||||
Add("رقم القاطرة", q.Tn);
|
||||
Add("رقم المقطورة", q.Trn);
|
||||
Add("الرقم الوطني", q.Nnpn);
|
||||
Add("رقم الحمولة", q.LoadingNo);
|
||||
Add("رقم النموذج", q.DischargeAuthNo);
|
||||
if (!string.IsNullOrWhiteSpace(q.StatusCode))
|
||||
f.Add(("الحالة", string.Join("،", q.StatusCode.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Select(s => s.Trim('\'')).Select(s => TripStatus.Captions.GetValueOrDefault(s, s)))));
|
||||
Add("رقم مطالبة اجور النقل", q.WageClaimNo);
|
||||
Add("رقم الحساب", q.BankAccount);
|
||||
var dates = new List<(DateTime Value, string Label)>();
|
||||
void AddDate(string label, DateTime? d) { if (d is not null) dates.Add((d.Value, label)); }
|
||||
AddDate("تاريخ الارسالية", q.DispatchDate);
|
||||
AddDate("تاريخ النموذج", q.DischargeEntryDate);
|
||||
AddDate("من تاريخ التحميل", q.LoadingDateFrom);
|
||||
AddDate("الى تاريخ التحميل", q.LoadingDateTo);
|
||||
AddDate("من تاريخ الدفع", q.PaymentedDateFrom);
|
||||
AddDate("الى تاريخ الدفع", q.PaymentedDateTo);
|
||||
foreach (var (value, label) in dates.OrderBy(d => d.Value)) f.Add((label, Day(value)));
|
||||
return f;
|
||||
}
|
||||
|
||||
public async Task<TripExportFile> TripsAsync(TripQuery query, CancellationToken ct)
|
||||
{
|
||||
TripQueryService.ValidateRanges(query);
|
||||
var rows = await trips.ReportAsync(query, ct);
|
||||
|
||||
var data = new List<IReadOnlyList<object?>>();
|
||||
var n = 0;
|
||||
foreach (var r in rows)
|
||||
{
|
||||
// NEW_TOTAL_VALUE: balance after the next diesel payment; from the 3rd step on it is just the balance
|
||||
decimal? newTotal = r.DieselCharge >= 2 ? r.CurrentBalance : await trips.CalculateDieselAsync(r.Id, ct);
|
||||
|
||||
// factoryweb.report 624-639: payment method text as the accountant reads it
|
||||
var paid = string.IsNullOrEmpty(r.PaidEpayment) ? r.PaymentMethod : r.PaidEpayment;
|
||||
string? bankName = r.BankName, iban = r.Iban, account = r.BankAccount, wallet = r.WalletNumber;
|
||||
var paidText = paid?.Trim();
|
||||
if (paidText == "الكتروني")
|
||||
{
|
||||
if (r.PaymentOptions?.Trim() == "CACH_PAYMENT") paid = "دفع نقدي";
|
||||
bankName = iban = account = string.Empty;
|
||||
}
|
||||
else if (paidText == "حوالة") wallet = string.Empty;
|
||||
|
||||
data.Add([
|
||||
++n, r.Pn, r.DispatchDate, r.LoadingNo, r.DischargeAuthNo, r.DischargeEntryDate, r.NetLoadingWeight, r.NetDischargeWeight,
|
||||
r.Tn, r.Trn, r.Nnpn, r.CurrentBalance, newTotal, r.NetWage, r.TripNetWage, r.RemainingBalance,
|
||||
TripStatus.Captions.GetValueOrDefault(r.StatusCode ?? string.Empty, r.StatusCode ?? string.Empty), r.WageClaimNo,
|
||||
Day(r.PaymentedDate), Day(r.ReceivedDate), r.ReceivedByName, r.ActualLoadingDate, paid, r.OwnerName, r.OwnerNameEnglish,
|
||||
bankName, iban, account, wallet, r.OwnerNnpn
|
||||
]);
|
||||
}
|
||||
|
||||
string[] headers =
|
||||
[
|
||||
"متسلسل", "رقم الارسالية", "تاريخ الارسالية", "رقم الحمولة", "رقم النموذج", "تاريخ النموذج", "الوزن الصافي(كغ)",
|
||||
"الوزن الصافي للتفريغ(كغ)", "رقم القاطرة", "رقم المقطورة", "الرقم الوطني", "القيمة التراكمية الحالية", "القيمة التراكمية الجديدة",
|
||||
"صافي قيمة الصرف الفعلي", "قيمة اجور النقل", "قيمة الذمم السابقة", "الحالة", "رقم مطالبة اجور النقل", "تاريخ الدفع",
|
||||
"تاريخ الاستلام", "اسم المستلم", "تاريخ التحميل", "آلية الصرف", "صاحب الحساب", "صاحب الحساب بالانجليزي", "البنك", "IBAN",
|
||||
"رقم الحساب", "رقم المحفظة", "رقم هوية المالك"
|
||||
];
|
||||
return Legacy("refinery-trips", TripsTitle, Filters(query), headers, TripsWidths, data);
|
||||
}
|
||||
|
||||
/// <summary>factoryweb.report, REFINERY_OP column set (lines 825-870): form no., truck, net wage, paid / received dates and receiver.
|
||||
/// The legacy limit to the trips the user received himself is a role rule and is not ported.</summary>
|
||||
public async Task<TripExportFile> OperatorAsync(TripQuery query, CancellationToken ct)
|
||||
{
|
||||
TripQueryService.ValidateRanges(query);
|
||||
var rows = await trips.ReportAsync(query, ct);
|
||||
var data = rows.Select((r, i) => (IReadOnlyList<object?>)
|
||||
[i + 1, r.DischargeAuthNo, r.Tn, r.NetWage, Day(r.PaymentedDate), Day(r.ReceivedDate), r.ReceivedByName]).ToList();
|
||||
string[] headers = ["متسلسل", "رقم النموذج", "رقم القاطرة", "صافي قيمة الصرف الفعلي", "تاريخ الدفع", "تاريخ الاستلام", "اسم المستلم"];
|
||||
return Xlsx("refinery-trips-operator", new ExportTable(["شاشة الارساليات"], headers, data));
|
||||
}
|
||||
|
||||
// legacy الحوالات list (companyreport.cfr output): title and column widths in characters, as in the legacy sample files
|
||||
private const string TransfersTitle = "قائمة ارقام نماذج التفريغ المعدة لصرف أجور النقل";
|
||||
private static readonly double[] TransfersWidths = [9.14, 10.86, 16.71, 12.29, 12.71, 24.86, 12.29, 13.57, 13.71, 11.43, 15.43, 15.43, 24.29];
|
||||
|
||||
/// <summary>
|
||||
/// الحوالات (legacy refineryBankReport, layout of companyreport.cfr): the discharge forms prepared for payment by bank transfer to ONE account.
|
||||
/// The bank account is required (ERROR.NO_BANK_ACCOUNT); the other filters are the legacy ones: status, wage-claim flag and payment dates.
|
||||
/// The sheet shows the account block (owner, English name, bank, account number, IBAN, total net wage) and then the trips table.
|
||||
/// </summary>
|
||||
public async Task<TripExportFile> ExchangeAsync(TripQuery query, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(query.BankAccount)) throw TripErrors.NoBankAccount();
|
||||
if (query.PaymentedDateFrom > query.PaymentedDateTo) throw TripErrors.FromAfterTo();
|
||||
var q = new TripQuery(
|
||||
BankAccount: query.BankAccount, StatusCode: query.StatusCode, HasWageClaim: query.HasWageClaim,
|
||||
PaymentedDateFrom: query.PaymentedDateFrom, PaymentedDateTo: query.PaymentedDateTo);
|
||||
var rows = await trips.ReportAsync(q, ct);
|
||||
|
||||
var first = rows.FirstOrDefault();
|
||||
var total = Math.Round(rows.Sum(r => r.NetWage ?? 0m), 3);
|
||||
IReadOnlyList<(string Label, object? Value)> info =
|
||||
[
|
||||
("صاحب الحساب", first?.OwnerName),
|
||||
("الاسم بالانجليزي", first?.OwnerNameEnglish),
|
||||
("اسم البنك", first?.BankName),
|
||||
("رقم الحساب", first?.BankAccount ?? query.BankAccount.Trim()),
|
||||
("IBAN", first?.Iban),
|
||||
("صافي قيمة اجور النقل", total)
|
||||
];
|
||||
var data = rows.Select((r, i) => (IReadOnlyList<object?>)
|
||||
[
|
||||
i + 1, r.Pn, r.DispatchDate, r.LoadingNo, r.DischargeAuthNo, r.DischargeEntryDate, r.NetLoadingWeight, r.NetDischargeWeight,
|
||||
r.Tn, r.Trn, r.NetWage, TripStatus.Captions.GetValueOrDefault(r.StatusCode ?? string.Empty, r.StatusCode ?? string.Empty),
|
||||
r.ReceivedDate?.ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture)
|
||||
]).ToList();
|
||||
string[] headers =
|
||||
[
|
||||
"متسلسل", "رقم الارسالية", "تاريخ الارسالية", "رقم الحمولة", "رقم النموذج", "تاريخ النموذج", "الوزن الصافي للتحميل (كغ)",
|
||||
"الوزن الصافي للتفريغ(كغ)", "رقم القاطرة", "رقم المقطورة", "صافي قيمة اجور النقل", "الحالة", "تاريخ الاستلام"
|
||||
];
|
||||
return new(
|
||||
LegacyReportWorkbook.ToTransfersXlsx(new TransfersReport(CompanyName, TransfersTitle, info, headers, TransfersWidths, data)),
|
||||
$"refinery-transfers-{Stamp}.xlsx", TabularExport.XlsxContentType);
|
||||
}
|
||||
|
||||
public async Task<TripExportFile> DieselAsync(DieselReportQuery query, CancellationToken ct)
|
||||
{
|
||||
if (query.DateFrom > query.DateTo) throw TripErrors.FromAfterTo();
|
||||
var rows = await trips.DieselReportAsync(query, ct);
|
||||
var data = rows.Select((r, i) => (IReadOnlyList<object?>)
|
||||
[
|
||||
i + 1, r.Pn, r.DischargeAuthNo, r.Tn, r.MethodName, r.BalanceBefore, r.BalanceAfter, r.Amount,
|
||||
r.CreationDate?.ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture), r.FirstName,
|
||||
TripStatus.Captions.GetValueOrDefault(r.StatusCode ?? string.Empty, r.StatusCode ?? string.Empty)
|
||||
]).ToList();
|
||||
string[] headers =
|
||||
[
|
||||
"متسلسل", "رقم الارسالية", "رقم النموذج", "رقم القاطرة", "نوع الحركة", "الرصيد قبل", "الرصيد بعد", "القيمة",
|
||||
"تاريخ ووقت الحركة", "اسم المستخدم", "الحالة"
|
||||
];
|
||||
return Xlsx("refinery-diesel", new ExportTable(["شحن الديزل"], headers, data));
|
||||
}
|
||||
|
||||
public async Task<TripExportFile> CardsAsync(string? tn, CancellationToken ct)
|
||||
{
|
||||
var rows = await trips.CardsAsync(string.IsNullOrWhiteSpace(tn) ? null : tn.Trim(), ct);
|
||||
var data = rows.Select((r, i) => (IReadOnlyList<object?>)[i + 1, r.Tn, r.CardNumber, r.CurrentBalance]).ToList();
|
||||
string[] headers = ["متسلسل", "رقم القاطرة", "رقم بطاقة جوبترول", "القيمة التراكمية الحالية"];
|
||||
var filters = string.IsNullOrWhiteSpace(tn) ? [] : new List<(string Label, string Value)> { ("رقم القاطرة", tn.Trim()) };
|
||||
return Legacy("refinery-cards", CardsTitle, filters, headers, CardsWidths, data);
|
||||
}
|
||||
|
||||
public async Task<TripExportFile> BankAsync(BankReportQuery query, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(query.BankAccount)) throw TripErrors.NoBankAccount();
|
||||
if (query.PaymentedDateFrom > query.PaymentedDateTo) throw TripErrors.FromAfterTo();
|
||||
var rows = await trips.BankReportAsync(query, ct);
|
||||
var data = rows.Select((r, i) => (IReadOnlyList<object?>)
|
||||
[
|
||||
i + 1, r.Pn, r.DischargeAuthNo, r.Tn, r.OwnerName, r.BankName, r.Iban, r.BankAccount, r.NetWage,
|
||||
Day(r.PaymentedDate), TripStatus.Captions.GetValueOrDefault(r.StatusCode ?? string.Empty, r.StatusCode ?? string.Empty)
|
||||
]).ToList();
|
||||
string[] headers =
|
||||
[
|
||||
"متسلسل", "رقم الارسالية", "رقم النموذج", "رقم القاطرة", "صاحب الحساب", "البنك", "IBAN", "رقم الحساب",
|
||||
"صافي قيمة الصرف الفعلي", "تاريخ الدفع", "الحالة"
|
||||
];
|
||||
return Xlsx("refinery-bank", new ExportTable(["عطاء صرف نماذج النفط الخام"], headers, data));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,253 @@
|
|||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Refinery.Trips;
|
||||
|
||||
/// <summary>REFINERY_TRIPS.STATUS_CODE values used by the trip actions.</summary>
|
||||
public static class TripStatus
|
||||
{
|
||||
public const string Released = "RESD";
|
||||
public const string Loaded = "LOADED";
|
||||
public const string Discharged = "DISCHARGED";
|
||||
public const string PendingExchange = "PENDING_EXCHANGE";
|
||||
public const string ReadyToPay = "READY_TO_PAY";
|
||||
public const string Exchanged = "EXCHANGED";
|
||||
public const string Revoked = "RVKD";
|
||||
|
||||
/// <summary>Arabic captions REFINERYTRIP.STATUS.* / REFINERYTRIP.STATUSCODE.* (ntp.lt_caption).</summary>
|
||||
public static readonly IReadOnlyDictionary<string, string> Captions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["RESD"] = "تم التسريب",
|
||||
["LOADING_FILL"] = "تم التعبئة للتحميل",
|
||||
["LOADED"] = "تم التحميل",
|
||||
["DISCHARGING_FILL"] = "تم التعبئة للتفريغ",
|
||||
["ARRIVE_LOCATION"] = "وصول شويعر",
|
||||
["DISCHARGING"] = "قيد التفريغ",
|
||||
["DISCHARGED"] = "تم التفريغ",
|
||||
["PENDING_EXCHANGE"] = "قيد التدقيق للصرف",
|
||||
["READY_TO_PAY"] = "جاهز للدفع",
|
||||
["EXCHANGED"] = "تم الصرف",
|
||||
["COMPLETE"] = "مكتمل",
|
||||
["RVKD"] = "ملغى",
|
||||
};
|
||||
|
||||
/// <summary>The statuses in which the second advance value is shown on the trip form (factory getREFINERYTRIP 138).</summary>
|
||||
public static readonly string[] ShowSecondPayment =
|
||||
["LOADED", "DISCHARGING_FILL", "ARRIVE_LOCATION", "EXCHANGED", "DISCHARGING", "DISCHARGED", "READY_TO_PAY"];
|
||||
|
||||
/// <summary>Statuses for which getREFINERYTRIP recomputes the wage figures (factory 129).</summary>
|
||||
public static readonly string[] RecalculateAmounts = ["DISCHARGED", "READY_TO_PAY"];
|
||||
|
||||
/// <summary>calculateRemainigBalance refuses to run while a trip of the period is in one of these (factory 1289).</summary>
|
||||
public static readonly string[] BlockRepricing = ["READY_TO_PAY", "PENDING_EXCHANGE", "DISCHARGING", "LOADED", "RESD", "ARRIVE_LOCATION"];
|
||||
}
|
||||
|
||||
/// <summary>Legacy captions (ntp.lt_caption) of the refinery trip messages, kept verbatim. Codes without a caption in the database are marked.</summary>
|
||||
public static class TripErrors
|
||||
{
|
||||
public const string Ok = "تمت العملية بنجاح"; // PUBLIC.SUCCESSFUL.OPERATION
|
||||
|
||||
public static BusinessException FirstAdvanceExists() =>
|
||||
new("FIRST_ADVANCED_PAYMENT_IS_EXIST", "تم اجراء دفعة الديزل الاولى مسبقاً");
|
||||
|
||||
/// <summary>
|
||||
/// Caption ERROR.SECOND_ADVANCED_PAYMENT_IS_EXIST of the database reads "لا يوجد بطاقة ديزل معرفة" (copy/paste slip in the legacy table);
|
||||
/// the plain code SECOND_ADVANCED_PAYMENT_IS_EXIST carries the meaning the legacy code intended, which is used here.
|
||||
/// </summary>
|
||||
public static BusinessException SecondAdvanceExists() =>
|
||||
new("SECOND_ADVANCED_PAYMENT_IS_EXIST", "تم اجراء دفعة الديزل الثانية مسبقاً");
|
||||
|
||||
/// <summary>No caption exists for FIRST_ADVANCED_PAYMENT_REVERSE_IS_EXIST in the legacy database; wording is new.</summary>
|
||||
public static BusinessException FirstAdvanceReverseExists() =>
|
||||
new("FIRST_ADVANCED_PAYMENT_REVERSE_IS_EXIST", "تم إلغاء دفعة الديزل الأولى مسبقاً");
|
||||
|
||||
/// <summary>No caption exists for CANNOT_FIRST_ADVANCED_PAYMENT_REVERSE in the legacy database; wording is new.</summary>
|
||||
public static BusinessException CannotReverseAdvance() =>
|
||||
new("CANNOT_FIRST_ADVANCED_PAYMENT_REVERSE", "لا يمكن إلغاء دفعة الديزل");
|
||||
|
||||
public static BusinessException CardNotFound() =>
|
||||
new("THE_REFINERY_CARD_IS_NOT_EXIST", "بطاقة تعبئة الديزل غير معرفة");
|
||||
|
||||
public static BusinessException WrongLoadingDate() =>
|
||||
new("WRONG_LOADING_DATE", "السعر غير معرف لتاريخ التحميل");
|
||||
|
||||
/// <summary>Legacy code ERROR.REFINERY_PRICE_IS_NOT_DECALRE_FOR_THIS_PERIOD resolves to the plain caption of the same name.</summary>
|
||||
public static BusinessException PriceNotDeclared() =>
|
||||
new("REFINERY_PRICE_IS_NOT_DECALRE_FOR_THIS_PERIOD", "السعر غير معرف لتاريخ التحميل");
|
||||
|
||||
public static BusinessException NegativeAmount() =>
|
||||
new("PAYMENT_ISNOT_ALLOW_FOR_MINUS_AMOUNT", "الدفع مسموح للمبالغ اكبر من صفر");
|
||||
|
||||
public static BusinessException BigAmount(decimal max) =>
|
||||
new("PAYMENT_ISNOT_ALLOW_FOR_BIG_AMOUNT",
|
||||
"الدفع مسموح فقط للمبالغ اقل من " + max.ToString("0.###", CultureInfo.InvariantCulture) + " دينار");
|
||||
|
||||
public static BusinessException NoPaymentMethod() =>
|
||||
new("CANNOT_COMPLETE_ACTION_NO_PAYMENT_METHOD", "لا يمكن استكمال الاجراء بدون تحديد طريقه الدفع");
|
||||
|
||||
public static BusinessException ReloadForm() =>
|
||||
new("THERE_IS_EWALLET_PLEASE_RELOAD_FORM", "لا يمكن استكمال الاجراء ، يرجى اغلاق نموذج الارسالية واعاده فتحة مرة اخرى");
|
||||
|
||||
public static BusinessException WalletNumberEmpty() =>
|
||||
new("WALLET_NUMBER_IS_EMPTY", "لا يوجد رقم محفظة الكترونية");
|
||||
|
||||
public static BusinessException OwnerNnpnEmpty() =>
|
||||
new("OWNER_NNPN_IS_EMPTY", "لا يوجد رقم وطني لصاحب المحفظة الالكترونية لغاية الدفع");
|
||||
|
||||
public static BusinessException OwnerNameEmpty() =>
|
||||
new("REFINERY_OWNER_NNPN_WALLET_IS_EMPTY", "لا يوجد اسم لصاحب المحفظة الالكترونية لغاية الدفع");
|
||||
|
||||
/// <summary>Legacy answered ERROR.NO_AUTHORITY when the trip was not in a status the action allows from.</summary>
|
||||
public static BusinessException WrongStatus() =>
|
||||
new("NO_AUTHORITY", "ليس لديك صلاحية لاتمام هذه العملية");
|
||||
|
||||
public static BusinessException PaymentAlreadySent() =>
|
||||
new("PAYMENT_ALREADY_SENT", "لايمكن تفعيل الصرف, تم الصرف مسبقا");
|
||||
|
||||
/// <summary>No caption exists for ERROR_BACK_FROM_DINARAK in the legacy database; wording is new (legacy appended the Dinarak text after it).</summary>
|
||||
public static BusinessException DinarakRefused(string dinarakMessage) =>
|
||||
new("ERROR_BACK_FROM_DINARAK", "تعذر إتمام الحوالة عبر دينارك" + "\n" + dinarakMessage.ToUpperInvariant());
|
||||
|
||||
/// <summary>No caption exists for REFINERY_NO_FAILED_TRANSFER in the legacy database; wording is new.</summary>
|
||||
public static BusinessException NoFailedTransfer() =>
|
||||
new("REFINERY_NO_FAILED_TRANSFER", "لا توجد حوالة مسجلة لهذه الارسالية");
|
||||
|
||||
/// <summary>New: legacy continued when the Dinarak status lookup failed (risk of paying twice); this port refuses.</summary>
|
||||
public static BusinessException DinarakStatusUnknown() =>
|
||||
new("DINARAK_STATUS_UNKNOWN", "تعذر التحقق من حالة الحوالة لدى دينارك، حاول لاحقاً");
|
||||
|
||||
public static BusinessException NoTripsInPeriod() =>
|
||||
new("THERE_IS_NO_ANY_TRIP_IN_THIS_PERIOD", "لا يوجد ارساليات ضمن هذه الفترة");
|
||||
|
||||
public static BusinessException NotAllExchanged() =>
|
||||
new("NO_TON_PRICE_EDIT_NOT_ALL_TRIPS_EXCHANGED", "لا يمكن اعادة تسعير سعر النفط ، يجب ان تكون جميع الارساليات ضمن الفترة مسددة");
|
||||
|
||||
public static BusinessException FromAfterTo() =>
|
||||
new("FROM_CAN_NOT_GREATER_THAN_TO", "لا يجوز ان يكون تاريخ من أكبر من تارخ الى");
|
||||
|
||||
public static BusinessException NoBankAccount() =>
|
||||
new("NO_BANK_ACCOUNT", "يجب ادخال رقم الحساب");
|
||||
}
|
||||
|
||||
/// <summary>Rules shared by the payment actions (refinerytripfactory.cfc exchange / PAYMENT / CACH_PAYMENT).</summary>
|
||||
public static class TripPaymentRules
|
||||
{
|
||||
/// <summary>
|
||||
/// 0 = no price for the loading date, negative = nothing to pay, above <paramref name="max"/> = too big
|
||||
/// (legacy application.REFINERY_MAX_PAYMENT_AMOUNT, caption says 500 dinars). <paramref name="checkSign"/> false = ORANGE_PAYMENT (zero check only).
|
||||
/// </summary>
|
||||
public static void EnsurePayable(decimal netWage, decimal max, bool checkSign = true)
|
||||
{
|
||||
if (netWage == 0) throw TripErrors.PriceNotDeclared();
|
||||
if (!checkSign) return;
|
||||
if (netWage < 0) throw TripErrors.NegativeAmount();
|
||||
if (netWage > max) throw TripErrors.BigAmount(max);
|
||||
}
|
||||
|
||||
/// <summary>Wallet checks before a wallet payment (exchange / cash / orange): <paramref name="epayment"/> must be 1.</summary>
|
||||
public static void EnsureWalletReady(bool walletExists, int? epayment, string? walletNumber, string? ownerNnpn, string? ownerName)
|
||||
{
|
||||
if (!walletExists) throw TripErrors.NoPaymentMethod();
|
||||
if (epayment == 0) throw TripErrors.ReloadForm();
|
||||
if (string.IsNullOrEmpty(walletNumber)) throw TripErrors.WalletNumberEmpty();
|
||||
if (string.IsNullOrEmpty(ownerNnpn)) throw TripErrors.OwnerNnpnEmpty();
|
||||
if (string.IsNullOrEmpty(ownerName)) throw TripErrors.OwnerNameEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the OLD_DATA / NEW_DATA JSON of REFINERY_TRIPS_LOG like legacy logs.saveLog: only the fields passed as arguments that exist on the
|
||||
/// trip record and whose value changed; STATUS_CODE and REMARKS are stored as Arabic captions. PRINT stores the arguments as they are.
|
||||
/// </summary>
|
||||
public static class TripLogBuilder
|
||||
{
|
||||
private static readonly JsonSerializerOptions Json = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
|
||||
|
||||
public static string? RemarksCaption(string? code) => code switch
|
||||
{
|
||||
"SUCCESSFULL_EXCHANGE_OPERATION" => "تمت عملية الصرف بنجاح", // caption SUCCESSFULL_EXCHANGE_OPERATION
|
||||
_ => code
|
||||
};
|
||||
|
||||
private static string Caption(string key, object? v)
|
||||
{
|
||||
var s = Text(v);
|
||||
return key switch
|
||||
{
|
||||
"STATUS_CODE" => TripStatus.Captions.TryGetValue(s, out var c) ? c : s,
|
||||
"REMARKS" => RemarksCaption(s) ?? string.Empty,
|
||||
_ => s
|
||||
};
|
||||
}
|
||||
|
||||
private static string Text(object? v) => v switch
|
||||
{
|
||||
null => string.Empty,
|
||||
decimal d => d.ToString("0.#########", CultureInfo.InvariantCulture),
|
||||
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
|
||||
_ => v.ToString() ?? string.Empty
|
||||
};
|
||||
|
||||
private static bool Same(object? a, object? b)
|
||||
{
|
||||
if (decimal.TryParse(Text(a), NumberStyles.Any, CultureInfo.InvariantCulture, out var x) &&
|
||||
decimal.TryParse(Text(b), NumberStyles.Any, CultureInfo.InvariantCulture, out var y)) return x == y;
|
||||
return string.Equals(Text(a), Text(b), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <param name="oldValue">Current value of a trip column (view column name, upper case) or null when the record has no such column.</param>
|
||||
/// <param name="args">New values by upper-case column name.</param>
|
||||
public static (string OldJson, string NewJson)? Build(string methodName, Func<string, (bool Exists, object? Value)> oldValue,
|
||||
IReadOnlyDictionary<string, object?> args)
|
||||
{
|
||||
if (methodName.Equals("PRINT", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var all = args.ToDictionary(a => a.Key, a => Text(a.Value));
|
||||
return all.Count == 0 ? null : ("{}", JsonSerializer.Serialize(all, Json));
|
||||
}
|
||||
|
||||
var oldD = new Dictionary<string, string>();
|
||||
var newD = new Dictionary<string, string>();
|
||||
foreach (var (key, value) in args)
|
||||
{
|
||||
var (exists, old) = oldValue(key);
|
||||
if (!exists || Same(old, value)) continue;
|
||||
oldD[key] = Caption(key, old);
|
||||
newD[key] = Caption(key, value);
|
||||
}
|
||||
return newD.Count == 0 ? null : (JsonSerializer.Serialize(oldD, Json), JsonSerializer.Serialize(newD, Json));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Which action buttons the trip form offers (legacy getREFINERYTRIP ACTIONS / REVERSE_ACTIONS + REFINERYTRIP.js status switch). The caller still needs the permission key.</summary>
|
||||
public static class TripActionRules
|
||||
{
|
||||
public static IReadOnlyList<string> Available(string status, int dieselCharge, int? epayment, bool auditMode, bool hasTransferLog)
|
||||
{
|
||||
var list = new List<string>();
|
||||
if (dieselCharge == 0 && status != TripStatus.Revoked) list.Add("firstAdvance");
|
||||
if (dieselCharge == 1 && status != TripStatus.Released) list.Add("secondAdvance");
|
||||
if (dieselCharge == 1) list.Add("firstAdvanceReverse");
|
||||
if (dieselCharge == 2) list.Add("secondAdvanceReverse");
|
||||
|
||||
if (status == TripStatus.Discharged)
|
||||
{
|
||||
if (epayment == 1)
|
||||
{
|
||||
list.Add(auditMode ? "exchangeAudit" : "exchange");
|
||||
list.Add("cashPayment");
|
||||
}
|
||||
else list.Add("receipt");
|
||||
list.Add("print");
|
||||
}
|
||||
if (status == TripStatus.PendingExchange && epayment == 1) list.Add("exchange");
|
||||
if ((status is TripStatus.Discharged or TripStatus.PendingExchange) && epayment == 1)
|
||||
{
|
||||
list.Add("activateWalletExchange");
|
||||
if (hasTransferLog) list.Add("confirmExchange");
|
||||
}
|
||||
if (status == TripStatus.ReadyToPay) list.Add("payment");
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,272 @@
|
|||
namespace NTP.Application.Refinery.Trips;
|
||||
|
||||
/// <summary>Envelope of write operations: <c>message</c> is the legacy Arabic success text (toasted by the client).</summary>
|
||||
public sealed record TripsResult(string Message, long? Id = null);
|
||||
|
||||
// ---------------------------------------------------------------- filters
|
||||
/// <summary>
|
||||
/// Grid / report filters (legacy factoryweb.search whitelist, mapped on REFINERY_TRIPS_VIEW). <c>StatusCode</c> and
|
||||
/// <c>PaymentMethodCode</c> accept a comma separated list (multi-select). Dates are days (yyyy-MM-dd).
|
||||
/// </summary>
|
||||
public sealed record TripQuery(
|
||||
string? Pn = null,
|
||||
string? Tn = null,
|
||||
string? Trn = null,
|
||||
string? Nnpn = null,
|
||||
string? LoadingNo = null,
|
||||
string? DischargeAuthNo = null,
|
||||
DateTime? DispatchDate = null,
|
||||
DateTime? DischargeEntryDate = null,
|
||||
DateTime? LoadingDateFrom = null,
|
||||
DateTime? LoadingDateTo = null,
|
||||
DateTime? PaymentedDateFrom = null,
|
||||
DateTime? PaymentedDateTo = null,
|
||||
string? StatusCode = null,
|
||||
string? PaymentMethodCode = null,
|
||||
string? HasWageClaim = null,
|
||||
string? HavePaymentMethod = null,
|
||||
string? DieselCharge = null,
|
||||
string? WageClaimNo = null,
|
||||
long? WageClaimId = null,
|
||||
string? BankAccount = null,
|
||||
string? WaterExist = null,
|
||||
long? Id = null);
|
||||
|
||||
// ---------------------------------------------------------------- grid
|
||||
/// <summary>One grid row. The icons of the legacy action column derive from DieselCharge / HavePaymentMethod / WaterAmount / ReversePayment.</summary>
|
||||
public sealed class TripRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Pn { get; set; }
|
||||
public string? DispatchDate { get; set; }
|
||||
public long? LoadingNo { get; set; }
|
||||
public string? DischargeAuthNo { get; set; }
|
||||
public string? DischargeEntryDate { get; set; }
|
||||
public string? Tn { get; set; }
|
||||
public string? Trn { get; set; }
|
||||
public string? Nnpn { get; set; }
|
||||
public long? WageClaimId { get; set; }
|
||||
public long? WageClaimNo { get; set; }
|
||||
public string? StatusCode { get; set; }
|
||||
public int DieselCharge { get; set; }
|
||||
public string? HavePaymentMethod { get; set; }
|
||||
public decimal? WaterAmount { get; set; }
|
||||
public int? ReversePayment { get; set; }
|
||||
public decimal? NetWage { get; set; }
|
||||
}
|
||||
|
||||
public sealed record TripGridDto(
|
||||
long Id, string? Pn, string? DispatchDate, long? LoadingNo, string? DischargeAuthNo, string? DischargeEntryDate,
|
||||
string? Tn, string? Trn, string? Nnpn, long? WageClaimId, long? WageClaimNo, string? StatusCode,
|
||||
int DieselCharge, bool HasPaymentMethod, bool HasWater, bool Reversed, decimal? NetWage);
|
||||
|
||||
// ---------------------------------------------------------------- one trip
|
||||
/// <summary>Raw row of REFINERY_TRIPS_VIEW for the form and the actions.</summary>
|
||||
public sealed class TripRecord
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Pn { get; set; }
|
||||
public string? StatusCode { get; set; }
|
||||
public string? DispatchDate { get; set; }
|
||||
public string? ActualLoadingDate { get; set; }
|
||||
public DateTime? LoadingDate { get; set; }
|
||||
public string? ClientName { get; set; }
|
||||
public string? Tn { get; set; }
|
||||
public string? Trn { get; set; }
|
||||
public string? Nnpn { get; set; }
|
||||
public string? Drvr { get; set; }
|
||||
public long? LoadingNo { get; set; }
|
||||
public decimal? GrossWeight { get; set; }
|
||||
public decimal? EmptyWeight { get; set; }
|
||||
public decimal? NetLoadingWeight { get; set; }
|
||||
public decimal? LitersWeight { get; set; }
|
||||
public string? DischargeAuthNo { get; set; }
|
||||
public string? DischargeEntryDate { 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; }
|
||||
public decimal? WeightDifference { get; set; }
|
||||
public decimal? NetWage { get; set; }
|
||||
public decimal? TripNetWage { get; set; }
|
||||
public decimal? RemainingBalance { get; set; }
|
||||
public int DieselCharge { get; set; }
|
||||
public int? ReversePayment { get; set; }
|
||||
public decimal? FirstAdvancePayment { get; set; }
|
||||
public decimal? SecondAdvancePayment { get; set; }
|
||||
public decimal? PenaltyAmount { get; set; }
|
||||
public decimal? PenaltyQuantity { get; set; }
|
||||
public string? HavePaymentMethod { get; set; }
|
||||
public string? DriverWalletNumber { get; set; }
|
||||
public long? WageClaimId { get; set; }
|
||||
public long? WageClaimNo { get; set; }
|
||||
public string? CardNumber { get; set; }
|
||||
public decimal? CurrentBalance { get; set; }
|
||||
public long? RefineryWalletId { get; set; }
|
||||
public decimal? DinarakReferenceId { get; set; }
|
||||
public string? Remarks { get; set; }
|
||||
public string? ReceivedByName { get; set; }
|
||||
public DateTime? ReceivedDate { get; set; }
|
||||
public DateTime? PaymentedDate { get; set; }
|
||||
public string? PaymentOptions { get; set; }
|
||||
public long? VoucherSerialNumber { get; set; }
|
||||
public string? PaidEpayment { get; set; }
|
||||
public string? PaymentMethod { get; set; }
|
||||
public string? OwnerName { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Active REFINERY_WALLET of the truck (legacy checkEWallet) or the wallet the trip was paid to.</summary>
|
||||
public sealed class TripWallet
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public int? Epayment { get; set; }
|
||||
public string? WalletNumber { get; set; }
|
||||
public long? OwnerNnpn { get; set; }
|
||||
public string? OwnerName { get; set; }
|
||||
public string? DriverName { get; set; }
|
||||
public long? DriverNnpn { get; set; }
|
||||
public string? BankAccount { get; set; }
|
||||
public string? Iban { get; set; }
|
||||
public string? BankName { get; set; }
|
||||
}
|
||||
|
||||
public sealed record TripWalletDto(
|
||||
int? Epayment, string? WalletNumber, string? OwnerNnpn, string? OwnerName, string? BankAccount, string? Iban, string? BankName,
|
||||
string? DriverWalletNumber);
|
||||
|
||||
public sealed record TripDetailDto(
|
||||
long Id,
|
||||
string? Pn,
|
||||
string? StatusCode,
|
||||
string? DispatchDate,
|
||||
string? ActualLoadingDate,
|
||||
string? ClientName,
|
||||
string? Tn,
|
||||
string? Trn,
|
||||
string? Nnpn,
|
||||
string? DriverName,
|
||||
long? LoadingNo,
|
||||
decimal? GrossWeight,
|
||||
decimal? EmptyWeight,
|
||||
decimal? NetLoadingWeight,
|
||||
decimal? LitersWeight,
|
||||
string? DischargeAuthNo,
|
||||
string? DischargeEntryDate,
|
||||
decimal? ActualGrossWeight,
|
||||
decimal? ActualEmptyWeight,
|
||||
decimal? NetDischargeWeight,
|
||||
decimal? WaterAmount,
|
||||
decimal? SedimentAmount,
|
||||
decimal? WeightDifference,
|
||||
decimal? NetWage,
|
||||
decimal? TripNetWage,
|
||||
decimal? RemainingBalance,
|
||||
int DieselCharge,
|
||||
bool Reversed,
|
||||
string? CardNumber,
|
||||
decimal? CurrentBalance,
|
||||
decimal? NewBalance,
|
||||
decimal? FirstPaymentValue,
|
||||
decimal? SecondPaymentValue,
|
||||
long? WageClaimId,
|
||||
long? WageClaimNo,
|
||||
string? Remarks,
|
||||
string? ReceivedByName,
|
||||
string? ReceivedDate,
|
||||
string? PaymentedDate,
|
||||
string? PaymentOptions,
|
||||
long? VoucherSerialNumber,
|
||||
bool AuditMode,
|
||||
TripWalletDto? Wallet,
|
||||
IReadOnlyList<string> Actions);
|
||||
|
||||
// ---------------------------------------------------------------- log
|
||||
public sealed class TripLogRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? MethodName { get; set; }
|
||||
public string? LogDate { get; set; }
|
||||
public string? Login { get; set; }
|
||||
public string? OldData { get; set; }
|
||||
public string? NewData { get; set; }
|
||||
}
|
||||
|
||||
public sealed record TripLogDto(long Id, string? MethodName, string? LogDate, string? Login, string? OldData, string? NewData);
|
||||
|
||||
// ---------------------------------------------------------------- print
|
||||
/// <summary>Cash voucher "سند صرف نقدي" (legacy print): the page prints it, the serial is stored on the trip.</summary>
|
||||
public sealed record TripVoucherDto(
|
||||
long Id, string Pn, string Serial, string Date, decimal Amount, string? DischargeAuthNo, string? OwnerName);
|
||||
|
||||
// ---------------------------------------------------------------- reports
|
||||
public sealed record DieselReportQuery(
|
||||
string? Pn = null, string? Tn = null, string? StatusCode = null, string? DischargeAuthNo = null, string? DieselCharge = null,
|
||||
DateTime? DateFrom = null, DateTime? DateTo = null);
|
||||
|
||||
public sealed class DieselReportRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Pn { get; set; }
|
||||
public string? Tn { get; set; }
|
||||
public string? StatusCode { get; set; }
|
||||
public string? DischargeAuthNo { get; set; }
|
||||
public DateTime? CreationDate { get; set; }
|
||||
public string? FirstName { get; set; }
|
||||
public string? MethodName { get; set; }
|
||||
public decimal? BalanceBefore { get; set; }
|
||||
public decimal? BalanceAfter { get; set; }
|
||||
public decimal? Amount { get; set; }
|
||||
}
|
||||
|
||||
public sealed class CardRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long Tn { get; set; }
|
||||
public string? CardNumber { get; set; }
|
||||
public decimal? CurrentBalance { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Row of the trips excel report (legacy report(), manager column set).</summary>
|
||||
public sealed class TripReportRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Pn { get; set; }
|
||||
public string? DispatchDate { get; set; }
|
||||
public long? LoadingNo { get; set; }
|
||||
public string? DischargeAuthNo { get; set; }
|
||||
public string? DischargeEntryDate { get; set; }
|
||||
public decimal? NetLoadingWeight { get; set; }
|
||||
public decimal? NetDischargeWeight { get; set; }
|
||||
public string? Tn { get; set; }
|
||||
public string? Trn { get; set; }
|
||||
public string? Nnpn { get; set; }
|
||||
public decimal? CurrentBalance { get; set; }
|
||||
public int DieselCharge { get; set; }
|
||||
public decimal? NetWage { get; set; }
|
||||
public decimal? TripNetWage { get; set; }
|
||||
public decimal? RemainingBalance { get; set; }
|
||||
public string? StatusCode { get; set; }
|
||||
public long? WageClaimNo { get; set; }
|
||||
public DateTime? PaymentedDate { get; set; }
|
||||
public DateTime? ReceivedDate { get; set; }
|
||||
public string? ReceivedByName { get; set; }
|
||||
public string? ActualLoadingDate { get; set; }
|
||||
public string? PaymentMethod { get; set; }
|
||||
public string? PaidEpayment { get; set; }
|
||||
public string? PaymentOptions { get; set; }
|
||||
public string? OwnerName { get; set; }
|
||||
public string? OwnerNameEnglish { get; set; }
|
||||
public string? BankName { get; set; }
|
||||
public string? Iban { get; set; }
|
||||
public string? BankAccount { get; set; }
|
||||
public string? WalletNumber { get; set; }
|
||||
public long? OwnerNnpn { get; set; }
|
||||
}
|
||||
|
||||
public sealed record BankReportQuery(string? BankAccount, string? StatusCode, string? HasWageClaim, DateTime? PaymentedDateFrom, DateTime? PaymentedDateTo);
|
||||
|
||||
public sealed record RecalculateBalanceRequest(DateTime StartDate, DateTime EndDate, long VariableGroupId);
|
||||
|
||||
/// <summary>Result of an export: file content, name and content type.</summary>
|
||||
public sealed record TripExportFile(byte[] Content, string FileName, string ContentType);
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Refinery.Trips;
|
||||
|
||||
/// <summary>Configuration of the trips slice (section "Refinery:Trips").</summary>
|
||||
public sealed class TripOptions
|
||||
{
|
||||
public const string SectionName = "Refinery:Trips";
|
||||
|
||||
/// <summary>
|
||||
/// Largest net wage a payment action accepts (legacy application.REFINERY_MAX_PAYMENT_AMOUNT, defined outside the repository;
|
||||
/// the caption ERROR.PAYMENT_ISNOT_ALLOW_FOR_BIG_AMOUNT says 500 dinars). UNVERIFIED default.
|
||||
/// </summary>
|
||||
public decimal MaxPaymentAmount { get; set; } = 500m;
|
||||
}
|
||||
|
||||
/// <summary>Reads <see cref="TripOptions"/> (Application has no Options package; implemented in Infrastructure).</summary>
|
||||
public interface ITripSettingsService
|
||||
{
|
||||
TripOptions Value { get; }
|
||||
}
|
||||
|
||||
public sealed record TripLock(string? StatusCode, int DieselCharge);
|
||||
|
||||
public sealed record CardInfo(long Id, decimal CurrentBalance);
|
||||
|
||||
/// <summary>Data access of the refinery trips (REFINERY_TRIPS and its view, cards, logs, DB functions).</summary>
|
||||
public interface ITripRepository
|
||||
{
|
||||
// ---- reads
|
||||
Task<PagedResult<TripRow>> SearchAsync(TripQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<TripRecord?> GetAsync(long id, CancellationToken ct = default);
|
||||
/// <summary>SELECT ... FOR UPDATE of the trip (inside a transaction): serialises two operators acting on the same trip.</summary>
|
||||
Task<TripLock?> LockAsync(long id, CancellationToken ct = default);
|
||||
Task<TripWallet?> GetActiveWalletByTruckAsync(string tn, CancellationToken ct = default);
|
||||
Task<TripWallet?> GetWalletAsync(long walletId, CancellationToken ct = default);
|
||||
/// <summary>REFINERY_VARIABLES AUTDIT_MODE = 1 (legacy checkAuditMode).</summary>
|
||||
Task<bool> GetAuditModeAsync(CancellationToken ct = default);
|
||||
/// <summary>FIRST_ADVANCE_PAYMENT valid today (legacy getFirstPaymentValue).</summary>
|
||||
Task<decimal?> GetFirstPaymentValueAsync(CancellationToken ct = default);
|
||||
/// <summary>All KEY_NAME / KEY_VALUE of the variables valid on the (truncated) loading date.</summary>
|
||||
Task<IReadOnlyList<KeyValuePair<string, string?>>> GetVariablesAsync(DateTime loadingDate, CancellationToken ct = default);
|
||||
/// <summary>WATER_FLAG of the trip, or null when the column does not exist yet in this database / is empty.</summary>
|
||||
Task<int?> GetWaterFlagAsync(long id, CancellationToken ct = default);
|
||||
/// <summary>CalculateRefinaryDiesel(id); null when the function finds no price (ORA-01403).</summary>
|
||||
Task<decimal?> CalculateDieselAsync(long id, CancellationToken ct = default);
|
||||
/// <summary>CalculateRefinaryAmount(id); null when the function finds no price (ORA-01403).</summary>
|
||||
Task<decimal?> CalculateAmountAsync(long id, CancellationToken ct = default);
|
||||
Task<bool> HasTransferLogAsync(long id, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<TripRecord>> GetTripsOfPeriodAsync(DateTime from, DateTime to, CancellationToken ct = default);
|
||||
|
||||
// ---- diesel cards
|
||||
Task<CardInfo?> GetActiveCardAsync(string tn, CancellationToken ct = default);
|
||||
Task<decimal?> GetLastCardLogAmountAsync(string pn, string methodName, CancellationToken ct = default);
|
||||
Task InsertCardLogAsync(long cardId, string methodName, decimal before, decimal after, decimal amount, string userId, string pn, CancellationToken ct = default);
|
||||
Task UpdateCardBalanceAsync(long cardId, decimal balance, string userId, long tripId, CancellationToken ct = default);
|
||||
|
||||
// ---- writes on the trip
|
||||
Task MarkFirstAdvanceAsync(long id, string userId, CancellationToken ct = default);
|
||||
Task MarkSecondAdvanceAsync(long id, string userId, decimal secondPaymentValue, CancellationToken ct = default);
|
||||
Task MarkAdvanceReversedAsync(long id, string userId, int dieselCharge, CancellationToken ct = default);
|
||||
/// <summary>Legacy NetWageAmount: stores the computed figures on the trip.</summary>
|
||||
Task SaveAmountsAsync(long id, string userId, TripAmounts amounts, CancellationToken ct = default);
|
||||
/// <summary>RECEIPT (READY_TO_PAY) and EXCHANGE_AUDIT (PENDING_EXCHANGE): new status + received by / date.</summary>
|
||||
Task SetStatusReceivedAsync(long id, string userId, string status, CancellationToken ct = default);
|
||||
/// <summary>Status EXCHANGED. <paramref name="setReceived"/> also fills RECEIVED_BY/DATE (not done by the bank-transfer PAYMENT).</summary>
|
||||
Task MarkExchangedAsync(long id, string userId, string? remarks, string? paymentOptions, bool setReceived, long? walletId, CancellationToken ct = default);
|
||||
Task<decimal> BumpDinarakReferenceAsync(long id, string userId, CancellationToken ct = default);
|
||||
Task SetVoucherSerialAsync(long id, long serial, CancellationToken ct = default);
|
||||
/// <summary>Legacy DAO.CONFIRM_EXCHANGE: EXCHANGED with wallet / user / date taken from the last Dinarak log and EXCHANGE log rows.</summary>
|
||||
Task ConfirmExchangeAsync(long id, string userId, CancellationToken ct = default);
|
||||
|
||||
// ---- history
|
||||
Task InsertLogAsync(long tripId, string methodName, string userId, string oldJson, string newJson, CancellationToken ct = default);
|
||||
Task<PagedResult<TripLogRow>> SearchLogAsync(long tripId, PageRequest page, CancellationToken ct = default);
|
||||
|
||||
// ---- reports
|
||||
Task<IReadOnlyList<TripReportRow>> ReportAsync(TripQuery query, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<DieselReportRow>> DieselReportAsync(DieselReportQuery query, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<CardRow>> CardsAsync(string? tn, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<TripReportRow>> BankReportAsync(BankReportQuery query, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Voucher serial of the cash voucher (NTP.SYSTEM_VARIABLES VOUCHER_SERIAL_NO, legacy GenerateSerialNumber('VOUCHER')). NTP-schema connection.</summary>
|
||||
public interface IVoucherSerialRepository
|
||||
{
|
||||
/// <summary>Takes the next number (locks the row until commit) and returns <c>{yyyy}{seq:00000}</c> as a number.</summary>
|
||||
Task<long> NextAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Refinery.Variables;
|
||||
|
||||
public interface IVariablesRepository
|
||||
{
|
||||
/// <summary>Pricing periods, newest group first (legacy sort GROUP_ID DESC).</summary>
|
||||
Task<PagedResult<VariablesSetRow>> SearchAsync(VariablesQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<VariablesSetRow?> GetAsync(long groupId, CancellationToken ct = default);
|
||||
/// <summary>Periods of every group (AUTDIT_MODE ignored), optionally without one group.</summary>
|
||||
Task<IReadOnlyList<VariablesPeriod>> GetPeriodsAsync(long? excludeGroupId, CancellationToken ct = default);
|
||||
/// <summary>Any REFINERY_TRIPS row loaded (ACTUAL_LOADING_DATE) inside the period.</summary>
|
||||
Task<bool> HasTripsAsync(DateTime start, DateTime end, CancellationToken ct = default);
|
||||
Task<TripsOfPeriodInfo> GetTripsOfPeriodAsync(DateTime start, DateTime end, CancellationToken ct = default);
|
||||
Task<long> NextGroupIdAsync(CancellationToken ct = default);
|
||||
Task InsertSetAsync(long groupId, DateOnly start, DateOnly end, IReadOnlyDictionary<string, string> values, string createdBy, CancellationToken ct = default);
|
||||
Task UpdateSetAsync(long groupId, DateOnly start, DateOnly end, IReadOnlyDictionary<string, string> values, string updatedBy, CancellationToken ct = default);
|
||||
/// <summary>Writes TON_PRICE_CORRECTION = value and TON_PRICE_CORRECTION_SET = 1 (rows are inserted when missing).</summary>
|
||||
Task SetTonPriceCorrectionAsync(long groupId, string value, DateTime start, DateTime end, string userId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RemainingBalanceRow>> GetRemainingBalancesAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IVariablesService
|
||||
{
|
||||
Task<PagedResult<VariablesSetRow>> SearchAsync(VariablesQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<VariablesSetDetail> GetAsync(long groupId, CancellationToken ct);
|
||||
Task<VariablesResult> CreateAsync(SaveVariablesRequest request, CancellationToken ct);
|
||||
Task<VariablesResult> UpdateAsync(long groupId, SaveVariablesRequest request, CancellationToken ct);
|
||||
Task<VariablesResult> SetTonPriceCorrectionAsync(long groupId, TonPriceCorrectionRequest request, CancellationToken ct);
|
||||
Task<ExportFile> ExportAsync(VariablesQuery query, CancellationToken ct);
|
||||
Task<ExportFile> ExportRemainingBalanceAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Step of UPDATE_TON_PRICE_CORRECTION that recalculates the previous balances of the trucks of a period
|
||||
/// (legacy refinerytripFactory.calculateRemainigBalance). Throws <see cref="BusinessException"/> when it must stop the action.
|
||||
/// The calculation of the trip amounts belongs to the trips module: see <c>TonPriceRecalculationService</c>.
|
||||
/// </summary>
|
||||
public interface ITonPriceRecalculationService
|
||||
{
|
||||
Task RecalculateAsync(long groupId, DateTime start, DateTime end, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
using NTP.Application.Refinery.RemainingBalance;
|
||||
|
||||
namespace NTP.Application.Refinery.Variables;
|
||||
|
||||
/// <summary>
|
||||
/// Recalculation after the actual ton price (TON_PRICE_CORRECTION) is set: legacy UPDATE_TON_PRICE_CORRECTION calls
|
||||
/// refinerytripFactory.calculateRemainigBalance (refinerytripfactory.cfc:1269). That port lives in the trips module
|
||||
/// (<see cref="IRemainingBalanceService.RecalculateForPeriodAsync"/>: trips must exist and be exchanged, the net wage difference of every
|
||||
/// penalised trip goes to the truck's remaining balance). It joins the caller's transaction (DbSession nesting), so a failure rolls back the
|
||||
/// correction rows too (legacy reset them to 0 instead).
|
||||
/// </summary>
|
||||
public sealed class TonPriceRecalculationService(IRemainingBalanceService balances) : ITonPriceRecalculationService
|
||||
{
|
||||
public async Task RecalculateAsync(long groupId, DateTime start, DateTime end, CancellationToken ct = default) =>
|
||||
await balances.RecalculateForPeriodAsync(start, end, groupId, ct);
|
||||
}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
namespace NTP.Application.Refinery.Variables;
|
||||
|
||||
/// <summary>
|
||||
/// One pricing period ("variables set"): the rows of REFINERY_VARIABLES that share a GROUP_ID, pivoted like the legacy
|
||||
/// REFINERY_VARIABLES_VIEW (plus the ton price correction, which the view leaves out). Class with settable properties (Dapper + Oracle NUMBER).
|
||||
/// </summary>
|
||||
public class VariablesSetRow
|
||||
{
|
||||
public long GroupId { get; set; }
|
||||
public DateTime? StartDate { get; set; }
|
||||
public DateTime? EndDate { get; set; }
|
||||
public decimal? DieselLiterPrice { get; set; }
|
||||
public decimal? TonWage { get; set; }
|
||||
public decimal? TonPrice { get; set; }
|
||||
public decimal? DriverTip { get; set; }
|
||||
public decimal? PermitDispatch { get; set; }
|
||||
public decimal? WaybillFee { get; set; }
|
||||
public decimal? Commission { get; set; }
|
||||
public decimal? TolerancePercentage { get; set; }
|
||||
public decimal? FirstAdvancePayment { get; set; }
|
||||
/// <summary>TON_PRICE_CORRECTION (actual ton price), null when never set.</summary>
|
||||
public decimal? TonPriceCorrection { get; set; }
|
||||
/// <summary>TON_PRICE_CORRECTION_SET = 1: the correction was applied, it cannot be set again (legacy ERROR.YOU_CANNOT_RESET_TON_PRICE).</summary>
|
||||
public bool TonPriceCorrectionSet { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Detail of one period: the row plus what the caller may still do with it.</summary>
|
||||
public sealed class VariablesSetDetail : VariablesSetRow
|
||||
{
|
||||
/// <summary>No trip was loaded inside the period (legacy getrefinery_variables sets ACTIONS = UPDATE).</summary>
|
||||
public bool CanUpdate { get; set; }
|
||||
/// <summary>The ton price correction was not applied yet.</summary>
|
||||
public bool CanSetTonPriceCorrection { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Period of a set (legacy overlap checks).</summary>
|
||||
public sealed record VariablesPeriod(long GroupId, DateTime Start, DateTime End);
|
||||
|
||||
/// <summary>Grid filters (legacy START_DATE_STRING / END_DATE_STRING of the search form).</summary>
|
||||
/// <param name="StartDate">Both dates: periods starting inside [StartDate, EndDate]. Only this: periods starting on this day.</param>
|
||||
/// <param name="EndDate">Only this: periods ending on this day.</param>
|
||||
public sealed record VariablesQuery(DateOnly? StartDate, DateOnly? EndDate);
|
||||
|
||||
/// <summary>Body of create / update. Dates as yyyy-MM-dd.</summary>
|
||||
public sealed class SaveVariablesRequest
|
||||
{
|
||||
public DateOnly StartDate { get; set; }
|
||||
public DateOnly EndDate { get; set; }
|
||||
public decimal DieselLiterPrice { get; set; }
|
||||
public decimal FirstAdvancePayment { get; set; }
|
||||
public decimal TonWage { get; set; }
|
||||
public decimal TonPrice { get; set; }
|
||||
public decimal DriverTip { get; set; }
|
||||
public decimal PermitDispatch { get; set; }
|
||||
public decimal WaybillFee { get; set; }
|
||||
public decimal Commission { get; set; }
|
||||
public decimal TolerancePercentage { get; set; }
|
||||
}
|
||||
|
||||
public sealed class TonPriceCorrectionRequest
|
||||
{
|
||||
public decimal TonPriceCorrection { get; set; }
|
||||
}
|
||||
|
||||
public sealed record VariablesResult(string Message, long? Id = null);
|
||||
|
||||
/// <summary>What the ton price recalculation needs to know about the trips of a period (legacy refinerytripFactory.calculateRemainigBalance).</summary>
|
||||
public sealed class TripsOfPeriodInfo
|
||||
{
|
||||
public long TripCount { get; set; }
|
||||
/// <summary>Trips still in READY_TO_PAY, PENDING_EXCHANGE, DISCHARGING, LOADED, RESD or ARRIVE_LOCATION.</summary>
|
||||
public long NotExchangedCount { get; set; }
|
||||
/// <summary>Trips with PENALTY_AMOUNT > 0: the only ones whose balance is recalculated.</summary>
|
||||
public long PenaltyTripCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Row of REFINERY_REMAINING_BALANCE (previous balances per truck).</summary>
|
||||
public sealed class RemainingBalanceRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long Tn { get; set; }
|
||||
public decimal RemainingBalance { get; set; }
|
||||
}
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
using System.Globalization;
|
||||
|
||||
namespace NTP.Application.Refinery.Variables;
|
||||
|
||||
/// <summary>User-facing texts (legacy captions, verbatim; the ones marked * have no row in LT_CAPTION and are new wording).</summary>
|
||||
public static class VariablesMessages
|
||||
{
|
||||
public const string DateOverlap = "يوجد تداخل في فترة التسعير"; // ERROR.DATE_IS_EXIT_IN_PREVIOUS_PERIOD
|
||||
public const string StartDateInPreviousPeriod = "تاريخ بداية فترة التسعير يقع ضمن فترة تسعير سابقة"; // * ERROR.START_DATE_IS_EXIT_IN_PREVIOUS_PERIOD
|
||||
public const string EndDateInPreviousPeriod = "تاريخ نهاية فترة التسعير يقع ضمن فترة تسعير سابقة"; // * ERROR.END_DATE_IS_EXIT_IN_PREVIOUS_PERIOD
|
||||
public const string DieselPriceNotCorrect = "سعر لتر الديزل غير صحيح"; // * ERROR.DIESEL_LITER_PRICE_IS_NOT_CORRECT
|
||||
public const string TonWageNotCorrect = "اجور الطن غير صحيحة"; // * ERROR.TON_WAGE_IS_NOT_CORRECT
|
||||
public const string StartAfterEnd = "لا يجوز أن يكون تاريخ بداية الفترة أكبر من تاريخ نهايتها"; // * ERROR.START_DATE_CAN_NOT_GREATER_THAN_END_DATE
|
||||
public const string TripsExist = "لا يمكن تعديل القيم بسبب وجود ارساليات مسعره عليها"; // ERROR.YOU_CANNOT_UPDATE_VARIABLES_THERE_IS_TRIPS
|
||||
public const string CannotResetTonPrice = "تم تعديل سعر الطن الفعلي سابقا"; // ERROR.YOU_CANNOT_RESET_TON_PRICE
|
||||
public const string NoTripsInPeriod = "لا يوجد ارساليات ضمن هذه الفترة"; // ERROR.THERE_IS_NO_ANY_TRIP_IN_THIS_PERIOD
|
||||
public const string NotAllTripsExchanged = "لا يمكن اعادة تسعير سعر النفط ، يجب ان تكون جميع الارساليات ضمن الفترة مسددة"; // ERROR.NO_TON_PRICE_EDIT_NOT_ALL_TRIPS_EXCHANGED
|
||||
public const string RecalculationNotAvailable = "إعادة احتساب الذمم السابقة غير متوفرة بعد، لا يمكن تعديل سعر الطن الفعلي لفترة فيها ارساليات مغرمة"; // * (balance recalculation belongs to the trips module)
|
||||
public const string NotFound = "فترة التسعير غير موجودة"; // *
|
||||
public const string Done = "";
|
||||
}
|
||||
|
||||
public static class VariablesErrors
|
||||
{
|
||||
public const string DateOverlap = "DATE_IS_EXIT_IN_PREVIOUS_PERIOD";
|
||||
public const string StartDateInPreviousPeriod = "START_DATE_IS_EXIT_IN_PREVIOUS_PERIOD";
|
||||
public const string EndDateInPreviousPeriod = "END_DATE_IS_EXIT_IN_PREVIOUS_PERIOD";
|
||||
public const string DieselPriceNotCorrect = "DIESEL_LITER_PRICE_IS_NOT_CORRECT";
|
||||
public const string TonWageNotCorrect = "TON_WAGE_IS_NOT_CORRECT";
|
||||
public const string StartAfterEnd = "START_DATE_CAN_NOT_GREATER_THAN_END_DATE";
|
||||
public const string TripsExist = "YOU_CANNOT_UPDATE_VARIABLES_THERE_IS_TRIPS";
|
||||
public const string CannotResetTonPrice = "YOU_CANNOT_RESET_TON_PRICE";
|
||||
public const string NoTripsInPeriod = "THERE_IS_NO_ANY_TRIP_IN_THIS_PERIOD";
|
||||
public const string NotAllTripsExchanged = "NO_TON_PRICE_EDIT_NOT_ALL_TRIPS_EXCHANGED";
|
||||
public const string RecalculationNotAvailable = "TON_PRICE_RECALCULATION_NOT_AVAILABLE";
|
||||
public const string NotFound = "REFINERY_VARIABLES_NOT_FOUND";
|
||||
}
|
||||
|
||||
/// <summary>Pure rules of the pricing periods (refinery_variablesfactory.cfc create / update / UPDATE_TON_PRICE_CORRECTION).</summary>
|
||||
public static class VariablesRules
|
||||
{
|
||||
/// <summary>Row of the same table that is not a pricing period: read by the trips module, ignored by the period checks.</summary>
|
||||
public const string AuditModeKey = "AUTDIT_MODE";
|
||||
public const string TonPriceCorrectionKey = "TON_PRICE_CORRECTION";
|
||||
public const string TonPriceCorrectionSetKey = "TON_PRICE_CORRECTION_SET";
|
||||
|
||||
/// <summary>The keys a period holds (legacy DAO create / update whitelist).</summary>
|
||||
public static readonly string[] SetKeys =
|
||||
[
|
||||
"COMMISSION", "DIESEL_LITER_PRICE", "TON_WAGE", "TON_PRICE", "DRIVER_TIP", "WAYBILL_FEE", "FIRST_ADVANCE_PAYMENT",
|
||||
"PERMIT_DISPATCH", "TOLERANCE_PERCENTAGE",
|
||||
];
|
||||
|
||||
/// <summary>KEY_VALUE is a VARCHAR2: the number as plain invariant text (legacy stored what the user typed).</summary>
|
||||
public static string FormatValue(decimal value) => value.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
public static Dictionary<string, string> ToValues(SaveVariablesRequest r) => new()
|
||||
{
|
||||
["COMMISSION"] = FormatValue(r.Commission),
|
||||
["DIESEL_LITER_PRICE"] = FormatValue(r.DieselLiterPrice),
|
||||
["TON_WAGE"] = FormatValue(r.TonWage),
|
||||
["TON_PRICE"] = FormatValue(r.TonPrice),
|
||||
["DRIVER_TIP"] = FormatValue(r.DriverTip),
|
||||
["WAYBILL_FEE"] = FormatValue(r.WaybillFee),
|
||||
["FIRST_ADVANCE_PAYMENT"] = FormatValue(r.FirstAdvancePayment),
|
||||
["PERMIT_DISPATCH"] = FormatValue(r.PermitDispatch),
|
||||
["TOLERANCE_PERCENTAGE"] = FormatValue(r.TolerancePercentage),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The first failing rule, in the legacy order (refinery_variablesfactory.cfc:112-143): start inside another period, end inside another
|
||||
/// period, another period wholly inside the new one, diesel price in (0, 2), ton wage in (0, 100), start after end.
|
||||
/// <paramref name="otherPeriods"/> must already exclude the period being updated.
|
||||
/// </summary>
|
||||
public static (string Code, string Message)? FirstError(IEnumerable<VariablesPeriod> otherPeriods, SaveVariablesRequest r)
|
||||
{
|
||||
var start = r.StartDate.ToDateTime(TimeOnly.MinValue);
|
||||
var end = r.EndDate.ToDateTime(TimeOnly.MinValue);
|
||||
var others = otherPeriods.ToList();
|
||||
if (others.Any(p => p.Start.Date <= start && start <= p.End.Date))
|
||||
return (VariablesErrors.StartDateInPreviousPeriod, VariablesMessages.StartDateInPreviousPeriod);
|
||||
if (others.Any(p => p.Start.Date <= end && end <= p.End.Date))
|
||||
return (VariablesErrors.EndDateInPreviousPeriod, VariablesMessages.EndDateInPreviousPeriod);
|
||||
if (others.Any(p => p.Start.Date > start && p.End.Date < end))
|
||||
return (VariablesErrors.DateOverlap, VariablesMessages.DateOverlap);
|
||||
if (r.DieselLiterPrice <= 0 || r.DieselLiterPrice >= 2)
|
||||
return (VariablesErrors.DieselPriceNotCorrect, VariablesMessages.DieselPriceNotCorrect);
|
||||
if (r.TonWage <= 0 || r.TonWage >= 100)
|
||||
return (VariablesErrors.TonWageNotCorrect, VariablesMessages.TonWageNotCorrect);
|
||||
if (start > end)
|
||||
return (VariablesErrors.StartAfterEnd, VariablesMessages.StartAfterEnd);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Legacy compares the stored TON_PRICE with the typed correction; the balances are only recalculated when they differ
|
||||
/// (refinery_variablesfactory.cfc:307).
|
||||
/// </summary>
|
||||
public static bool TonPriceChanges(decimal? currentTonPrice, decimal correction) => currentTonPrice is not null && currentTonPrice.Value != correction;
|
||||
}
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
using FluentValidation;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
using NTP.Application.Grains.Reports;
|
||||
|
||||
namespace NTP.Application.Refinery.Variables;
|
||||
|
||||
/// <summary>
|
||||
/// Port of refinery_variablesfactory.cfc / refinery_variablesfactoryweb.cfc (screen REFINERY_VARIABLES, تسعير عطاء النفط الخام).
|
||||
/// Access is decided only by the permission keys on the controller (SU / REFINERY_MGR); the legacy REFINERY_MGR / REFINERY_AC role branches are not ported.
|
||||
/// There is no log: the legacy log call is commented out and no REFINERY_VARIABLES_LOG table exists.
|
||||
/// </summary>
|
||||
public sealed class VariablesService(
|
||||
IVariablesRepository repository,
|
||||
ITonPriceRecalculationService recalculation,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user,
|
||||
IReportExcelService excel,
|
||||
IValidator<SaveVariablesRequest> saveValidator,
|
||||
IValidator<TonPriceCorrectionRequest> correctionValidator) : IVariablesService
|
||||
{
|
||||
private const string ExcelType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
|
||||
public Task<PagedResult<VariablesSetRow>> SearchAsync(VariablesQuery query, PageRequest page, CancellationToken ct) =>
|
||||
repository.SearchAsync(query, page, ct);
|
||||
|
||||
public async Task<VariablesSetDetail> GetAsync(long groupId, CancellationToken ct)
|
||||
{
|
||||
var row = await repository.GetAsync(groupId, ct) ?? throw new NotFoundException("Refinery variables", groupId);
|
||||
var canUpdate = row.StartDate is not null && row.EndDate is not null
|
||||
&& !await repository.HasTripsAsync(row.StartDate.Value, row.EndDate.Value, ct);
|
||||
return new VariablesSetDetail
|
||||
{
|
||||
GroupId = row.GroupId, StartDate = row.StartDate, EndDate = row.EndDate, DieselLiterPrice = row.DieselLiterPrice,
|
||||
TonWage = row.TonWage, TonPrice = row.TonPrice, DriverTip = row.DriverTip, PermitDispatch = row.PermitDispatch,
|
||||
WaybillFee = row.WaybillFee, Commission = row.Commission, TolerancePercentage = row.TolerancePercentage,
|
||||
FirstAdvancePayment = row.FirstAdvancePayment, TonPriceCorrection = row.TonPriceCorrection,
|
||||
TonPriceCorrectionSet = row.TonPriceCorrectionSet,
|
||||
CanUpdate = canUpdate,
|
||||
CanSetTonPriceCorrection = !row.TonPriceCorrectionSet,
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<VariablesResult> CreateAsync(SaveVariablesRequest request, CancellationToken ct)
|
||||
{
|
||||
await saveValidator.ValidateAndThrowAsync(request, ct);
|
||||
var error = VariablesRules.FirstError(await repository.GetPeriodsAsync(null, ct), request);
|
||||
if (error is { } e) throw new BusinessException(e.Code, e.Message);
|
||||
|
||||
var groupId = await unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
var id = await repository.NextGroupIdAsync(token);
|
||||
await repository.InsertSetAsync(id, request.StartDate, request.EndDate, VariablesRules.ToValues(request), user.UserId, token);
|
||||
return id;
|
||||
}, ct);
|
||||
return new VariablesResult(VariablesMessages.Done, groupId);
|
||||
}
|
||||
|
||||
public async Task<VariablesResult> UpdateAsync(long groupId, SaveVariablesRequest request, CancellationToken ct)
|
||||
{
|
||||
await saveValidator.ValidateAndThrowAsync(request, ct);
|
||||
var current = await repository.GetAsync(groupId, ct) ?? throw new NotFoundException("Refinery variables", groupId);
|
||||
var error = VariablesRules.FirstError(await repository.GetPeriodsAsync(groupId, ct), request);
|
||||
if (error is { } e) throw new BusinessException(e.Code, e.Message);
|
||||
|
||||
// refinery_variablesfactory.cfc:162-170: the stored period must not hold a trip (checked on the dates before the change)
|
||||
if (current.StartDate is not null && current.EndDate is not null
|
||||
&& await repository.HasTripsAsync(current.StartDate.Value, current.EndDate.Value, ct))
|
||||
throw new BusinessException(VariablesErrors.TripsExist, VariablesMessages.TripsExist);
|
||||
|
||||
await unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await repository.UpdateSetAsync(groupId, request.StartDate, request.EndDate, VariablesRules.ToValues(request), user.UserId, token);
|
||||
return true;
|
||||
}, ct);
|
||||
return new VariablesResult(VariablesMessages.Done, groupId);
|
||||
}
|
||||
|
||||
/// <summary>UPDATE_TON_PRICE_CORRECTION: sets the actual ton price once; the balances of the trucks are recalculated when it differs from TON_PRICE.</summary>
|
||||
public async Task<VariablesResult> SetTonPriceCorrectionAsync(long groupId, TonPriceCorrectionRequest request, CancellationToken ct)
|
||||
{
|
||||
await correctionValidator.ValidateAndThrowAsync(request, ct);
|
||||
var current = await repository.GetAsync(groupId, ct) ?? throw new NotFoundException("Refinery variables", groupId);
|
||||
if (current.TonPriceCorrectionSet)
|
||||
throw new BusinessException(VariablesErrors.CannotResetTonPrice, VariablesMessages.CannotResetTonPrice);
|
||||
if (current.StartDate is null || current.EndDate is null)
|
||||
throw new BusinessException(VariablesErrors.NotFound, VariablesMessages.NotFound);
|
||||
|
||||
await unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await repository.SetTonPriceCorrectionAsync(groupId, VariablesRules.FormatValue(request.TonPriceCorrection),
|
||||
current.StartDate.Value, current.EndDate.Value, user.UserId, token);
|
||||
// legacy: a failed recalculation resets both rows to 0 (DELETE_ON_PRICE_CORRECTION) and returns the error; here the transaction is rolled back
|
||||
if (VariablesRules.TonPriceChanges(current.TonPrice, request.TonPriceCorrection))
|
||||
await recalculation.RecalculateAsync(groupId, current.StartDate.Value, current.EndDate.Value, token);
|
||||
return true;
|
||||
}, ct);
|
||||
return new VariablesResult(VariablesMessages.Done, groupId);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ reports (Excel)
|
||||
|
||||
public async Task<ExportFile> ExportAsync(VariablesQuery query, CancellationToken ct)
|
||||
{
|
||||
var rows = new List<VariablesSetRow>();
|
||||
for (var p = 1; rows.Count < 20000; p++)
|
||||
{
|
||||
var r = await repository.SearchAsync(query, new PageRequest(p, PageRequest.MaxPageSize), ct);
|
||||
rows.AddRange(r.Items);
|
||||
if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break;
|
||||
}
|
||||
var cols = new List<ReportColumn>
|
||||
{
|
||||
new("startDate", "بداية فترة التسعير", "Start", "date"), new("endDate", "نهاية فترة التسعير", "End", "date"),
|
||||
new("dieselLiterPrice", "سعر لتر الديزل", "Diesel liter price"), new("tonWage", "اجور الطن", "Ton wage"),
|
||||
new("tonPrice", "سعر الطن", "Ton price"), new("driverTip", "اكرامية السائق", "Driver tip"),
|
||||
new("permitDispatch", "سعر تسريب الصهريج", "Permit dispatch"), new("waybillFee", "اصدار وثيقة", "Waybill fee"),
|
||||
new("commission", "عمولة الصرف التنافسي", "Commission"), new("tolerancePercentage", "نسبة السماح", "Tolerance"),
|
||||
new("firstAdvancePayment", "قيمة شحن الديزل للتحميل", "First advance payment"),
|
||||
};
|
||||
var data = rows.Select(r => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
|
||||
{
|
||||
["startDate"] = r.StartDate, ["endDate"] = r.EndDate, ["dieselLiterPrice"] = r.DieselLiterPrice, ["tonWage"] = r.TonWage,
|
||||
["tonPrice"] = r.TonPrice, ["driverTip"] = r.DriverTip, ["permitDispatch"] = r.PermitDispatch, ["waybillFee"] = r.WaybillFee,
|
||||
["commission"] = r.Commission, ["tolerancePercentage"] = r.TolerancePercentage, ["firstAdvancePayment"] = r.FirstAdvancePayment,
|
||||
}).ToList();
|
||||
return Build("REFINERY_VARIABLES", "تسعير عطاء النفط الخام", "Crude oil tender pricing", cols, data);
|
||||
}
|
||||
|
||||
/// <summary>refineryRemainingBalanceReport: REFINERY_REMAINING_BALANCE ordered by balance, biggest first.</summary>
|
||||
public async Task<ExportFile> ExportRemainingBalanceAsync(CancellationToken ct)
|
||||
{
|
||||
var rows = await repository.GetRemainingBalancesAsync(ct);
|
||||
var cols = new List<ReportColumn>
|
||||
{
|
||||
new("counter", "متسلسل", "#"), new("tn", "رقم الشاحنة", "Truck"), new("remainingBalance", "قيمة الذمم السابقة", "Previous balance"),
|
||||
};
|
||||
var n = 0;
|
||||
var data = rows.Select(r => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
|
||||
{
|
||||
["counter"] = ++n, ["tn"] = r.Tn, ["remainingBalance"] = r.RemainingBalance,
|
||||
}).ToList();
|
||||
return Build("REMAINING_BALANCE", "قيمة الذمم السابقة", "Previous balance", cols, data);
|
||||
}
|
||||
|
||||
private ExportFile Build(string key, string titleAr, string titleEn, IReadOnlyList<ReportColumn> cols, IReadOnlyList<IReadOnlyDictionary<string, object?>> rows)
|
||||
{
|
||||
var table = new ReportTable { Key = key, TitleAr = titleAr, TitleEn = titleEn, Columns = cols, Rows = rows };
|
||||
var bytes = excel.Build(table, user.UserId, DateTime.Now, true);
|
||||
return new ExportFile(bytes, ExcelType, key + ".xlsx");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
using FluentValidation;
|
||||
|
||||
namespace NTP.Application.Refinery.Variables;
|
||||
|
||||
/// <summary>The form of the screen: every field is required (legacy HTML required), numbers are not negative (class floatnumber, maxlength 7).</summary>
|
||||
public sealed class SaveVariablesValidator : AbstractValidator<SaveVariablesRequest>
|
||||
{
|
||||
public const string Required = "الرجاء ادخال جميع الحقول"; // REPORT.VALIDATION
|
||||
|
||||
public SaveVariablesValidator()
|
||||
{
|
||||
RuleFor(x => x.StartDate).NotEqual(default(DateOnly)).WithMessage(Required);
|
||||
RuleFor(x => x.EndDate).NotEqual(default(DateOnly)).WithMessage(Required);
|
||||
// the value range checks of diesel price and ton wage are in VariablesRules (legacy messages, legacy order)
|
||||
RuleFor(x => x.DieselLiterPrice).GreaterThanOrEqualTo(0).WithMessage(Required);
|
||||
RuleFor(x => x.TonWage).GreaterThanOrEqualTo(0).WithMessage(Required);
|
||||
RuleFor(x => x.FirstAdvancePayment).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required);
|
||||
RuleFor(x => x.TonPrice).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required);
|
||||
RuleFor(x => x.DriverTip).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required);
|
||||
RuleFor(x => x.PermitDispatch).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required);
|
||||
RuleFor(x => x.WaybillFee).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required);
|
||||
RuleFor(x => x.Commission).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required);
|
||||
RuleFor(x => x.TolerancePercentage).GreaterThanOrEqualTo(0).LessThan(10_000_000m).WithMessage(Required);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TonPriceCorrectionValidator : AbstractValidator<TonPriceCorrectionRequest>
|
||||
{
|
||||
public TonPriceCorrectionValidator()
|
||||
{
|
||||
// 0 is what DELETE_ON_PRICE_CORRECTION writes to mean "no correction", so it is not a value to set
|
||||
RuleFor(x => x.TonPriceCorrection).GreaterThan(0).LessThan(10_000_000m).WithMessage(SaveVariablesValidator.Required);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using NTP.Application.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Refinery.WageClaims;
|
||||
|
||||
/// <summary>Excel (HTML table opened by Excel, like the other V1 exports) of a claim report: company and report title, filter lines, header, rows, footer.</summary>
|
||||
internal static class ClaimExcel
|
||||
{
|
||||
public static string E(object? v) => WebUtility.HtmlEncode(Convert.ToString(v, CultureInfo.InvariantCulture) ?? string.Empty);
|
||||
|
||||
public static string N(decimal v) => v.ToString("0.###", CultureInfo.InvariantCulture);
|
||||
|
||||
public static string D(DateTime? d) => d is null ? string.Empty : d.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
|
||||
|
||||
public static ExportFile Build(string title, IEnumerable<string> infoLines, string[] headers, IEnumerable<object?[]> rows, string user, string fileName)
|
||||
{
|
||||
var n = headers.Length;
|
||||
var h = new StringBuilder();
|
||||
h.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
|
||||
h.Append("<style>.header{font-weight:bold;font-size:28px;}");
|
||||
h.Append(".sub_header{font-weight:bold;font-size:14px;background-color:#034878;color:#FFFFFF;text-align:center;}</style>");
|
||||
h.Append("<table align=\"center\" dir=\"rtl\" border=\"1\">");
|
||||
h.Append($"<tr align=\"center\"><td colspan=\"{n}\" class=\"header\">شركة نافذ للخدمات اللوجستية</td></tr>");
|
||||
h.Append($"<tr align=\"center\"><td colspan=\"{n}\" class=\"header\">{E(title)}</td></tr>");
|
||||
foreach (var line in infoLines) h.Append($"<tr align=\"center\"><td colspan=\"{n}\">{E(line)}</td></tr>");
|
||||
h.Append("<tr align=\"center\">");
|
||||
foreach (var c in headers) h.Append($"<td class=\"sub_header\">{E(c)}</td>");
|
||||
h.Append("</tr>");
|
||||
var count = 0;
|
||||
foreach (var r in rows)
|
||||
{
|
||||
count++;
|
||||
h.Append("<tr align=\"center\">");
|
||||
foreach (var v in r) h.Append($"<td>{E(v)}</td>");
|
||||
h.Append("</tr>");
|
||||
}
|
||||
if (count == 0) h.Append($"<tr><td colspan=\"{n}\">لا يوجد معلومات</td></tr>");
|
||||
h.Append($"<tr><td colspan=\"{n}\">بتاريخ : {DateTime.Now:dd/MM/yyyy HH:mm} - عدد النتائج : {count} - طبع التقرير بواسطة : {E(user)}</td></tr>");
|
||||
h.Append("</table></body></html>");
|
||||
var bytes = new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(h.ToString())).ToArray();
|
||||
return new ExportFile(bytes, "application/vnd.ms-excel", fileName + ".xls");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Refinery.WageClaims;
|
||||
|
||||
/// <summary>A trip of a claim waiting for the Jopetrol transfer (REFINERY_TRIPS.TRIP_STATUS = 6).</summary>
|
||||
public sealed class TransferTripRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Pn { get; set; }
|
||||
public string? StatusCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SQL of refinery_wage_claimdao.cfc (+ the writes of refinery_wage_claimfactory.cfc). REFINERY_TRIPS is only read, except for the columns the
|
||||
/// legacy claim code writes: WAGE_CLAIM_ID, STATUS_CODE (COMPLETE), TRIP_STATUS (7), LAST_UPDATE_DATE, UPDATED_BY.
|
||||
/// </summary>
|
||||
public interface IWageClaimRepository
|
||||
{
|
||||
Task<PagedResult<WageClaimRowDto>> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<WageClaimRowDto?> GetAsync(long id, CancellationToken ct = default);
|
||||
Task<PagedResult<ClaimTripRowDto>> ClaimTripsAsync(long claimId, PageRequest page, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Trips of the given statuses without a wage claim (optionally limited to a loading date range): the create preview.</summary>
|
||||
Task<PagedResult<ClaimTripRowDto>> CandidateTripsAsync(IReadOnlyList<string> statuses, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct = default);
|
||||
Task<int> CountCandidateTripsAsync(IReadOnlyList<string> statuses, DateOnly from, DateOnly to, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Takes the next claim number (legacy GenerateSerialNumber) and inserts the claim as NEW; returns its id. Run inside a transaction.</summary>
|
||||
Task<long> InsertClaimAsync(string createdBy, CancellationToken ct = default);
|
||||
Task<int> AttachTripsAsync(long claimId, IReadOnlyList<string> statuses, DateOnly from, DateOnly to, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<string>> ClaimTripStatusesAsync(long claimId, CancellationToken ct = default);
|
||||
/// <summary>TRIP_COMPLETE for every trip of the claim: status COMPLETE plus one REFINERY_TRIPS_LOG row each. Returns the number of trips.</summary>
|
||||
Task<int> CompleteClaimTripsAsync(long claimId, string userLogin, long userId, string? ip, CancellationToken ct = default);
|
||||
/// <summary>STATUS_CODE of a commission claim (null when it does not exist).</summary>
|
||||
Task<string?> CommissionClaimStatusAsync(long commissionClaimId, CancellationToken ct = default);
|
||||
Task SetClaimStatusAsync(long claimId, string status, string userLogin, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<TransferTripRow>> TripsToTransferAsync(long claimId, CancellationToken ct = default);
|
||||
/// <summary>TRIP_STATUS 7 + REFINERY_TRIPS_LOG row TRANSFER_TO_REFINERY. Run inside a transaction.</summary>
|
||||
Task MarkTripTransferredAsync(TransferTripRow trip, long userId, string? ip, CancellationToken ct = default);
|
||||
|
||||
Task AddLogAsync(long claimId, string method, string? oldData, string? newData, long userId, string? ip, CancellationToken ct = default);
|
||||
Task<PagedResult<ClaimLogRowDto>> LogAsync(long claimId, PageRequest page, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<WageClaimReportRaw>> ReportRowsAsync(long claimId, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
namespace NTP.Application.Refinery.WageClaims;
|
||||
|
||||
// ------------------------------------------------------------------ wage claim list / view (REFINERY_WAGE_CLAIM_VIEW)
|
||||
|
||||
public sealed class WageClaimRowDto
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long? WageClaimNo { get; set; }
|
||||
public DateTime? WageClaimDate { get; set; }
|
||||
public long TripCnt { get; set; }
|
||||
public long? CommissionClaimId { get; set; }
|
||||
public long? CommissionClaimNo { get; set; }
|
||||
/// <summary>NEW / CLOSE / COMPLETE.</summary>
|
||||
public string StatusCode { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>Filters of the legacy grid (WAGE_CLAIM_NO, WAGE_CLAIM_DATE, STATUS_CODE, COMMISSION_CLAIM_NO, HAS_COMMISSION_CLAIM).</summary>
|
||||
public sealed record WageClaimQuery(
|
||||
string? WageClaimNo, DateOnly? WageClaimDate, IReadOnlyList<string> StatusCodes, string? CommissionClaimNo, bool? HasCommissionClaim);
|
||||
|
||||
/// <summary>A trip as shown inside a claim (legacy searchClaimTrips columns) and in the create preview.</summary>
|
||||
public sealed class ClaimTripRowDto
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Pn { get; set; }
|
||||
public DateTime? PaymentedDate { get; set; }
|
||||
public long? LoadingNo { get; set; }
|
||||
public string? DischargeAuthoriztionNo { get; set; }
|
||||
public DateTime? DischargeEntryDate { get; set; }
|
||||
public string? Tn { get; set; }
|
||||
public string? Trn { get; set; }
|
||||
public string? Nnpn { get; set; }
|
||||
public string StatusCode { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>One row of the log popup (REFINERY_WAGE_CLAIM_LOG_VIEW / REFINERY_COMMISSION_LOG_VIEW).</summary>
|
||||
public sealed class ClaimLogRowDto
|
||||
{
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>Body of POST wage-claims (legacy create: STATUS_CODE list + LOADING_DATE_FROM / TO).</summary>
|
||||
public sealed record CreateWageClaimRequest(IReadOnlyList<string>? StatusCodes, DateOnly? LoadingDateFrom, DateOnly? LoadingDateTo);
|
||||
|
||||
/// <summary>Answer of the write endpoints: the (Arabic) message to toast and the id of the created record.</summary>
|
||||
public sealed record ClaimResult(string Message, long? Id = null);
|
||||
|
||||
// ------------------------------------------------------------------ export
|
||||
|
||||
/// <summary>Raw values of one trip of the claim report (legacy REFINERY_CLAIMS_REPORT_VIEW).</summary>
|
||||
public sealed class WageClaimReportRaw
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Drvr { get; set; }
|
||||
public string? Tn { get; set; }
|
||||
public string? DischargeAuthoriztionNo { get; set; }
|
||||
public long? DischargeAuthoriztionYear { get; set; }
|
||||
public DateTime? DischargeEntryDate { get; set; }
|
||||
public string? ClientNo { get; set; }
|
||||
public long? LoadingNo { get; set; }
|
||||
public DateTime? ActualLoadingDate { get; set; }
|
||||
public decimal? NetLoadingWeight { get; set; }
|
||||
public decimal? WaterAmount { get; set; }
|
||||
public decimal? NetDischargeWeight { get; set; }
|
||||
public decimal? CalculatedQuantityTon { get; set; }
|
||||
public decimal? ToleranceQuantity { get; set; }
|
||||
public decimal? PenaltyQuantity { get; set; }
|
||||
public decimal? TonPrice { get; set; }
|
||||
public decimal? TonWage { get; set; }
|
||||
public decimal? PenaltyAmount { get; set; }
|
||||
public decimal? DriverTip { get; set; }
|
||||
public decimal? PermitDispatch { get; set; }
|
||||
public decimal? WaybillFee { get; set; }
|
||||
public decimal? DieselLiterPrice { get; set; }
|
||||
/// <summary>sum(REFINERY_CARDS_LOG.AMOUNT) of the trip.</summary>
|
||||
public decimal? AdvancePaymentForDiesel { get; set; }
|
||||
public decimal? Commission { get; set; }
|
||||
public decimal? NetWage { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The one-row summary of a claim (legacy تقرير الملخص, refinerytripsxls.cfr): totals over its trips, deductions shown positive.</summary>
|
||||
public sealed record WageClaimSummary(
|
||||
int TripCount, decimal LoadingWeight, decimal Water, decimal DischargeWeight, decimal Difference, decimal CalculatedTon, decimal QuantityWage,
|
||||
decimal PenaltyQuantity, decimal PenaltyAmount, decimal DriverTip, decimal PermitDispatch, decimal WaybillFee, decimal DieselAdvance,
|
||||
decimal Commission, decimal NetWage, string Tender);
|
||||
|
||||
/// <summary>Values of one report line after the legacy sign changes (deductions are shown negative).</summary>
|
||||
public sealed record WageClaimReportLine(
|
||||
string? Drvr, string? Tn, string? DischargeAuthoriztionNo, long? DischargeAuthoriztionYear, DateTime? DischargeEntryDate, string? ClientNo,
|
||||
long? LoadingNo, DateTime? ActualLoadingDate, decimal NetLoadingWeight, decimal WaterAmount, decimal NetDischargeWeight, decimal WeightDifference,
|
||||
decimal CalculatedQuantityTon, decimal ToleranceQuantity, bool WaterExist, decimal PenaltyQuantity, decimal TonPrice, decimal PenaltyAmount,
|
||||
decimal DriverTip, decimal PermitDispatch, decimal WaybillFee, decimal DieselLiterPrice, decimal AdvancePaymentForDiesel, decimal Commission, decimal NetWage);
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Refinery.WageClaims;
|
||||
|
||||
/// <summary>User-facing texts of the claim screens: the legacy captions (NTP.LT_CAPTION), verbatim.</summary>
|
||||
public static class ClaimMessages
|
||||
{
|
||||
public const string Success = "تمت العملية بنجاح"; // PUBLIC.SUCCESSFUL.OPERATION
|
||||
public const string StatusRequired = "يجب اختيار الحالة"; // ERROR.STATUS_REQUIRED
|
||||
public const string DateRequired = "يجب اختيار التاريخ"; // ERROR.DATE_REQUIRED
|
||||
public const string FromGreaterThanTo = "لا يجوز ان يكون تاريخ من أكبر من تارخ الى"; // ERROR.FROM_CAN_NOT_GREATER_THAN_TO
|
||||
public const string NoTripsNeedWage = "لا يوجد ارساليات جاهزة لانشاء مطالبة مالية"; // ERROR.THERS_IS_NOT_TRIPS_NEED_WAGE
|
||||
public const string CloseClaim = "لا يمكن تسديد هذه المطالبة يوجد ارساليات ضمن المطالبة حالتها جاهز للدفع او تم التفريغ"; // ERROR.CLOSE_CLAIM
|
||||
public const string NoAuthority = "ليس لديك صلاحية لاتمام هذه العملية"; // ERROR.NO_AUTHORITY
|
||||
public const string NoWages = "لا يوجد مطالبات اجور"; // ERROR.THERE_ARE_NO_WAGES
|
||||
public const string PleaseSelectClaim = "يرجى اختيار المطالبة"; // ERROR.PLEASE_SELECT_CLAIM
|
||||
public const string WageClaimNotClose = "لا يمكن تسديد هذه المطالبة يوجد مطالبات اجور غير مسددة"; // ERROR.WAGE_CLAIM_IS_NOT_CLOSE
|
||||
public const string NoTripsIssue = "لا يوجد ارساليات"; // ERROR.NO_TRIPS_THERE_IS_ISSUE
|
||||
public const string CommissionVariableIssue = "يوجد خطأ في تعريف قيمة عمولة الاجور"; // ERROR.REFINERY_VARIABLES_COMMISSION_ISSUE
|
||||
/// <summary>New text (the legacy code had no such case): the Jopetrol integration is switched off by configuration.</summary>
|
||||
public const string JopetrolDisabled = "خدمة الترحيل إلى المصفاة غير مفعلة في هذه البيئة، لم يتم تغيير أي شيء";
|
||||
/// <summary>New text: the status of a wage claim can change only while its commission claim (if any) is still new.</summary>
|
||||
public const string CommissionNotNew = "لا يمكن تغيير حالة المطالبة لان مطالبة العمولة المرتبطة بها ليست بحالة جديد";
|
||||
public const string NotFound ="المطالبة غير موجودة";
|
||||
|
||||
// log captions (method names of the *_LOG tables)
|
||||
public const string StatusNew = "جديد"; // REFINERY_WAGE_CLAIM.STATUSCODE.NEW
|
||||
public const string StatusClose = "تم التسديد"; // ...STATUSCODE.CLOSE
|
||||
public const string StatusComplete = "مكتمل"; // ...STATUSCODE.COMPLETE
|
||||
public const string TripExchanged = "تم الصرف"; // REFINERYTRIP.STATUSCODE.EXCHANGED
|
||||
public const string TripComplete = "مكتمل"; // REFINERYTRIP.STATUSCODE.COMPLETE
|
||||
}
|
||||
|
||||
/// <summary>Pure rules of the wage claim screen (refinery_wage_claimfactory.cfc).</summary>
|
||||
public static class WageClaimRules
|
||||
{
|
||||
public const string New = "NEW";
|
||||
public const string Close = "CLOSE";
|
||||
public const string Complete = "COMPLETE";
|
||||
|
||||
/// <summary>Trip statuses the create dialog offers (REFINERY_WAGE_CLAIMMain.html); trips of other statuses are never attached.</summary>
|
||||
public static readonly IReadOnlyList<string> ClaimableTripStatuses = ["EXCHANGED", "READY_TO_PAY", "DISCHARGED"];
|
||||
|
||||
/// <summary>Distinct upper-case statuses, only the claimable ones (the legacy select-all option "ALL" and unknown values are dropped).</summary>
|
||||
public static IReadOnlyList<string> NormalizeTripStatuses(IEnumerable<string>? raw) =>
|
||||
(raw ?? [])
|
||||
.SelectMany(s => (s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
.Select(s => s.ToUpperInvariant())
|
||||
.Where(s => ClaimableTripStatuses.Contains(s))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
|
||||
/// <summary>factory.create: status required, both dates required, from not after to (messages in this order).</summary>
|
||||
public static void ValidateCreate(IReadOnlyList<string> statuses, DateOnly? from, DateOnly? to)
|
||||
{
|
||||
if (statuses.Count == 0) throw new BusinessException("STATUS_REQUIRED", ClaimMessages.StatusRequired);
|
||||
if (from is null || to is null) throw new BusinessException("DATE_REQUIRED", ClaimMessages.DateRequired);
|
||||
if (from.Value > to.Value) throw new BusinessException("FROM_GREATER_THAN_TO", ClaimMessages.FromGreaterThanTo);
|
||||
}
|
||||
|
||||
/// <summary>factory.CLAIM_CLOSE: a claim is paid only when it has trips and every one of them is EXCHANGED.</summary>
|
||||
public static bool CanCloseClaim(IEnumerable<string> tripStatuses)
|
||||
{
|
||||
var distinct = tripStatuses.Distinct().ToList();
|
||||
return distinct.Count == 1 && distinct[0] == "EXCHANGED";
|
||||
}
|
||||
|
||||
/// <summary>factory.TRANSFER: the Jopetrol answer must contain this text (findNoCase) for the trip to move to TRIP_STATUS 7.</summary>
|
||||
public static bool IsStatus7Success(string? serviceAnswer) =>
|
||||
serviceAnswer is not null && serviceAnswer.Contains("Status Updated successfully To 7", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Last day (inclusive) of a [from, to] day range as an exclusive upper bound (legacy: between FROM000000 and TO235959).</summary>
|
||||
public static DateTime ExclusiveEnd(DateOnly to) => to.AddDays(1).ToDateTime(TimeOnly.MinValue);
|
||||
|
||||
/// <summary>
|
||||
/// Report line of one trip, as legacy factoryweb.report prepares it: the deductions (driver tip, permit dispatch, waybill fee, diesel liter price,
|
||||
/// diesel advance when > 0, commission) are multiplied by -1; the penalty quantity is 0 when the weight difference is below the tolerance
|
||||
/// (REFINERY_CLAIMS_REPORT_VIEW).
|
||||
/// </summary>
|
||||
public static WageClaimReportLine ToReportLine(WageClaimReportRaw r)
|
||||
{
|
||||
decimal V(decimal? d) => d ?? 0m;
|
||||
var diff = V(r.NetLoadingWeight) - V(r.NetDischargeWeight);
|
||||
var penaltyQty = diff < V(r.ToleranceQuantity) ? 0m : V(r.PenaltyQuantity);
|
||||
var advance = V(r.AdvancePaymentForDiesel);
|
||||
return new WageClaimReportLine(
|
||||
r.Drvr, r.Tn, r.DischargeAuthoriztionNo, r.DischargeAuthoriztionYear, r.DischargeEntryDate, r.ClientNo,
|
||||
r.LoadingNo, r.ActualLoadingDate, V(r.NetLoadingWeight), V(r.WaterAmount), V(r.NetDischargeWeight), diff,
|
||||
V(r.CalculatedQuantityTon), V(r.ToleranceQuantity), V(r.WaterAmount) > 0, penaltyQty, V(r.TonPrice), V(r.PenaltyAmount),
|
||||
-V(r.DriverTip), -V(r.PermitDispatch), -V(r.WaybillFee), -V(r.DieselLiterPrice),
|
||||
advance > 0 ? -advance : advance, -V(r.Commission), V(r.NetWage));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// تقرير الملخص: totals over the trips. Quantity * ton wage is summed unrounded; the penalty quantity follows the same tolerance rule as the
|
||||
/// trip report; the tender label is the tender number (the form number without its 3-digit serial) of the highest form, with its year.
|
||||
/// </summary>
|
||||
public static WageClaimSummary ToSummary(IReadOnlyList<WageClaimReportRaw> trips)
|
||||
{
|
||||
decimal V(decimal? d) => d ?? 0m;
|
||||
var lines = trips.Select(ToReportLine).ToList();
|
||||
return new WageClaimSummary(
|
||||
trips.Count, trips.Sum(t => V(t.NetLoadingWeight)), trips.Sum(t => V(t.WaterAmount)), trips.Sum(t => V(t.NetDischargeWeight)),
|
||||
lines.Sum(l => l.WeightDifference), trips.Sum(t => V(t.CalculatedQuantityTon)), trips.Sum(t => V(t.CalculatedQuantityTon) * V(t.TonWage)),
|
||||
lines.Sum(l => l.PenaltyQuantity), trips.Sum(t => V(t.PenaltyAmount)), trips.Sum(t => V(t.DriverTip)), trips.Sum(t => V(t.PermitDispatch)),
|
||||
trips.Sum(t => V(t.WaybillFee)), trips.Sum(t => V(t.AdvancePaymentForDiesel)), trips.Sum(t => V(t.Commission)), trips.Sum(t => V(t.NetWage)),
|
||||
TenderLabel(trips));
|
||||
}
|
||||
|
||||
/// <summary>"27/2021": form numbers are tender number + 3-digit serial (26596 = tender 26); empty when the trips have no usable form number.</summary>
|
||||
public static string TenderLabel(IEnumerable<WageClaimReportRaw> trips)
|
||||
{
|
||||
var best = trips
|
||||
.Select(t => (No: long.TryParse(t.DischargeAuthoriztionNo, out var n) ? n : 0, t.DischargeAuthoriztionYear))
|
||||
.Where(x => x.No >= 1000)
|
||||
.OrderByDescending(x => x.No)
|
||||
.FirstOrDefault();
|
||||
return best.No == 0 ? "" : $"{best.No / 1000}/{best.DischargeAuthoriztionYear}";
|
||||
}
|
||||
|
||||
/// <summary>Caption of a claim status (REFINERY_WAGE_CLAIM.STATUS.* / REFINERY_COMMISSION_CLAIM.STATUS.*).</summary>
|
||||
public static string ClaimStatusCaption(string? code) => code switch
|
||||
{
|
||||
New => ClaimMessages.StatusNew,
|
||||
Close => ClaimMessages.StatusClose,
|
||||
Complete => ClaimMessages.StatusComplete,
|
||||
_ => code ?? "",
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,229 @@
|
|||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
using NTP.Application.Refinery.Integrations;
|
||||
using NTP.Application.Refinery.Trips;
|
||||
|
||||
namespace NTP.Application.Refinery.WageClaims;
|
||||
|
||||
/// <summary>JSON of the OLD_DATA / NEW_DATA columns of the *_LOG tables: <c>{"STATUS_CODE":"..."}</c> with real (unescaped) Arabic, as legacy logs.saveLog.</summary>
|
||||
public static class ClaimLogJson
|
||||
{
|
||||
private static readonly JsonSerializerOptions Opts = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
|
||||
public static string Status(string caption) => JsonSerializer.Serialize(new Dictionary<string, string> { ["STATUS_CODE"] = caption }, Opts);
|
||||
}
|
||||
|
||||
public interface IWageClaimService
|
||||
{
|
||||
Task<PagedResult<WageClaimRowDto>> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<WageClaimRowDto> GetAsync(long id, CancellationToken ct);
|
||||
Task<PagedResult<ClaimTripRowDto>> TripsAsync(long id, PageRequest page, CancellationToken ct);
|
||||
Task<PagedResult<ClaimTripRowDto>> CandidateTripsAsync(IReadOnlyList<string>? statusCodes, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct);
|
||||
Task<PagedResult<ClaimLogRowDto>> LogAsync(long id, PageRequest page, CancellationToken ct);
|
||||
Task<ClaimResult> CreateAsync(CreateWageClaimRequest request, string? ip, CancellationToken ct);
|
||||
Task<ClaimResult> CloseAsync(long id, string? ip, CancellationToken ct);
|
||||
Task<ClaimResult> SetClosedAsync(long id, string? ip, CancellationToken ct);
|
||||
Task<ClaimResult> ReopenAsync(long id, string? ip, CancellationToken ct);
|
||||
Task<ClaimResult> TransferAsync(long id, string? ip, CancellationToken ct);
|
||||
Task<ExportFile> ExportAsync(long id, CancellationToken ct);
|
||||
Task<ExportFile> ExportSummaryAsync(long id, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Port of refinery_wage_claimfactory.cfc. Who may do what is decided by the permission keys on the controller
|
||||
/// (PermissionKeys.RefineryWageClaims*), not by the legacy role branches.
|
||||
/// </summary>
|
||||
public sealed class WageClaimService(IWageClaimRepository repo, IUnitOfWork unit, IJopetrolGateway jopetrol, ICurrentUser user) : IWageClaimService
|
||||
{
|
||||
public Task<PagedResult<WageClaimRowDto>> SearchAsync(WageClaimQuery query, PageRequest page, CancellationToken ct) => repo.SearchAsync(query, page, ct);
|
||||
|
||||
public async Task<WageClaimRowDto> GetAsync(long id, CancellationToken ct) =>
|
||||
await repo.GetAsync(id, ct) ?? throw new NotFoundException("REFINERY_WAGE_CLAIM", id);
|
||||
|
||||
public async Task<PagedResult<ClaimTripRowDto>> TripsAsync(long id, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
await GetAsync(id, ct);
|
||||
return await repo.ClaimTripsAsync(id, page, ct);
|
||||
}
|
||||
|
||||
public Task<PagedResult<ClaimTripRowDto>> CandidateTripsAsync(IReadOnlyList<string>? statusCodes, DateOnly? from, DateOnly? to, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
// legacy searchClaimTrips: no status = the three statuses of the dialog; from after to is refused
|
||||
var statuses = WageClaimRules.NormalizeTripStatuses(statusCodes);
|
||||
if (statuses.Count == 0) statuses = WageClaimRules.ClaimableTripStatuses;
|
||||
if (from is not null && to is not null && from.Value > to.Value) throw new BusinessException("FROM_GREATER_THAN_TO", ClaimMessages.FromGreaterThanTo);
|
||||
return repo.CandidateTripsAsync(statuses, from, to, page, ct);
|
||||
}
|
||||
|
||||
public async Task<PagedResult<ClaimLogRowDto>> LogAsync(long id, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
await GetAsync(id, ct);
|
||||
return await repo.LogAsync(id, page, ct);
|
||||
}
|
||||
|
||||
/// <summary>factory.create: attaches the trips of the chosen statuses and loading dates that have no wage claim to a new NEW claim.</summary>
|
||||
public async Task<ClaimResult> CreateAsync(CreateWageClaimRequest request, string? ip, CancellationToken ct)
|
||||
{
|
||||
var statuses = WageClaimRules.NormalizeTripStatuses(request.StatusCodes);
|
||||
WageClaimRules.ValidateCreate(statuses, request.LoadingDateFrom, request.LoadingDateTo);
|
||||
var from = request.LoadingDateFrom!.Value;
|
||||
var to = request.LoadingDateTo!.Value;
|
||||
|
||||
var id = await unit.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
if (await repo.CountCandidateTripsAsync(statuses, from, to, c) == 0)
|
||||
throw new BusinessException("NO_TRIPS_NEED_WAGE", ClaimMessages.NoTripsNeedWage);
|
||||
var claimId = await repo.InsertClaimAsync(user.UserId, c);
|
||||
await repo.AttachTripsAsync(claimId, statuses, from, to, c);
|
||||
await repo.AddLogAsync(claimId, "CREATE", "{}", ClaimLogJson.Status(WageClaimRules.New), user.Id, ip, c);
|
||||
return claimId;
|
||||
}, ct);
|
||||
return new ClaimResult(ClaimMessages.Success, id);
|
||||
}
|
||||
|
||||
/// <summary>factory.CLAIM_CLOSE (تسديد, claim screen): NEW claim whose trips are all EXCHANGED -> trips COMPLETE (+ trip log), claim CLOSE (+ log).</summary>
|
||||
public async Task<ClaimResult> CloseAsync(long id, string? ip, CancellationToken ct)
|
||||
{
|
||||
var claim = await GetAsync(id, ct);
|
||||
if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority);
|
||||
await EnsureCommissionNewAsync(claim, ct);
|
||||
if (!WageClaimRules.CanCloseClaim(await repo.ClaimTripStatusesAsync(id, ct)))
|
||||
throw new BusinessException("CLOSE_CLAIM", ClaimMessages.CloseClaim);
|
||||
|
||||
await unit.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
await repo.CompleteClaimTripsAsync(id, user.UserId, user.Id, ip, c);
|
||||
await repo.SetClaimStatusAsync(id, WageClaimRules.Close, user.UserId, c);
|
||||
await repo.AddLogAsync(id, "CLAIM_CLOSE", ClaimLogJson.Status(ClaimMessages.StatusNew), ClaimLogJson.Status(ClaimMessages.StatusClose), user.Id, ip, c);
|
||||
return 0;
|
||||
}, ct);
|
||||
return new ClaimResult(ClaimMessages.Success, id);
|
||||
}
|
||||
|
||||
/// <summary>Grid status change NEW -> CLOSE: only the REFINERY_WAGE_CLAIM record (+ log); the trips keep their status.</summary>
|
||||
public async Task<ClaimResult> SetClosedAsync(long id, string? ip, CancellationToken ct)
|
||||
{
|
||||
var claim = await GetAsync(id, ct);
|
||||
if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority);
|
||||
await EnsureCommissionNewAsync(claim, ct);
|
||||
|
||||
await unit.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
await repo.SetClaimStatusAsync(id, WageClaimRules.Close, user.UserId, c);
|
||||
await repo.AddLogAsync(id, "CLAIM_CLOSE", ClaimLogJson.Status(ClaimMessages.StatusNew), ClaimLogJson.Status(ClaimMessages.StatusClose), user.Id, ip, c);
|
||||
return 0;
|
||||
}, ct);
|
||||
return new ClaimResult(ClaimMessages.Success, id);
|
||||
}
|
||||
|
||||
/// <summary>The status of a wage claim changes only when it has no commission claim or that commission claim is NEW.</summary>
|
||||
private async Task EnsureCommissionNewAsync(WageClaimRowDto claim, CancellationToken ct)
|
||||
{
|
||||
if (claim.CommissionClaimId is null) return;
|
||||
if (await repo.CommissionClaimStatusAsync(claim.CommissionClaimId.Value, ct) != WageClaimRules.New)
|
||||
throw new BusinessException("COMMISSION_NOT_NEW", ClaimMessages.CommissionNotNew);
|
||||
}
|
||||
|
||||
/// <summary>Reopen: CLOSE claim -> NEW (+ log), trips untouched. Refused when its commission claim is not NEW.</summary>
|
||||
public async Task<ClaimResult> ReopenAsync(long id, string? ip, CancellationToken ct)
|
||||
{
|
||||
var claim = await GetAsync(id, ct);
|
||||
if (claim.StatusCode != WageClaimRules.Close) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority);
|
||||
await EnsureCommissionNewAsync(claim, ct);
|
||||
|
||||
await unit.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
await repo.SetClaimStatusAsync(id, WageClaimRules.New, user.UserId, c);
|
||||
await repo.AddLogAsync(id, "CLAIM_REOPEN", ClaimLogJson.Status(ClaimMessages.StatusClose), ClaimLogJson.Status(ClaimMessages.StatusNew), user.Id, ip, c);
|
||||
return 0;
|
||||
}, ct);
|
||||
return new ClaimResult(ClaimMessages.Success, id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// factory.TRANSFER (ترحيل): each trip of the claim with TRIP_STATUS 6 is sent to Jopetrol; when the service answers "Status Updated successfully To 7"
|
||||
/// the trip gets TRIP_STATUS 7 and a TRANSFER_TO_REFINERY log row. When the integration is disabled nothing is called and nothing is changed.
|
||||
/// </summary>
|
||||
public async Task<ClaimResult> TransferAsync(long id, string? ip, CancellationToken ct)
|
||||
{
|
||||
var claim = await GetAsync(id, ct);
|
||||
if (claim.StatusCode != WageClaimRules.New) throw new BusinessException("NO_AUTHORITY", ClaimMessages.NoAuthority);
|
||||
|
||||
var trips = await repo.TripsToTransferAsync(id, ct);
|
||||
var sent = 0;
|
||||
foreach (var trip in trips)
|
||||
{
|
||||
string? answer;
|
||||
try
|
||||
{
|
||||
answer = await jopetrol.SendClaimAndUpdateStatusTo7Async(trip.Pn ?? "", claim.WageClaimNo?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "", ct);
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException or System.Xml.XmlException)
|
||||
{
|
||||
// the service is down: stop here, what was already moved stays moved
|
||||
throw new BusinessException("JOPETROL_FAILED", $"تعذر الاتصال بخدمة المصفاة، تم ترحيل {sent} من {trips.Count} ارسالية");
|
||||
}
|
||||
if (answer is null) throw new BusinessException("JOPETROL_DISABLED", ClaimMessages.JopetrolDisabled);
|
||||
if (!WageClaimRules.IsStatus7Success(answer)) continue;
|
||||
|
||||
await unit.ExecuteInTransactionAsync(async c =>
|
||||
{
|
||||
await repo.MarkTripTransferredAsync(trip, user.Id, ip, c);
|
||||
return 0;
|
||||
}, ct);
|
||||
sent++;
|
||||
}
|
||||
return new ClaimResult(sent == trips.Count ? ClaimMessages.Success : $"تم ترحيل {sent} من {trips.Count} ارسالية", id);
|
||||
}
|
||||
|
||||
/// <summary>تقرير الملخص (createCFRReport): one row of totals over the trips of the claim, in the layout of the legacy Excel file.</summary>
|
||||
public async Task<ExportFile> ExportSummaryAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var claim = await GetAsync(id, ct);
|
||||
var s = WageClaimRules.ToSummary(await repo.ReportRowsAsync(id, ct));
|
||||
static object R(decimal v) => Math.Round(v, 3, MidpointRounding.AwayFromZero); // no floating point noise in the cells
|
||||
string[] headers =
|
||||
[
|
||||
"عدد الارساليات", "كمية البوليصة كغم", "كمية الماء كغم", "كمية المصفاة كغم", "الفروقات كغم", "الكمية المحسوبة طن", "الكمية* اجرة الطن",
|
||||
"كمية التغريم كغم", "خصم قيمة فرق الكمية المغرمة", "خصم إكرامية السائق", "خصم تسريب الصهاريج", "خصم اصدار وثيقة", "خصم قيمة لتر ديزل 350",
|
||||
"خصم عمولة الصرف التنافسية", "صافي القيمة",
|
||||
];
|
||||
object?[] values =
|
||||
[
|
||||
s.TripCount, R(s.LoadingWeight), R(s.Water), R(s.DischargeWeight), R(s.Difference), R(s.CalculatedTon), R(s.QuantityWage),
|
||||
R(s.PenaltyQuantity), R(s.PenaltyAmount), R(s.DriverTip), R(s.PermitDispatch), R(s.WaybillFee), R(s.DieselAdvance), R(s.Commission), R(s.NetWage),
|
||||
];
|
||||
double[] widths = [14.56, 19.56, 19.56, 19.56, 19.56, 19.56, 19.56, 19.56, 24.67, 24.67, 24.67, 24.67, 24.67, 24.67, 14.56];
|
||||
var report = new SummaryReport(
|
||||
"شركة نافذ للخدمات اللوجستية", "خلاصة قائمة نماذج التفريغ المعدة لصرف أجور النقل حسب رقم المطالبة",
|
||||
$"رقم المطالبة :{claim.WageClaimNo}", $"رقم العطاء:{s.Tender}", $"خلال شهر:{DateTime.Now:MM/yyyy}", headers, widths, values);
|
||||
return new ExportFile(LegacyReportWorkbook.ToSummaryXlsx(report), TabularExport.XlsxContentType, $"wage_claim_summary_{claim.WageClaimNo}.xlsx");
|
||||
}
|
||||
|
||||
/// <summary>factoryweb.report: the trips of the claim with the amounts, deductions shown negative (column list of the legacy report).</summary>
|
||||
public async Task<ExportFile> ExportAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var claim = await GetAsync(id, ct);
|
||||
var lines = (await repo.ReportRowsAsync(id, ct)).Select(WageClaimRules.ToReportLine).ToList();
|
||||
string[] headers =
|
||||
[
|
||||
"متسلسل", "اسم السائق", "رقم الشاحنة", "رقم النموذج", "السنة", "تاريخ النموذج", "رقم الناقل الفرعي", "اسم الناقل الفرعي", "رقم البوليصة",
|
||||
"تاريخ البوليصة", "كمية البوليصة", "كمية الماء (كغم)", "كمية المصفاة (كغم)", "الفروقات", "الكمية المحسوبة طن", "كمية السماح", "الماء المصاحب",
|
||||
"كمية التغريم (كغم)", "سعر الطن", "خصم قيمة فرق كمية مغرمة", "اكرامية السائق", "خصم تسريب الصهريج", "خصم اصدار وثيقة", "سعر لتر دينار/لتر",
|
||||
"خصم قيمة 350 لتر ديزل", "خصم عمولة الصرف التنافسي", "صافي قيمة الصرف الفعلي",
|
||||
];
|
||||
var i = 0;
|
||||
var rows = lines.Select(l => new object?[]
|
||||
{
|
||||
++i, l.Drvr, l.Tn, l.DischargeAuthoriztionNo, l.DischargeAuthoriztionYear, ClaimExcel.D(l.DischargeEntryDate), l.ClientNo, "", l.LoadingNo,
|
||||
ClaimExcel.D(l.ActualLoadingDate), ClaimExcel.N(l.NetLoadingWeight), ClaimExcel.N(l.WaterAmount), ClaimExcel.N(l.NetDischargeWeight),
|
||||
ClaimExcel.N(l.WeightDifference), ClaimExcel.N(l.CalculatedQuantityTon), ClaimExcel.N(l.ToleranceQuantity), l.WaterExist ? "نعم" : "لا",
|
||||
ClaimExcel.N(l.PenaltyQuantity), ClaimExcel.N(l.TonPrice), ClaimExcel.N(l.PenaltyAmount), ClaimExcel.N(l.DriverTip), ClaimExcel.N(l.PermitDispatch),
|
||||
ClaimExcel.N(l.WaybillFee), ClaimExcel.N(l.DieselLiterPrice), ClaimExcel.N(l.AdvancePaymentForDiesel), ClaimExcel.N(l.Commission), ClaimExcel.N(l.NetWage),
|
||||
});
|
||||
return ClaimExcel.Build("شاشة مطالبات صرف أجور النقل",
|
||||
[$"رقم مطالبة اجور النقل : {claim.WageClaimNo}"], headers, rows, user.UserId, $"wage_claim_{claim.WageClaimNo}");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
using FluentValidation;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Refinery.Wallets;
|
||||
|
||||
public interface IWalletsRepository
|
||||
{
|
||||
/// <summary>Oldest first (legacy sort ID ASC).</summary>
|
||||
Task<PagedResult<WalletRow>> SearchAsync(WalletsQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<WalletRow?> GetAsync(long id, CancellationToken ct = default);
|
||||
/// <summary>Ids of the ACTIVE records of a truck.</summary>
|
||||
Task<IReadOnlyList<long>> GetActiveIdsByTruckAsync(long tn, CancellationToken ct = default);
|
||||
/// <summary>Ids of the ACTIVE records of a driver (national number).</summary>
|
||||
Task<IReadOnlyList<long>> GetActiveIdsByDriverAsync(long nnpn, CancellationToken ct = default);
|
||||
Task<long> InsertAsync(WalletWrite record, string createdBy, CancellationToken ct = default);
|
||||
Task SetStatusAsync(long id, string status, string userId, CancellationToken ct = default);
|
||||
Task InsertLogAsync(long entityId, string method, string userId, string? userIp, string oldData, string newData, CancellationToken ct = default);
|
||||
Task<PagedResult<WalletLogRow>> GetLogAsync(long entityId, PageRequest page, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IWalletsService
|
||||
{
|
||||
Task<PagedResult<WalletRow>> SearchAsync(WalletsQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<WalletDetail> GetAsync(long id, CancellationToken ct);
|
||||
Task<PagedResult<WalletLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct);
|
||||
Task<WalletsResult> CreateAsync(SaveWalletRequest request, string? userIp, CancellationToken ct);
|
||||
Task<WalletsResult> UpdateAsync(long id, SaveWalletRequest request, string? userIp, CancellationToken ct);
|
||||
Task<WalletsResult> ActivateAsync(long id, string? userIp, CancellationToken ct);
|
||||
Task<WalletsResult> DeactivateAsync(long id, string? userIp, CancellationToken ct);
|
||||
Task<ExportFile> ExportAsync(WalletsQuery query, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The form of REFINERY_WALLET.js: required fields per payment method, mobile / bank account / digits formats. Stricter than legacy in two places
|
||||
/// only: the truck number (WALLET, BANK) and the wallet number (WALLET, DRIVER_TIP) are required, because the duplicate rule and the payment
|
||||
/// need them (every stored record has them).
|
||||
/// </summary>
|
||||
public sealed class SaveWalletValidator : AbstractValidator<SaveWalletRequest>
|
||||
{
|
||||
public SaveWalletValidator()
|
||||
{
|
||||
RuleFor(x => x.PaymentMethod).Must(m => m is WalletValues.MethodWallet or WalletValues.MethodBank or WalletValues.MethodDriverTip)
|
||||
.WithMessage(WalletsMessages.Required);
|
||||
|
||||
When(x => x.PaymentMethod is WalletValues.MethodWallet or WalletValues.MethodBank, () =>
|
||||
{
|
||||
RuleFor(x => x.Tn).Must(v => WalletsRules.IsDigits(v?.Trim(), 10)).WithMessage(WalletsMessages.Required);
|
||||
RuleFor(x => x.OwnerName).NotEmpty().MaximumLength(450).WithMessage(WalletsMessages.Required);
|
||||
RuleFor(x => x.OwnerNnpn).Must(v => string.IsNullOrWhiteSpace(v) || WalletsRules.IsDigits(v.Trim(), 15)).WithMessage(WalletsMessages.NumbersOnly);
|
||||
});
|
||||
|
||||
When(x => x.PaymentMethod == WalletValues.MethodWallet, () =>
|
||||
{
|
||||
RuleFor(x => x.WalletNumber).NotEmpty().WithMessage(WalletsMessages.Required)
|
||||
.Must(v => WalletsRules.IsMobile(v?.Trim())).WithMessage(WalletsMessages.WrongMobile);
|
||||
});
|
||||
|
||||
When(x => x.PaymentMethod == WalletValues.MethodBank, () =>
|
||||
{
|
||||
RuleFor(x => x.Iban).NotEmpty().MaximumLength(50).WithMessage(WalletsMessages.Required);
|
||||
RuleFor(x => x.BankAccount).NotEmpty().MaximumLength(50).WithMessage(WalletsMessages.Required)
|
||||
.Must(v => WalletsRules.IsBankAccount(v?.Trim())).WithMessage(WalletsMessages.WrongBankAccount);
|
||||
RuleFor(x => x.BankName).MaximumLength(300);
|
||||
RuleFor(x => x.BankBranch).MaximumLength(50);
|
||||
RuleFor(x => x.OwnerNameEnglish).MaximumLength(150);
|
||||
});
|
||||
|
||||
When(x => x.PaymentMethod == WalletValues.MethodDriverTip, () =>
|
||||
{
|
||||
RuleFor(x => x.DriverName).NotEmpty().MaximumLength(450).WithMessage(WalletsMessages.Required);
|
||||
RuleFor(x => x.DriverNnpn).Must(v => WalletsRules.IsDigits(v?.Trim(), 15)).WithMessage(WalletsMessages.Required);
|
||||
RuleFor(x => x.WalletNumber).NotEmpty().WithMessage(WalletsMessages.Required)
|
||||
.Must(v => WalletsRules.IsMobile(v?.Trim())).WithMessage(WalletsMessages.WrongMobile);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
namespace NTP.Application.Refinery.Wallets;
|
||||
|
||||
/// <summary>
|
||||
/// Row of REFINERY_WALLET: how a truck owner (or a driver, for the tip) gets paid: e-wallet, bank transfer or driver wallet. Same columns as the legacy
|
||||
/// REFINERY_WALLET_VIEW (OwnerNnpn / OwnerName fall back to the driver's when the owner's are empty). Class with settable properties.
|
||||
/// </summary>
|
||||
public class WalletRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long? Tn { get; set; }
|
||||
public long? CompanyCode { get; set; }
|
||||
/// <summary>0 = bank transfer, 1 = e-wallet (also the driver wallet). Legacy EPAYMENT.</summary>
|
||||
public int Epayment { get; set; }
|
||||
/// <summary>Stored OWNER_NNPN (empty for a driver wallet).</summary>
|
||||
public long? OwnerNnpn { get; set; }
|
||||
public string? WalletNumber { get; set; }
|
||||
/// <summary>Stored OWNER_NAME (empty for a driver wallet).</summary>
|
||||
public string? OwnerName { get; set; }
|
||||
/// <summary>What the legacy grid shows as national no.: the owner's, else the driver's (view column OWNER_NNPN / NNPN).</summary>
|
||||
public long? HolderNnpn { get; set; }
|
||||
/// <summary>What the legacy grid shows as owner name: the owner's, else the driver's (view column OWNER_NAME).</summary>
|
||||
public string? HolderName { get; set; }
|
||||
public string? OwnerNameEnglish { get; set; }
|
||||
public string? DriverName { get; set; }
|
||||
public long? DriverNnpn { get; set; }
|
||||
public string? Iban { get; set; }
|
||||
public string? BankAccount { get; set; }
|
||||
public string? BankName { get; set; }
|
||||
public string? BankBranch { get; set; }
|
||||
public DateTime? CreationDate { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTime? UpdateDate { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
public string? StatusCode { get; set; }
|
||||
/// <summary>BANK, EWALLET or DRAIVER_WALLET (legacy view spelling): the kind of the record, see <see cref="WalletValues"/>.</summary>
|
||||
public string? PaymentMethod { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One record plus what may be done with it.</summary>
|
||||
public sealed class WalletDetail : WalletRow
|
||||
{
|
||||
/// <summary>ACTIVE record: edit (deactivates it and creates a new one).</summary>
|
||||
public bool CanUpdate { get; set; }
|
||||
public bool CanDeactivate { get; set; }
|
||||
/// <summary>INACTIVE record and the truck / driver has no other ACTIVE record (legacy getREFINERY_WALLET sets ACTIONS = ACTIVATE).</summary>
|
||||
public bool CanActivate { get; set; }
|
||||
}
|
||||
|
||||
public class WalletLogRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public long EntityId { get; set; }
|
||||
public string? MethodName { get; set; }
|
||||
public string? Login { get; set; }
|
||||
public DateTime? LogDate { get; set; }
|
||||
public string? UserId { get; set; }
|
||||
public string? UserIp { get; set; }
|
||||
/// <summary>JSON text (property name -> value); legacy rows may hold one-element arrays as values.</summary>
|
||||
public string? OldData { get; set; }
|
||||
public string? NewData { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Grid filters: tn, walletNumber, bankAccount, nnpn, paymentMethod, statusCode exact; ownerName contains.</summary>
|
||||
public sealed record WalletsQuery(string? Tn, string? WalletNumber, string? OwnerName, string? BankAccount, string? PaymentMethod, string? StatusCode, string? Nnpn);
|
||||
|
||||
/// <summary>
|
||||
/// Create / update body. <see cref="PaymentMethod"/> WALLET (e-wallet of a truck), BANK (bank transfer of a truck) or DRIVER_TIP (driver wallet).
|
||||
/// Fields not used by the chosen method are ignored. Numbers travel as text (digits only).
|
||||
/// </summary>
|
||||
public sealed class SaveWalletRequest
|
||||
{
|
||||
public string? PaymentMethod { get; set; }
|
||||
/// <summary>WALLET / BANK: truck number.</summary>
|
||||
public string? Tn { get; set; }
|
||||
/// <summary>WALLET / BANK: national number of the owner (optional).</summary>
|
||||
public string? OwnerNnpn { get; set; }
|
||||
/// <summary>WALLET / DRIVER_TIP: mobile number of the wallet (07xxxxxxxx or 7xxxxxxxx, 77/78/79).</summary>
|
||||
public string? WalletNumber { get; set; }
|
||||
/// <summary>WALLET / BANK: account owner.</summary>
|
||||
public string? OwnerName { get; set; }
|
||||
public string? OwnerNameEnglish { get; set; }
|
||||
public string? BankName { get; set; }
|
||||
public string? BankBranch { get; set; }
|
||||
public string? Iban { get; set; }
|
||||
public string? BankAccount { get; set; }
|
||||
/// <summary>DRIVER_TIP.</summary>
|
||||
public string? DriverName { get; set; }
|
||||
public string? DriverNnpn { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Normalised record to insert (what the legacy factory builds into the bean per payment method).</summary>
|
||||
public sealed record WalletWrite(
|
||||
int Epayment, long? Tn, long? OwnerNnpn, string? WalletNumber, string? OwnerName, string? OwnerNameEnglish,
|
||||
long? DriverNnpn, string? DriverName, string? Iban, string? BankAccount, string? BankName, string? BankBranch);
|
||||
|
||||
public sealed record WalletsResult(string Message, long? Id = null);
|
||||
|
||||
public static class WalletValues
|
||||
{
|
||||
public const string Active = "ACTIVE";
|
||||
public const string Inactive = "INACTIVE";
|
||||
|
||||
// request codes (the select of the legacy form)
|
||||
public const string MethodWallet = "WALLET";
|
||||
public const string MethodBank = "BANK";
|
||||
public const string MethodDriverTip = "DRIVER_TIP";
|
||||
|
||||
// kinds of a stored record (legacy REFINERY_WALLET_VIEW.PAYMENT_METHOD, spelling kept)
|
||||
public const string KindBank = "BANK";
|
||||
public const string KindEWallet = "EWALLET";
|
||||
public const string KindDriverWallet = "DRAIVER_WALLET";
|
||||
|
||||
// log METHOD_NAME values
|
||||
public const string LogCreate = "CREATE";
|
||||
public const string LogUpdate = "UPDATE";
|
||||
public const string LogActivate = "ACTIVATE";
|
||||
public const string LogDeactivate = "DEACTIVATE";
|
||||
}
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace NTP.Application.Refinery.Wallets;
|
||||
|
||||
/// <summary>User-facing texts (legacy captions verbatim; * = no row in LT_CAPTION, new wording).</summary>
|
||||
public static class WalletsMessages
|
||||
{
|
||||
public const string Required = "الرجاء ادخال جميع الحقول"; // REPORT.VALIDATION
|
||||
public const string WrongMobile = "رقم المحفظة غير صحيح"; // PUBLIC.WRONG_MOBILE_NUMBER
|
||||
public const string WrongBankAccount = "رقم الحساب غير صحيح مسموح بالارقام والاحرف وال / فقط"; // VAILD.LETTERS_NYMBERS_SLASH_ONLY
|
||||
public const string NumbersOnly = "الحقل لا يقبل أحرف"; // PUBLIC.NUMBERSONLY
|
||||
public const string TruckHasActive = "رقم الشاحنة المدخل له آلية صرف فعالة"; // TRUCK_ALREADY_HAS_ACTIVE_RECORD
|
||||
public const string DriverHasActive = "الرقم الوطني المدخل له آلية صرف فعالة"; // DRIVER_ALREADY_HAS_ACTIVE_RECORD
|
||||
public const string NotFound = "آلية الصرف غير موجودة"; // *
|
||||
public const string StatusNotAllowed = "لا يمكن تنفيذ هذا الإجراء على السجل في حالته الحالية"; // * (legacy: STATUS_ACTION_MATRIX refusal)
|
||||
public const string Done = "";
|
||||
}
|
||||
|
||||
public static class WalletsErrors
|
||||
{
|
||||
public const string TruckHasActive = "TRUCK_ALREADY_HAS_ACTIVE_RECORD";
|
||||
public const string DriverHasActive = "DRIVER_ALREADY_HAS_ACTIVE_RECORD";
|
||||
public const string NotFound = "REFINERY_WALLET_NOT_FOUND";
|
||||
public const string StatusNotAllowed = "REFINERY_WALLET_STATUS_NOT_ALLOWED";
|
||||
}
|
||||
|
||||
/// <summary>Pure rules of refinery_walletfactory.cfc and the checks of REFINERY_WALLET.js.</summary>
|
||||
public static partial class WalletsRules
|
||||
{
|
||||
// REFINERY_WALLET.js createRefineryWallet: ^(07){1}[7-9]{1}[0-9]{7}$ or ^(7){1}[7-9]{1}[0-9]{7}$
|
||||
[GeneratedRegex(@"^0?7[7-9][0-9]{7}$")]
|
||||
private static partial Regex MobileRegex();
|
||||
// ^[//a-zA-Z 0-9]*$
|
||||
[GeneratedRegex(@"^[/a-zA-Z 0-9]*$")]
|
||||
private static partial Regex BankAccountRegex();
|
||||
[GeneratedRegex(@"^\d+$")]
|
||||
private static partial Regex DigitsRegex();
|
||||
|
||||
public static bool IsMobile(string? v) => v is not null && MobileRegex().IsMatch(v);
|
||||
public static bool IsBankAccount(string? v) => v is not null && BankAccountRegex().IsMatch(v);
|
||||
public static bool IsDigits(string? v, int max) => v is not null && v.Length <= max && DigitsRegex().IsMatch(v);
|
||||
|
||||
private static string? Clean(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim();
|
||||
private static long? ToLong(string? v) => Clean(v) is { } s && long.TryParse(s, out var n) ? n : null;
|
||||
|
||||
/// <summary>
|
||||
/// What the legacy factory copies into the bean for each payment method (refinery_walletfactory.cfc:67-95): BANK = EPAYMENT 0 with the
|
||||
/// bank data; WALLET = EPAYMENT 1 with the wallet number; DRIVER_TIP = EPAYMENT 1, driver data only, no truck. Fields that belong to another
|
||||
/// method are dropped (the DB defaults then give '-' for IBAN, BANK_ACCOUNT and BANK_NAME).
|
||||
/// </summary>
|
||||
public static WalletWrite ToWrite(SaveWalletRequest r) => r.PaymentMethod switch
|
||||
{
|
||||
WalletValues.MethodBank => new WalletWrite(0, ToLong(r.Tn), ToLong(r.OwnerNnpn), null, Clean(r.OwnerName), Clean(r.OwnerNameEnglish),
|
||||
null, null, Clean(r.Iban), Clean(r.BankAccount), Clean(r.BankName), Clean(r.BankBranch)),
|
||||
WalletValues.MethodWallet => new WalletWrite(1, ToLong(r.Tn), ToLong(r.OwnerNnpn), Clean(r.WalletNumber), Clean(r.OwnerName), null,
|
||||
null, null, null, null, null, null),
|
||||
_ => new WalletWrite(1, null, null, Clean(r.WalletNumber), null, null, ToLong(r.DriverNnpn), Clean(r.DriverName), null, null, null, null),
|
||||
};
|
||||
|
||||
/// <summary>The payment method code of the form for a stored record (a bank record has EPAYMENT 0, a driver record has no truck).</summary>
|
||||
public static string MethodOf(WalletRow w) =>
|
||||
w.Epayment == 0 ? WalletValues.MethodBank : w.Tn is null && w.DriverNnpn is not null ? WalletValues.MethodDriverTip : WalletValues.MethodWallet;
|
||||
|
||||
// ------------------------------------------------------------------ log JSON (aqabaTCSBCommon.logs.saveLog)
|
||||
|
||||
private static readonly JsonSerializerOptions Json = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
|
||||
|
||||
public static string ToJson(IReadOnlyDictionary<string, string> values) => JsonSerializer.Serialize(values, Json);
|
||||
|
||||
public static string EmptyJson => "{}";
|
||||
|
||||
/// <summary>CREATE log of a new record (legacy: only {"STATUS_CODE":"ACTIVE"} when created from the form).</summary>
|
||||
public static string CreateNewData() => ToJson(new Dictionary<string, string> { ["STATUS_CODE"] = "ACTIVE" });
|
||||
|
||||
/// <summary>
|
||||
/// CREATE log of the record that replaces an updated one: the whole bean (system columns empty, as legacy), keys upper-case.
|
||||
/// </summary>
|
||||
public static string ReplacementNewData(WalletWrite w, string createdBy) => ToJson(new Dictionary<string, string>
|
||||
{
|
||||
["TN"] = w.Tn?.ToString() ?? "", ["COMPANY_CODE"] = "", ["EPAYMENT"] = w.Epayment.ToString(),
|
||||
["OWNER_NNPN"] = w.OwnerNnpn?.ToString() ?? "", ["WALLET_NUMBER"] = w.WalletNumber ?? "", ["OWNER_NAME"] = w.OwnerName ?? "",
|
||||
["CREATION_DATE"] = "", ["DRIVER_NAME"] = w.DriverName ?? "", ["DRIVER_NNPN"] = w.DriverNnpn?.ToString() ?? "",
|
||||
["IBAN"] = w.Iban ?? "-", ["BANK_ACCOUNT"] = w.BankAccount ?? "-", ["BANK_NAME"] = w.BankName ?? "-", ["CREATED_BY"] = createdBy,
|
||||
["UPDATE_DATE"] = "", ["UPDATED_BY"] = "", ["STATUS_CODE"] = "", ["BANK_BRANCH"] = w.BankBranch ?? "",
|
||||
["OWNER_NAME_ENGLISH"] = w.OwnerNameEnglish ?? "",
|
||||
});
|
||||
|
||||
/// <summary>The data columns the UPDATE log compares (legacy: the bean columns that also exist in the old record, minus system columns).</summary>
|
||||
public static IReadOnlyDictionary<string, string> DataColumns(WalletRow w) => new Dictionary<string, string>
|
||||
{
|
||||
["TN"] = w.Tn?.ToString() ?? "", ["EPAYMENT"] = w.Epayment.ToString(),
|
||||
["OWNER_NNPN"] = w.OwnerNnpn?.ToString() ?? "", ["WALLET_NUMBER"] = w.WalletNumber ?? "", ["OWNER_NAME"] = w.OwnerName ?? "",
|
||||
["DRIVER_NAME"] = w.DriverName ?? "", ["DRIVER_NNPN"] = w.DriverNnpn?.ToString() ?? "",
|
||||
["IBAN"] = w.Iban ?? "", ["BANK_ACCOUNT"] = w.BankAccount ?? "", ["BANK_NAME"] = w.BankName ?? "",
|
||||
["BANK_BRANCH"] = w.BankBranch ?? "", ["OWNER_NAME_ENGLISH"] = w.OwnerNameEnglish ?? "",
|
||||
};
|
||||
|
||||
public static IReadOnlyDictionary<string, string> DataColumns(WalletWrite w) => new Dictionary<string, string>
|
||||
{
|
||||
["TN"] = w.Tn?.ToString() ?? "", ["EPAYMENT"] = w.Epayment.ToString(),
|
||||
["OWNER_NNPN"] = w.OwnerNnpn?.ToString() ?? "", ["WALLET_NUMBER"] = w.WalletNumber ?? "", ["OWNER_NAME"] = w.OwnerName ?? "",
|
||||
["DRIVER_NAME"] = w.DriverName ?? "", ["DRIVER_NNPN"] = w.DriverNnpn?.ToString() ?? "",
|
||||
["IBAN"] = w.Iban ?? "-", ["BANK_ACCOUNT"] = w.BankAccount ?? "-", ["BANK_NAME"] = w.BankName ?? "-",
|
||||
["BANK_BRANCH"] = w.BankBranch ?? "", ["OWNER_NAME_ENGLISH"] = w.OwnerNameEnglish ?? "",
|
||||
};
|
||||
|
||||
/// <summary>UPDATE log of the replaced record: only the columns whose value changed, old and new (null when nothing changed).</summary>
|
||||
public static (string OldData, string NewData)? Diff(WalletRow old, WalletWrite updated)
|
||||
{
|
||||
var before = DataColumns(old);
|
||||
var after = DataColumns(updated);
|
||||
var o = new Dictionary<string, string>();
|
||||
var n = new Dictionary<string, string>();
|
||||
foreach (var (key, b) in before)
|
||||
if (!string.Equals(b, after[key], StringComparison.OrdinalIgnoreCase)) { o[key] = b; n[key] = after[key]; }
|
||||
return o.Count == 0 ? null : (ToJson(o), ToJson(n));
|
||||
}
|
||||
|
||||
/// <summary>Caption of REFINERY_WALLET.STATUSCODE.* (logs.saveLog translates STATUS_CODE).</summary>
|
||||
public static string StatusCaption(string status) =>
|
||||
string.Equals(status, WalletValues.Active, StringComparison.OrdinalIgnoreCase) ? "فعال" : "غير فعال";
|
||||
|
||||
/// <summary>Status change log: old and new caption of STATUS_CODE.</summary>
|
||||
public static (string OldData, string NewData) StatusChange(string from, string to) =>
|
||||
(ToJson(new Dictionary<string, string> { ["STATUS_CODE"] = StatusCaption(from) }),
|
||||
ToJson(new Dictionary<string, string> { ["STATUS_CODE"] = StatusCaption(to) }));
|
||||
}
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
using FluentValidation;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Grains.Orders;
|
||||
using NTP.Application.Grains.Reports;
|
||||
|
||||
namespace NTP.Application.Refinery.Wallets;
|
||||
|
||||
/// <summary>
|
||||
/// Port of refinery_walletfactory.cfc / refinery_walletfactoryweb.cfc (screen REFINERY_WALLET, شاشة طرق الدفع). Access by permission keys only
|
||||
/// (legacy REFINERY_MGR / REFINERY_AC branches not ported). CREATED_BY / UPDATED_BY and the log USER_ID are the numeric NTPUSERS id
|
||||
/// (legacy session.userrecordid), the log USER_IP the caller's address. The Dinarak API is not called from here.
|
||||
/// </summary>
|
||||
public sealed class WalletsService(
|
||||
IWalletsRepository repository,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user,
|
||||
IReportExcelService excel,
|
||||
IValidator<SaveWalletRequest> validator) : IWalletsService
|
||||
{
|
||||
private string Me => user.Id.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
public Task<PagedResult<WalletRow>> SearchAsync(WalletsQuery query, PageRequest page, CancellationToken ct) =>
|
||||
repository.SearchAsync(query, page, ct);
|
||||
|
||||
public async Task<WalletDetail> GetAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var w = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id);
|
||||
var active = string.Equals(w.StatusCode, WalletValues.Active, StringComparison.OrdinalIgnoreCase);
|
||||
var canActivate = false;
|
||||
if (!active)
|
||||
canActivate = (await ActiveIdsOfSameOwnerAsync(w.Tn, w.DriverNnpn, ct)).Count == 0;
|
||||
return new WalletDetail
|
||||
{
|
||||
Id = w.Id, Tn = w.Tn, CompanyCode = w.CompanyCode, Epayment = w.Epayment, OwnerNnpn = w.OwnerNnpn, WalletNumber = w.WalletNumber,
|
||||
OwnerName = w.OwnerName, HolderNnpn = w.HolderNnpn, HolderName = w.HolderName, OwnerNameEnglish = w.OwnerNameEnglish, DriverName = w.DriverName, DriverNnpn = w.DriverNnpn, Iban = w.Iban,
|
||||
BankAccount = w.BankAccount, BankName = w.BankName, BankBranch = w.BankBranch, CreationDate = w.CreationDate, CreatedBy = w.CreatedBy,
|
||||
UpdateDate = w.UpdateDate, UpdatedBy = w.UpdatedBy, StatusCode = w.StatusCode, PaymentMethod = w.PaymentMethod,
|
||||
CanUpdate = active, CanDeactivate = active, CanActivate = canActivate,
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<PagedResult<WalletLogRow>> GetLogAsync(long id, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
_ = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id);
|
||||
return await repository.GetLogAsync(id, page, ct);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<long>> ActiveIdsOfSameOwnerAsync(long? tn, long? driverNnpn, CancellationToken ct) =>
|
||||
tn is not null ? await repository.GetActiveIdsByTruckAsync(tn.Value, ct)
|
||||
: driverNnpn is not null ? await repository.GetActiveIdsByDriverAsync(driverNnpn.Value, ct)
|
||||
: [];
|
||||
|
||||
/// <summary>refinery_walletfactory.cfc:100-117 / 188-203: a truck and a driver have one ACTIVE record each.</summary>
|
||||
private async Task EnsureNoOtherActiveAsync(WalletWrite w, long? exceptId, CancellationToken ct)
|
||||
{
|
||||
if (w.Tn is not null && (await repository.GetActiveIdsByTruckAsync(w.Tn.Value, ct)).Any(i => i != exceptId))
|
||||
throw new BusinessException(WalletsErrors.TruckHasActive, WalletsMessages.TruckHasActive);
|
||||
if (w.DriverNnpn is not null && (await repository.GetActiveIdsByDriverAsync(w.DriverNnpn.Value, ct)).Any(i => i != exceptId))
|
||||
throw new BusinessException(WalletsErrors.DriverHasActive, WalletsMessages.DriverHasActive);
|
||||
}
|
||||
|
||||
public async Task<WalletsResult> CreateAsync(SaveWalletRequest request, string? userIp, CancellationToken ct)
|
||||
{
|
||||
await validator.ValidateAndThrowAsync(request, ct);
|
||||
var record = WalletsRules.ToWrite(request);
|
||||
await EnsureNoOtherActiveAsync(record, null, ct);
|
||||
|
||||
var id = await unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
var newId = await repository.InsertAsync(record, Me, token);
|
||||
await repository.InsertLogAsync(newId, WalletValues.LogCreate, Me, userIp, WalletsRules.EmptyJson, WalletsRules.CreateNewData(), token);
|
||||
return newId;
|
||||
}, ct);
|
||||
return new WalletsResult(WalletsMessages.Done, id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Legacy update keeps the history: the record is set INACTIVE and a new ACTIVE record with the new data is inserted (two log rows:
|
||||
/// CREATE on the new id, UPDATE with the changed columns on the old id). The payment method of a record cannot change (the select is disabled).
|
||||
/// </summary>
|
||||
public async Task<WalletsResult> UpdateAsync(long id, SaveWalletRequest request, string? userIp, CancellationToken ct)
|
||||
{
|
||||
var old = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id);
|
||||
if (!string.Equals(old.StatusCode, WalletValues.Active, StringComparison.OrdinalIgnoreCase))
|
||||
throw new BusinessException(WalletsErrors.StatusNotAllowed, WalletsMessages.StatusNotAllowed);
|
||||
request.PaymentMethod = WalletsRules.MethodOf(old);
|
||||
await validator.ValidateAndThrowAsync(request, ct);
|
||||
var record = WalletsRules.ToWrite(request);
|
||||
await EnsureNoOtherActiveAsync(record, id, ct);
|
||||
|
||||
var newId = await unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await repository.SetStatusAsync(id, WalletValues.Inactive, Me, token);
|
||||
var created = await repository.InsertAsync(record, Me, token);
|
||||
await repository.InsertLogAsync(created, WalletValues.LogCreate, Me, userIp, WalletsRules.EmptyJson, WalletsRules.ReplacementNewData(record, Me), token);
|
||||
if (WalletsRules.Diff(old, record) is { } diff)
|
||||
await repository.InsertLogAsync(id, WalletValues.LogUpdate, Me, userIp, diff.OldData, diff.NewData, token);
|
||||
return created;
|
||||
}, ct);
|
||||
return new WalletsResult(WalletsMessages.Done, newId);
|
||||
}
|
||||
|
||||
public async Task<WalletsResult> ActivateAsync(long id, string? userIp, CancellationToken ct)
|
||||
{
|
||||
var w = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id);
|
||||
// STATUS_ACTION_MATRIX: CHSTAT only INACTIVE -> ACTIVE
|
||||
if (!string.Equals(w.StatusCode, WalletValues.Inactive, StringComparison.OrdinalIgnoreCase))
|
||||
throw new BusinessException(WalletsErrors.StatusNotAllowed, WalletsMessages.StatusNotAllowed);
|
||||
// refinery_walletfactory.cfc:296-306: no other ACTIVE record for the same truck (or driver when there is no truck)
|
||||
if ((await ActiveIdsOfSameOwnerAsync(w.Tn, w.DriverNnpn, ct)).Count > 0)
|
||||
throw w.Tn is not null
|
||||
? new BusinessException(WalletsErrors.TruckHasActive, WalletsMessages.TruckHasActive)
|
||||
: new BusinessException(WalletsErrors.DriverHasActive, WalletsMessages.DriverHasActive);
|
||||
await ChangeStatusAsync(id, WalletValues.Inactive, WalletValues.Active, WalletValues.LogActivate, userIp, ct);
|
||||
return new WalletsResult(WalletsMessages.Done, id);
|
||||
}
|
||||
|
||||
public async Task<WalletsResult> DeactivateAsync(long id, string? userIp, CancellationToken ct)
|
||||
{
|
||||
var w = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Refinery wallet", id);
|
||||
// STATUS_ACTION_MATRIX: DEACTIVATE only from ACTIVE
|
||||
if (!string.Equals(w.StatusCode, WalletValues.Active, StringComparison.OrdinalIgnoreCase))
|
||||
throw new BusinessException(WalletsErrors.StatusNotAllowed, WalletsMessages.StatusNotAllowed);
|
||||
await ChangeStatusAsync(id, WalletValues.Active, WalletValues.Inactive, WalletValues.LogDeactivate, userIp, ct);
|
||||
return new WalletsResult(WalletsMessages.Done, id);
|
||||
}
|
||||
|
||||
private Task ChangeStatusAsync(long id, string from, string to, string method, string? userIp, CancellationToken ct) =>
|
||||
unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await repository.SetStatusAsync(id, to, Me, token);
|
||||
var (o, n) = WalletsRules.StatusChange(from, to);
|
||||
await repository.InsertLogAsync(id, method, Me, userIp, o, n, token);
|
||||
return true;
|
||||
}, ct);
|
||||
|
||||
public async Task<ExportFile> ExportAsync(WalletsQuery query, CancellationToken ct)
|
||||
{
|
||||
var rows = new List<WalletRow>();
|
||||
for (var p = 1; rows.Count < 20000; p++)
|
||||
{
|
||||
var r = await repository.SearchAsync(query, new PageRequest(p, PageRequest.MaxPageSize), ct);
|
||||
rows.AddRange(r.Items);
|
||||
if (r.Items.Count == 0 || rows.Count >= r.TotalCount) break;
|
||||
}
|
||||
// legacy report columns: counter, TN, payment method, owner national no., owner name, wallet no., IBAN, bank account, bank name, status
|
||||
var cols = new List<ReportColumn>
|
||||
{
|
||||
new("counter", "متسلسل", "#"), new("tn", "رقم الشاحنة", "Truck"), new("paymentMethod", "طريقة الدفع", "Payment method"),
|
||||
new("ownerNnpn", "الرقم الوطني للمالك", "Owner national no."), new("ownerName", "اسم المالك", "Owner name"),
|
||||
new("walletNumber", "رقم المحفظة", "Wallet number"), new("iban", "IBAN", "IBAN"), new("bankAccount", "رقم الحساب", "Bank account"),
|
||||
new("bankName", "اسم البنك", "Bank name"), new("status", "الحالة", "Status"),
|
||||
};
|
||||
var n = 0;
|
||||
var data = rows.Select(r => (IReadOnlyDictionary<string, object?>)new Dictionary<string, object?>
|
||||
{
|
||||
["counter"] = ++n, ["tn"] = r.Tn, ["paymentMethod"] = KindCaption(r.PaymentMethod), ["ownerNnpn"] = r.HolderNnpn,
|
||||
["ownerName"] = r.HolderName, ["walletNumber"] = r.WalletNumber, ["iban"] = r.Iban, ["bankAccount"] = r.BankAccount,
|
||||
["bankName"] = r.BankName, ["status"] = WalletsRules.StatusCaption(r.StatusCode ?? string.Empty),
|
||||
}).ToList();
|
||||
var table = new ReportTable { Key = "REFINERY_WALLET", TitleAr = "شاشة طرق الدفع", TitleEn = "Payment methods", Columns = cols, Rows = data };
|
||||
return new ExportFile(excel.Build(table, user.UserId, DateTime.Now, true),
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "REFINERY_WALLET.xlsx");
|
||||
}
|
||||
|
||||
/// <summary>Captions REFINERY_WALLET.BANK / EWALLET / DRAIVER_WALLET.</summary>
|
||||
public static string KindCaption(string? kind) => kind switch
|
||||
{
|
||||
WalletValues.KindBank => "حوالة بنكية",
|
||||
WalletValues.KindEWallet => "محفظة الالكترونية",
|
||||
WalletValues.KindDriverWallet => "محفظة سائق",
|
||||
_ => kind ?? string.Empty,
|
||||
};
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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();
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue