Compare commits
No commits in common. "main" and "live_old_version_11" have entirely different histories.
main
...
live_old_v
63
CLAUDE.md
63
CLAUDE.md
|
|
@ -1,63 +0,0 @@
|
|||
# NTP V2: instructions for Claude Code
|
||||
|
||||
.NET 10 API + React web app that replace the legacy ColdFusion "NTP" system (Aqaba; the **Grains / حبوب** modules are the active work).
|
||||
The legacy system is the specification: when behaviour is unclear, read the legacy code and match it. Current state, open decisions and
|
||||
deployment checklists are in **docs/HANDOVER.md** (read it first in a new session). Environments: docs/ENVIRONMENTS.md. Porting
|
||||
conventions: docs/MIGRATION.md. Table definitions: docs/schema/NTP.md and NAFITHTCS.md. Stack rationale: README.md.
|
||||
|
||||
## Layout
|
||||
- `src/NTP.Api` controllers (thin), error mapping (`GlobalExceptionHandler`), auth, versioning
|
||||
- `src/NTP.Application` services, contracts, validators (FluentValidation), repository interfaces, permission keys/defaults
|
||||
- `src/NTP.Infrastructure` Oracle + Dapper repositories (raw SQL), gateways (TCS, IVR, notifications), file store
|
||||
- `src/NTP.Domain` entities and rules; `tests/NTP.Tests` xUnit (283 tests at hand-over)
|
||||
- `web/src/features/grains-{orders,permits,registry,reports}` screens (metadata-driven DataGrid / MetaForm in `web/src/components`), `web/src/shell` menu, header, home
|
||||
- `src/NTP.*/Jobs` + `web/src/features/jobs` scheduled jobs (SU screen `/jobs`; catalog in `JobCatalog`; tables from `db/grains-jobs.sql`)
|
||||
- `db/*.sql` one-off permission / role scripts (run by hand per environment, not by the app); `deploy/` Docker + Jenkins (see `Jenkinsfile`)
|
||||
|
||||
## Commands (Windows; Git Bash or PowerShell)
|
||||
- Needs the **.NET 10 SDK** (`dotnet --list-sdks`). On the previous machine PATH pointed to SDK 9, so a local SDK 10 folder was used explicitly.
|
||||
- Build: `dotnet build src/NTP.Api` - Tests: `dotnet test tests/NTP.Tests` - Web type check: `cd web && npx tsc -b --noEmit`
|
||||
- **Stop the running API before building** (otherwise MSB3248 "file is being used"; a failed build then silently leaves the old DLLs). Wait a few seconds after stopping.
|
||||
- Run: API `https://localhost:7180` (profile `https`), web `npm run dev` in `web/` (http://localhost:5173, proxies /api). Local DB settings go in
|
||||
`src/NTP.Api/appsettings.Local.json` (git-ignored, copy `appsettings.Local.example.json`): `ConnectionStrings:NAFITHTCS` and `ConnectionStrings:NtpSchema`.
|
||||
- `.claude/` is git-ignored, so recreate `.claude/launch.json` for the preview tools:
|
||||
`{"version":"0.0.1","configurations":[{"name":"api","runtimeExecutable":"dotnet","runtimeArgs":["run","--project","<repo>/src/NTP.Api","--launch-profile","https","--no-build"],"port":7180,"url":"https://localhost:7180"},{"name":"web","runtimeExecutable":"npm","runtimeArgs":["run","dev","--prefix","<repo>/web"],"port":5173}]}`
|
||||
(`--no-build`: always build first).
|
||||
- Never print `appsettings.Local.json` or any connection string (it holds real database passwords).
|
||||
- Shell quoting: backslashes inside regexes get lost in heredocs / `node -e`. For code with regexes write a script file or use the Edit tool, then compile.
|
||||
|
||||
## Legacy references (read-only, never edit; paths are per machine, ask for a copy if missing)
|
||||
- `C:\inetpub\wwwroot\NTP_LIVE` legacy app: `services\Grains\cfc\grains.cfc` (6.2k lines: permits, queue, distribution, weighbridge, blacklist), `register.cfc` (trucks / trailers / drivers),
|
||||
`autoCallResponse.cfc` (IVR callback), `GrainsFactoryWeb.cfc`, `customtags\menu.cfm` (menu roles), `services\Grains\*.cfm` (screens), `components\` (common helpers)
|
||||
- `C:\inetpub\wwwroot\AqabaTCS_LIVE\IVR\callivr.cfc` IVR web service (SOAP `callAPI` dials every REQST truck); that app's `Application.cfc` base64-decodes URL parameters
|
||||
- `C:\inetpub\wwwroot\mams` reference project for the look and feel (palette, Cairo font, grids)
|
||||
- Legacy gates screens with `application.objAuth.isActAuthorized(<id>, session.lstGID)`. The id->group mapping is in the database (`GROUP_ACTIONS` + `GROUPS` + `ACTIONS`, NTP schema):
|
||||
72 register turn, 73 submit, 74 accept, 77 edit, 85 reject, 88 cancel confirmation, 93 phone confirm, 94 distribute, 96 voice-call/report, 100/101 print, 106 cancel order,
|
||||
107 destinations, 167 cancel permit, 66-71 registry accept / revoke
|
||||
|
||||
## Rules of the code base
|
||||
- **Oracle 11.2** (ODP.NET 3.21.x pinned): no OFFSET/FETCH or identity; page with ROWNUM (`OracleSql.Paginate`). Dapper, not EF.
|
||||
- Dapper maps a positional record badly with Oracle NUMBER (decimal vs long): use classes with settable properties for query results.
|
||||
- ODP.NET binds by name: a parameter added to `DynamicParameters` that the SQL text does not use fails with **ORA-01006** (anonymous objects are filtered, DynamicParameters are not).
|
||||
- Do not wrap indexed number columns in `TO_CHAR(...)` in new SQL (it kills the index); bind a number. Several old queries still do.
|
||||
- Services register by convention (`*Service` / `*Repository` against `I{Name}`, scoped). Two connections: `IDbSession` = primary NAFITHTCS, `INtpDbSession` = NTP schema; transactions are per connection.
|
||||
- Errors: throw `BusinessException` (422), `ForbiddenException` (403), `NotFoundException` (404), FluentValidation (400); user-facing messages are the legacy Arabic texts, keep them verbatim. Unexpected 5xx errors are written to `NTP.SYSTEM_ERRORS`.
|
||||
- Writes: `IUnitOfWork.ExecuteInTransactionAsync`; permit history goes through `IEventLogger` (EVENTS table: type, previous/current status, remarks, doneBy).
|
||||
- **Permissions** (`src/NTP.Application/Access`): keys in `PermissionKeys`; the table `GRAINS_SCREEN_PERMISSIONS` (role -> key) is the source of truth, `PermissionDefaults` only applies when that table is missing. SU is always allowed; role `DISABLED` switches a key off for everybody.
|
||||
Hard-coded role lists also exist (`GrainsRoles` in `PermitSupport.cs`, `RegistryAccessService`, `BlacklistService`, web `OPERATORS` in grains-permits/pages.tsx): when a role is added, grep for `"GTO"` and update them together. Registry accept / revoke / destinations use legacy `GROUPS`/`GROUP_ACTIONS` by role name (`HasActionAsync`).
|
||||
- Company users (`stkid 62` or role `DISP`) see and change only their own company (`EnsureCompanyAccess`); company code 327 = "الأهالي" (individual owners, `BadiyaScac`).
|
||||
- Web: Arabic (RTL) is the default and only language shown; light default, dark available; use logical CSS properties (`marginInlineStart`, not left/right); MUI 9 (`sx`, no system props); strings are bilingual `{ en, ar }` in each feature's `strings.ts`; theme in `web/src/theme`.
|
||||
- Every new SQL script in `db/` must be safe to re-run and listed in docs/ENVIRONMENTS.md.
|
||||
|
||||
## Domain vocabulary
|
||||
PN permit number, TN truck, TRN trailer, NNPN driver national no., SCAC company code, TT cargo class (BULK / PCKD / GALLAB). Permit status: OPEN on the turn (على الدور),
|
||||
REQST distributed to an order, PLND submitted by the company, ACCPT confirmed (ready for release), RESD released (تسريب), ACTRL at control, CLRPR cleared, CLOSE closed, RVKD revoked.
|
||||
Distribution categories: PCKD, BULK_AHALE, BULK_COMP, BULK_GALLAB_AHALE, BULK_GALLAB_COMP (queue type `AHALI` in queues, `AHALE` in orders: a legacy quirk).
|
||||
|
||||
## How to work here (agreed with the owner)
|
||||
- Understand the legacy behaviour first and cite legacy file:line when porting or fixing. Do not port dead legacy code (check `menu.cfm` and callers).
|
||||
- For a review request: report findings first (grouped definite bug / needs confirmation / benign), fix only what the owner picks. Verify agent findings in the code before presenting them.
|
||||
- Before saying "done": `dotnet build`, `dotnet test`, `npx tsc -b --noEmit`, restart the API and check its log. Say plainly what was not tested (nothing here was run against production data).
|
||||
- Commit only when asked. `git push` fails from a Claude session (no Gitea credentials): give the owner the command instead.
|
||||
- Production values (`appsettings.Production.json`) hold only non-secret settings; secrets come from the server `.env`. Never put passwords, keys or tokens in the repo or in chat.
|
||||
- Keep answers short, plain, and in the language the owner writes in; UI texts stay Arabic.
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
-- Scheduled jobs (screen "المهام المجدولة", SU only). Run once per database in the PRIMARY schema (NAFITHTCS). Safe to re-run; not run by the app.
|
||||
-- Until this script has run the scheduler stays idle (one warning in the API log) and the screen shows a message.
|
||||
--
|
||||
-- GRAINS_JOBS one row per job: stopped / started, schedule, last run. Rows are created by the screen, nothing to seed.
|
||||
-- GRAINS_JOB_RUNS history of every run (kept 90 days by the application).
|
||||
--
|
||||
-- Jobs (ports of the legacy jobs\*.cfm files): activate-company-destinations, close-old-permits, fill-company-shares.
|
||||
-- Schedule: SCHEDULETYPE = 'INTERVAL' (INTERVALMINUTES) or 'DAILY' (DAILYTIMES = 'HH:mm,HH:mm', database server time).
|
||||
|
||||
DECLARE
|
||||
PROCEDURE ddl(p_sql VARCHAR2) IS
|
||||
BEGIN
|
||||
EXECUTE IMMEDIATE p_sql;
|
||||
EXCEPTION
|
||||
WHEN OTHERS THEN
|
||||
-- already there: name in use (955), column list already indexed (1408)
|
||||
IF SQLCODE NOT IN (-955, -1408) THEN RAISE; END IF;
|
||||
END;
|
||||
BEGIN
|
||||
ddl('CREATE TABLE GRAINS_JOBS (
|
||||
JOBKEY VARCHAR2(50) NOT NULL,
|
||||
ENABLED NUMBER(1) DEFAULT 0 NOT NULL,
|
||||
SCHEDULETYPE VARCHAR2(10),
|
||||
INTERVALMINUTES NUMBER(8),
|
||||
DAILYTIMES VARCHAR2(200),
|
||||
LASTSTARTDATE DATE,
|
||||
LASTENDDATE DATE,
|
||||
LASTSTATUS VARCHAR2(20),
|
||||
LASTMESSAGE VARCHAR2(500),
|
||||
LASTCOUNT NUMBER(10),
|
||||
UPDATEDATE DATE,
|
||||
UPDATEDBY VARCHAR2(50),
|
||||
CONSTRAINT PK_GRAINS_JOBS PRIMARY KEY (JOBKEY)
|
||||
)');
|
||||
|
||||
ddl('CREATE TABLE GRAINS_JOB_RUNS (
|
||||
ID NUMBER(12) NOT NULL,
|
||||
JOBKEY VARCHAR2(50) NOT NULL,
|
||||
STARTDATE DATE NOT NULL,
|
||||
ENDDATE DATE,
|
||||
STATUS VARCHAR2(20),
|
||||
ROWSAFFECTED NUMBER(10),
|
||||
MESSAGE VARCHAR2(500),
|
||||
TRIGGEREDBY VARCHAR2(50),
|
||||
CONSTRAINT PK_GRAINS_JOB_RUNS PRIMARY KEY (ID)
|
||||
)');
|
||||
|
||||
ddl('CREATE SEQUENCE SEQ_GRAINS_JOB_RUNS START WITH 1 INCREMENT BY 1 NOCACHE');
|
||||
ddl('CREATE INDEX IX_GRAINS_JOB_RUNS_KEY ON GRAINS_JOB_RUNS (JOBKEY, ID)');
|
||||
END;
|
||||
/
|
||||
|
||||
-- Stop a job from SQL if the screen is not reachable: UPDATE GRAINS_JOBS SET ENABLED = 0 WHERE JOBKEY = 'close-old-permits'; COMMIT;
|
||||
|
|
@ -63,8 +63,6 @@ INSERT ALL
|
|||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.manualEntry')
|
||||
-- إيقاف\تفعيل الاستنكاف
|
||||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.absence')
|
||||
-- الاتصال الصوتي
|
||||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.voiceCall')
|
||||
-- طلبية التموين (orders menu)
|
||||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.orders.supply')
|
||||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.orders.supply')
|
||||
|
|
@ -82,9 +80,6 @@ INSERT ALL
|
|||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.loading-weights')
|
||||
-- الارساليات المكتملة
|
||||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.closed-permits')
|
||||
-- ارسالية عطاء التموين / ملخص التوزيع
|
||||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.tender-order')
|
||||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.distribution-summary')
|
||||
-- وجهات الشركات
|
||||
INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.orders.companyDest')
|
||||
-- تحديد وجهة ارسالية تموين
|
||||
|
|
|
|||
|
|
@ -1,17 +0,0 @@
|
|||
-- Grants GTO two more reports: ارسالية عطاء التموين (tender-order) and ملخص التوزيع (distribution-summary).
|
||||
-- Safe to re-run; not run by the app. Take either away by deleting its row (the API applies it within about a minute).
|
||||
|
||||
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
|
||||
SELECT v.rolecode, v.resource_key
|
||||
FROM (SELECT 'GTO' AS rolecode, 'grains.reports.t.tender-order' AS resource_key FROM dual UNION ALL
|
||||
SELECT 'GTO', 'grains.reports.t.distribution-summary' 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;
|
||||
|
||||
-- الاتصال الصوتي (voice call button on ارساليات التموين; legacy action 96): GTO.
|
||||
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
|
||||
SELECT 'GTO', 'grains.permits.voiceCall' FROM dual
|
||||
WHERE NOT EXISTS (SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS p WHERE p.rolecode = 'GTO' AND p.resource_key = 'grains.permits.voiceCall');
|
||||
|
||||
COMMIT;
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
-- 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';
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
-- 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;
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
-- 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;
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
-- New role CO with the same authority as GTO. Safe to re-run; not run by the app.
|
||||
-- Run order: part 1 in the NTP schema, part 2 in the primary (NAFITHTCS) schema.
|
||||
-- Afterwards assign role CO to the users who need it (NTPUSERS) - they sign in as before.
|
||||
-- The API applies the permission rows within about a minute, the browser on the next reload / sign-in.
|
||||
|
||||
-- ---------------------------------------------------------------------------------------------------------------------------
|
||||
-- Part 1 (NTP schema): the role itself, copied from GTO (level, type, manager columns). Rename it in NAME if needed.
|
||||
-- ---------------------------------------------------------------------------------------------------------------------------
|
||||
INSERT INTO ROLES (CODE, NAME, DIRECTMANAGER, EMPLOYEES, MANAGERS, LEVELNUMBER, ROLETYPE, TENDER)
|
||||
SELECT 'CO', 'CO', r.DIRECTMANAGER, r.EMPLOYEES, r.MANAGERS, r.LEVELNUMBER, r.ROLETYPE, r.TENDER
|
||||
FROM ROLES r
|
||||
WHERE r.CODE = 'GTO'
|
||||
AND NOT EXISTS (SELECT 1 FROM ROLES x WHERE x.CODE = 'CO');
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- ---------------------------------------------------------------------------------------------------------------------------
|
||||
-- Part 2 (primary schema): every screen / action / report right GTO has (grains-screen-permissions.sql, gto-reports.sql,
|
||||
-- menu-reorganisation.sql, registry-create-permissions.sql ...) is copied to CO. Later GTO rows: run this part again.
|
||||
-- ---------------------------------------------------------------------------------------------------------------------------
|
||||
INSERT INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY)
|
||||
SELECT 'CO', g.RESOURCE_KEY
|
||||
FROM GRAINS_SCREEN_PERMISSIONS g
|
||||
WHERE g.ROLECODE = 'GTO'
|
||||
AND NOT EXISTS (SELECT 1 FROM GRAINS_SCREEN_PERMISSIONS c WHERE c.ROLECODE = 'CO' AND c.RESOURCE_KEY = g.RESOURCE_KEY);
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- Take a right away from CO by deleting its row, e.g.:
|
||||
-- DELETE FROM GRAINS_SCREEN_PERMISSIONS WHERE ROLECODE = 'CO' AND RESOURCE_KEY = 'grains.permits.voiceCall';
|
||||
|
|
@ -7,7 +7,4 @@ Jwt__Key=
|
|||
# origin users open in the browser, exactly as typed in the address bar
|
||||
Cors__AllowedOrigins__0=https://<production-host>
|
||||
# logins that may hold role SU (none by default in production), e.g. Auth__SuperUsers__0=login
|
||||
# SMS account for owners without the app (secret; without it the SMS is skipped with a warning)
|
||||
# Grains__Permits__Notifications__Sms__UserName=
|
||||
# Grains__Permits__Notifications__Sms__Password=
|
||||
# NTP_PORT=8081
|
||||
|
|
|
|||
|
|
@ -21,11 +21,6 @@
|
|||
|
||||
ProxyPreserveHost On
|
||||
RequestHeader set X-Forwarded-Proto "https"
|
||||
# browser hardening (the API also sets these; Apache covers its own error pages)
|
||||
Header always set Strict-Transport-Security "max-age=31536000"
|
||||
Header always set X-Content-Type-Options "nosniff"
|
||||
Header always set X-Frame-Options "DENY"
|
||||
Header always set Referrer-Policy "same-origin"
|
||||
ProxyTimeout 120
|
||||
ProxyPass / http://127.0.0.1:8081/
|
||||
ProxyPassReverse / http://127.0.0.1:8081/
|
||||
|
|
|
|||
|
|
@ -12,15 +12,9 @@ services:
|
|||
args:
|
||||
WEB_MODE: build:prod
|
||||
restart: unless-stopped
|
||||
# /mnt/NTPFiles is owned by 65534 (nobody), group 2 and only its owner may write: run as that user, not as the image's "app" (1654)
|
||||
user: "65534:2"
|
||||
env_file: .env
|
||||
environment:
|
||||
ASPNETCORE_ENVIRONMENT: Production
|
||||
TZ: Asia/Amman # permit expiry, blacklist and report times follow the Oracle server clock (Amman)
|
||||
ports:
|
||||
# change the left side (or set NTP_PORT in .env) when 8081 is taken; use 127.0.0.1: when the proxy runs on this host
|
||||
- "127.0.0.1:${NTP_PORT:-8081}:8080"
|
||||
volumes:
|
||||
# attachments (trucks / trailers / drivers): the host folder /mnt/NTPFiles is read and written by the API at the same path
|
||||
- /mnt/NTPFiles:/mnt/NTPFiles
|
||||
|
|
|
|||
|
|
@ -20,11 +20,7 @@ FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
|||
WORKDIR /app
|
||||
COPY --from=api /app ./
|
||||
COPY --from=web /web/dist ./wwwroot
|
||||
# run as the image's built-in non-root user "app"; the API only writes to App_Data (QA attachments) and the mounted attachment folder
|
||||
RUN mkdir -p /app/App_Data && chown -R app:app /app/App_Data
|
||||
USER app
|
||||
ENV ASPNETCORE_URLS=http://+:8080 \
|
||||
ASPNETCORE_FORWARDEDHEADERS_ENABLED=true \
|
||||
TZ=Asia/Amman
|
||||
ASPNETCORE_FORWARDEDHEADERS_ENABLED=true
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["dotnet", "NTP.Api.dll"]
|
||||
|
|
|
|||
|
|
@ -22,11 +22,6 @@
|
|||
|
||||
ProxyPreserveHost On
|
||||
RequestHeader set X-Forwarded-Proto "https"
|
||||
# browser hardening (the API also sets these; Apache covers its own error pages)
|
||||
Header always set Strict-Transport-Security "max-age=31536000"
|
||||
Header always set X-Content-Type-Options "nosniff"
|
||||
Header always set X-Frame-Options "DENY"
|
||||
Header always set Referrer-Policy "same-origin"
|
||||
ProxyTimeout 120
|
||||
ProxyPass / http://127.0.0.1:8081/
|
||||
ProxyPassReverse / http://127.0.0.1:8081/
|
||||
|
|
|
|||
|
|
@ -11,6 +11,5 @@ services:
|
|||
env_file: .env
|
||||
environment:
|
||||
ASPNETCORE_ENVIRONMENT: QA
|
||||
TZ: Asia/Amman
|
||||
ports:
|
||||
- "127.0.0.1:8081:8080"
|
||||
- "0.0.0.0:8081:8080"
|
||||
|
|
|
|||
|
|
@ -34,7 +34,6 @@ 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 |
|
||||
|
||||
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,16 +49,10 @@ 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)
|
||||
5b. `db/gto-reports.sql` - GTO gets the ارسالية عطاء التموين and ملخص التوزيع reports (safe to re-run)
|
||||
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
|
||||
|
||||
**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
|
||||
|
|
|
|||
|
|
@ -1,63 +0,0 @@
|
|||
# Hand-over notes (written 2026-11-17)
|
||||
|
||||
How to start: open the repository folder in Claude Code (it reads `CLAUDE.md` by itself), then say
|
||||
"Read docs/HANDOVER.md and CLAUDE.md, summarise the state and the open items". Claude's per-machine memory does **not** travel with the
|
||||
repository: everything a new person needs is in these two files, `docs/ENVIRONMENTS.md` and `docs/MIGRATION.md`. Keep them updated.
|
||||
|
||||
## 1. State of the work
|
||||
- **Look and feel** ported from the `mams` project (theme tokens, Cairo font, grids, framed form sections, view page with Details / Attachments tabs, grouped home page, collapsible menu, Arabic only, breadcrumbs in the header).
|
||||
- **Billing (المطالبات المالية)** ported from the new legacy `Invoice.cfc` (wages / fines lookup, invoice creation, serial / invoice number mapping).
|
||||
- **Registry (trucks, trailers, drivers):** attachments are stored under `Grains:Registry:UploadedFilesPath` (production `/mnt/NTPFiles`, sub-folders `ntp_trucks_files` / `ntp_trailers_files` / `ntp_drivers_files`; legacy names like `0.723.pdf` are read).
|
||||
- **Reports:** the two GTO reports (ارسالية عطاء التموين, ملخص التوزيع) and turn reports (translated values, centred counters).
|
||||
- **Permits / distribution:** distribution reviewed twice against legacy and fixed (BlCategory bind, General Cargo exclusion, OPEN guards, queue cursor reset at sign-in, per-category confirmation, process-with-destination dropdowns + server check); voice call (الاتصال الصوتي) uses the legacy SOAP call; dialer callback hardened.
|
||||
- **Security pass:** accept / reject / cancel-confirmation staff-only, submit needs REQST, company-access null check, seed / check-trucks SU-only, attachment download scoped to the company.
|
||||
- **Scheduled jobs:** SU screen `/jobs` ("المهام المجدولة") starts / stops the three legacy jobs (`activateGrainsDestination`, `GRAINS_Close_Old_Permits` - ported new, `parseGrainsPermits`) and sets their running time: every N minutes / hours, or at fixed times of the day (database server time). Code: `src/NTP.Application/Jobs` (catalog, schedule rules, service), `src/NTP.Infrastructure/Jobs` (20-second scheduler loop, runner), `JobsController`, `web/src/features/jobs`. Needs `db/grains-jobs.sql` first. The lock is a database row, so two API instances never run one job twice. Add a job = one entry in `JobCatalog`. The old config-driven `GrainsPermitJobsWorker` is not registered and superseded by this.
|
||||
- **Operations:** unexpected 5xx errors go to `SYSTEM_ERRORS`; containers run with `TZ=Asia/Amman`.
|
||||
- **Roles:** `CO` was given the same code-level rights as `GTO` (see 3.1).
|
||||
- Last local commit at hand-over: `bf1c04b`. **It may not be pushed** (Claude sessions cannot authenticate to Gitea): run `git log origin/main..HEAD` and push it.
|
||||
|
||||
## 2. Deploy / configuration checklist (nothing below was verified on the production server)
|
||||
1. Jenkins builds `deploy/qa/Dockerfile` (`WEB_MODE=build:prod`), pushes the image, copies `deploy/prod/docker-compose.yml` to the server and runs `docker compose pull && up -d --no-build` (see `Jenkinsfile`). The compose file must reach the server for new volumes / env to apply.
|
||||
2. Server `.env` (never committed): `ConnectionStrings__NAFITHTCS`, `ConnectionStrings__NtpSchema`, `Jwt__Key`, `Cors__AllowedOrigins__0`; optional `Grains__Permits__AutoCall__ApiKey` (the dialer's callback key, empty = callback disabled).
|
||||
3. Host folder `/mnt/NTPFiles` must exist, be writable by the container, and hold the legacy files in `ntp_*_files`. Check `docker inspect ntpv2-prod --format '{{json .Mounts}}'`.
|
||||
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`).
|
||||
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).
|
||||
|
||||
## 3. Open decisions and known gaps
|
||||
### 3.0 Scheduled jobs: untested parts
|
||||
The schedule rules are unit-tested and the close-old-permits SQL was run read-only on QA, but the job tables did not exist when this was written: run `db/grains-jobs.sql`, then try the screen (save a time, start, run now, history) on QA. Close-old-permits differs from legacy in two safe ways: a permit found by two of its four groups is closed once, and it is closed only while it still has the status it was found with.
|
||||
### 3.1 Role CO
|
||||
`CO` already existed in the database ("مدير العمليات وخدمة الجمهور", own group id 149, stakeholder 61, 29 mostly oil-related actions, 1 user) and the legacy menu uses it in many places. The code now treats CO like GTO, and `GRAINS_SCREEN_PERMISSIONS` already has the same 27 rows for both. **Decide** whether that user should really get GTO's grains authority or whether a new role code is wanted. Also unresolved: CO's legacy group has none of the registry actions 66-71 / 107, so accept / revoke of trucks, trailers, drivers and destinations are off for CO; `db/role-co.sql` does not create `GROUPS` / `GROUP_ACTIONS` rows.
|
||||
|
||||
### 3.2 Role lists in code differ from the legacy action holders
|
||||
Legacy holders (from the database): phone confirm 93 = GNSU, GOO, GTO, MOT, SU; cancel order 106 = GNSU, GOO, GPO, MOT, SU; cancel permit 167 = GTO, MOT; voice call 96 = GNAC, GNSU, GTO, MOT, SU; accept / reject / cancel-confirmation 74 / 85 / 88 = GNSU, GOO, GPO, GTO, MOT, SU. V2 uses the single list `GrainsRoles.Operators` (SU, GPO, GNSU, GNCO, GTO, CO), so GOO cannot confirm by phone or cancel an order, and the "staff" gate for accept / reject is "any non-company user" (includes GGO). Proposed: one explicit role list per action.
|
||||
|
||||
### 3.3 Review findings: owner decisions (2026-11-17)
|
||||
Decided **to match legacy** (done): blacklist expiry uses shift 1 for a typed permit number and for NO_ANSWER (the real order shift only when a permit id is sent); the dialer callback accepts numbers or strings, any key case and any content type, and answers with the legacy keys `CODE` / `MSG`; trailer edit needs one document (stored or new); revoking a trailer resets its truck to REGREQST only when the revoke is made from the truck's page (trailer opened with `?truckId=`), and never a revoked truck.
|
||||
Decided **to keep V2** (not open): `acceptDriver` accepts (legacy never did), upload rules (fixed extension list, 10 MB), `TO_CHAR(pn/tn)` comparisons, manual weighbridge entry+exit without an outer transaction, manual-input date list, done-by shown to company users, used-orders count summed.
|
||||
Settled: time zone (container `TZ=Asia/Amman`, verified by the owner). No rate limit on the dialer callback; replays duplicate blacklist rows, as in legacy.
|
||||
Still open / not ported: company destinations save (Orders slice) only deletes the locations the screen offers (PCKD / BULK / BULK_GALLAB) where legacy deleted every row of the company, and it writes only ID / SCAC / LOCATIONID where legacy also wrote date and user (check the production table's columns and NOT NULL flags: `select column_name, nullable from user_tab_columns where table_name='GRAINS_COMPANIES_LOCATION'`); company users' "registered count share/open" on the truck / trailer grids; head-type change log; Firebase push; QUED/TCS permit flow (tables missing on QA); the approvals-file import is a second copy of the phone logic and likely broken (SU-only, legacy button commented out).
|
||||
|
||||
### 3.4 Never tested against real data
|
||||
Distribution runs, the IVR call, dialer callbacks, `SYSTEM_ERRORS` insert, the attachment folder in the container, the Amman time zone. Everything was verified only by build, unit tests, type check and read-only queries.
|
||||
|
||||
## 4. Security housekeeping for the owner
|
||||
- Database passwords from `appsettings.Local.json` were once shown in a Claude session's output: **rotate them**.
|
||||
- Make sure the new developer has Gitea access (push) and their own `appsettings.Local.json`; they need network access to the Oracle servers.
|
||||
- The repository holds no secrets by design (`.env` and `appsettings.Local.json` are git-ignored).
|
||||
|
||||
## 5. Useful read-only database checks
|
||||
Role and groups: `select * from roles where code='GTO'`, `select id,name,stakeholderid,status from groups where name in ('GTO','CO')`.
|
||||
Who holds a legacy action: `select ga.actionid, listagg(g.name,',') within group (order by g.name) from group_actions ga join groups g on g.id=ga.groupid and g.status=1 where ga.actionid in (73,74,93,94) group by ga.actionid`.
|
||||
Screen rights per role: `select rolecode, count(*) from grains_screen_permissions group by rolecode`.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
# 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.
|
||||
|
|
@ -1,983 +0,0 @@
|
|||
=== 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;
|
||||
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Application.Jobs;
|
||||
|
||||
namespace NTP.Api.Controllers.V1.Grains;
|
||||
|
||||
/// <summary>
|
||||
/// Scheduled jobs (ports of the legacy jobs\*.cfm files): list, set the running time, start / stop, run now, run history.
|
||||
/// Super users only. Nothing runs until a job is started here.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/grains/jobs")]
|
||||
[Produces("application/json")]
|
||||
[Authorize(Roles = "SU")]
|
||||
public sealed class JobsController(IJobService jobs) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public Task<IReadOnlyList<JobDto>> List(CancellationToken ct) => jobs.ListAsync(ct);
|
||||
|
||||
/// <summary>Running time: every N minutes (INTERVAL) or at fixed times of the day (DAILY, HH:mm).</summary>
|
||||
[HttpPut("{key}")]
|
||||
public Task<JobDto> SaveSchedule(string key, SaveJobScheduleRequest request, CancellationToken ct) => jobs.SaveScheduleAsync(key, request, ct);
|
||||
|
||||
[HttpPost("{key}/start")]
|
||||
public Task<JobDto> Start(string key, CancellationToken ct) => jobs.StartAsync(key, ct);
|
||||
|
||||
[HttpPost("{key}/stop")]
|
||||
public Task<JobDto> Stop(string key, CancellationToken ct) => jobs.StopAsync(key, ct);
|
||||
|
||||
/// <summary>Starts the job now in the background, whether it is started or stopped; refuses when it is already running.</summary>
|
||||
[HttpPost("{key}/run")]
|
||||
public Task<JobActionResult> Run(string key, CancellationToken ct) => jobs.RunNowAsync(key, ct);
|
||||
|
||||
[HttpGet("{key}/runs")]
|
||||
public Task<IReadOnlyList<JobRunDto>> Runs(string key, CancellationToken ct) => jobs.RunsAsync(key, 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);
|
||||
|
||||
/// Legacy Excel (HTML table) of the distribution ratios.
|
||||
/// format: csv (default) or xlsx.
|
||||
[HttpGet("tender-orders/export")]
|
||||
[RequirePermission(PermissionKeys.OrdersReportOrders)]
|
||||
public async Task<IActionResult> ExportTenderOrders([FromQuery] DateTime orderDate, CancellationToken ct = default)
|
||||
public async Task<IActionResult> ExportTenderOrders([FromQuery] DateTime orderDate, [FromQuery] string format = "csv", CancellationToken ct = default)
|
||||
{
|
||||
var f = await reports.ExportTenderOrderReportAsync(orderDate, ct);
|
||||
var f = await reports.ExportTenderOrderReportAsync(orderDate, format, ct);
|
||||
return File(f.Content, f.ContentType, f.FileName);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -160,12 +160,12 @@ public sealed class PermitQueueController(IQueueService queue) : ControllerBase
|
|||
|
||||
/// <summary>checkTrucks.</summary>
|
||||
[HttpPost("check-trucks")]
|
||||
[Authorize(Roles = "SU")]
|
||||
[RequirePermission(PermissionKeys.PermitsCreate)]
|
||||
public Task<PermitOperationResult> CheckTrucks([FromQuery] long tn, [FromQuery] long scac, CancellationToken ct) => queue.CheckTrucksAsync(tn, scac, ct);
|
||||
|
||||
/// <summary>parseGrainsPermits job, on demand: create OPEN permits for the given companies.</summary>
|
||||
[HttpPost("seed")]
|
||||
[Authorize(Roles = "SU")]
|
||||
[RequirePermission(PermissionKeys.PermitsCreate)]
|
||||
public Task<PermitOperationResult> Seed(SeedPermitsRequest request, CancellationToken ct) => queue.SeedPermitsAsync(request, ct);
|
||||
|
||||
// ---- TCS permit form (createPermit.cfm)
|
||||
|
|
@ -237,6 +237,11 @@ public sealed class PermitDestinationsController(IDestinationService destination
|
|||
[RequirePermission(PermissionKeys.PermitsDestinations)]
|
||||
public Task<IReadOnlyList<long>> CompanyDestinations(long scac, CancellationToken ct) => destinations.GetCompanyDestinationsAsync(scac, ct);
|
||||
|
||||
[HttpPut("companies/{scac:long}")]
|
||||
[RequirePermission(PermissionKeys.PermitsDestinations)]
|
||||
public Task<PermitOperationResult> SaveCompanyDestinations(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct) =>
|
||||
destinations.SaveCompanyDestinationsAsync(scac, request, ct);
|
||||
|
||||
/// <summary>savegrainsdest (assginggdest.cfm).</summary>
|
||||
[HttpPost("assign-by-pn")]
|
||||
[RequirePermission(PermissionKeys.PermitsDestinations)]
|
||||
|
|
@ -296,9 +301,8 @@ public sealed class PermitDistributionController(IDistributionService distributi
|
|||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<PermitOperationResult> Distribute(DistributeRequest request, CancellationToken ct) => distribution.DistributeAsync(request, ct);
|
||||
|
||||
// not used by any screen: legacy released permits only inside the distribute loop, which also moves the queue counter
|
||||
[HttpPost("release")]
|
||||
[Authorize(Roles = "SU")]
|
||||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<PermitOperationResult> Release(ReleasePermitRequest request, CancellationToken ct) => distribution.ReleaseAsync(request, ct);
|
||||
|
||||
[HttpPost("process-open")]
|
||||
|
|
@ -310,9 +314,8 @@ public sealed class PermitDistributionController(IDistributionService distributi
|
|||
public Task<PermitOperationResult> ProcessOpenWithDestination(OpenPermitWithDestinationRequest request, CancellationToken ct) =>
|
||||
distribution.ProcessOpenPermitWithDestinationAsync(request, ct);
|
||||
|
||||
// legacy screen "فك دور الشركات": GNSU and SU only
|
||||
[HttpPost("process-company-open")]
|
||||
[Authorize(Roles = "SU,GNSU")]
|
||||
[RequirePermission(PermissionKeys.PermitsTruckOrder)]
|
||||
public Task<PermitOperationResult> ProcessCompanyOpen(CompanyOpenPermitsRequest request, CancellationToken ct) =>
|
||||
distribution.ProcessCompanyOpenPermitsAsync(request, ct);
|
||||
|
||||
|
|
@ -337,7 +340,7 @@ public sealed class PermitDistributionController(IDistributionService distributi
|
|||
public Task<IReadOnlyList<BlacklistedDistributionDto>> Blacklisted([FromQuery] string tn, CancellationToken ct) => distribution.GetBlacklistedAsync(tn, ct);
|
||||
|
||||
[HttpPost("check-trips")]
|
||||
[Authorize(Roles = "SU")]
|
||||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<PermitOperationResult> CheckTrips(CheckTripsRequest request, CancellationToken ct) => distribution.CheckTripsAsync(request, ct);
|
||||
|
||||
/// <summary>RevokeAllREQST.cfm: send every REQST / PLND permit of an order id below the given limit back to OPEN.</summary>
|
||||
|
|
@ -356,7 +359,7 @@ public sealed class PermitDistributionController(IDistributionService distributi
|
|||
public Task<PermitOperationResult> SendAutoCall(AutoCallRequest request, CancellationToken ct) => distribution.SendAutoCallFileAsync(request, ct);
|
||||
|
||||
[HttpPost("auto-call/ivr")]
|
||||
[RequirePermission(PermissionKeys.PermitsVoiceCall)]
|
||||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<PermitOperationResult> TriggerIvr(CancellationToken ct) => distribution.TriggerIvrAsync(ct);
|
||||
}
|
||||
|
||||
|
|
@ -369,26 +372,11 @@ public sealed class PermitAutoCallController(IDistributionService distribution)
|
|||
{
|
||||
[HttpPost("callback")]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> Callback([FromHeader(Name = "X-Api-Key")] string? apiKey, CancellationToken ct)
|
||||
public async Task<IActionResult> Callback(AutoCallResponse body, [FromHeader(Name = "X-Api-Key")] string? apiKey, CancellationToken ct)
|
||||
{
|
||||
if (!distribution.IsValidDialerApiKey(apiKey)) return Unauthorized();
|
||||
|
||||
AutoCallResponse body;
|
||||
try
|
||||
{
|
||||
// legacy: the raw body is read as UTF-8 JSON whatever the content type is
|
||||
using var ms = new MemoryStream();
|
||||
await Request.Body.CopyToAsync(ms, ct);
|
||||
body = AutoCallResponse.FromJson(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
|
||||
}
|
||||
catch (Exception ex) when (ex is System.Text.Json.JsonException or FormatException)
|
||||
{
|
||||
return Ok(new Dictionary<string, string> { ["CODE"] = "500", ["MSG"] = ex.Message });
|
||||
}
|
||||
|
||||
var r = await distribution.HandleDialerCallbackAsync(body, ct);
|
||||
// legacy answered with the struct keys CODE / MSG
|
||||
return Ok(new Dictionary<string, string> { ["CODE"] = r.Code, ["MSG"] = r.Message });
|
||||
return Ok(new { code = r.Code, msg = r.Message });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -25,8 +25,7 @@ public sealed class RegistryController(
|
|||
IRegistryOpsService ops,
|
||||
IRegistryLookupService lookups,
|
||||
IRegistryAttachmentService attachments,
|
||||
IRegistryQueuePermitService queuePermits,
|
||||
IRegistryExportService exports) : ControllerBase
|
||||
IRegistryQueuePermitService queuePermits) : ControllerBase
|
||||
{
|
||||
// ------------------------------------------------------------------------------------------ permissions + lookups
|
||||
|
||||
|
|
@ -68,33 +67,6 @@ 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)]
|
||||
|
|
@ -154,7 +126,7 @@ public sealed class RegistryController(
|
|||
|
||||
[HttpPost("trailers/{id:long}/revoke")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrailers)]
|
||||
public Task<RegistryResult> RevokeTrailer(long id, [FromQuery] long? truckId, CancellationToken ct) => trailers.RevokeAsync(id, truckId, ct);
|
||||
public Task<RegistryResult> RevokeTrailer(long id, CancellationToken ct) => trailers.RevokeAsync(id, ct);
|
||||
|
||||
// ------------------------------------------------------------------------------------------ drivers (driverGrid.cfm, regesterDriver.cfm)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,56 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,180 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
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>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);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string> Split(string? s) =>
|
||||
(s ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
using FluentValidation;
|
||||
using Microsoft.AspNetCore.Diagnostics;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
using Oracle.ManagedDataAccess.Client;
|
||||
|
||||
|
|
@ -15,22 +14,13 @@ namespace NTP.Api.ErrorHandling;
|
|||
internal sealed class GlobalExceptionHandler(
|
||||
IProblemDetailsService problemDetails,
|
||||
IHostEnvironment env,
|
||||
ISystemErrorLogger systemErrors,
|
||||
ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
|
||||
{
|
||||
public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct)
|
||||
{
|
||||
var (status, title, detail, errors) = Map(exception);
|
||||
|
||||
if (status >= 500)
|
||||
{
|
||||
logger.LogError(exception, "Unhandled error: {Title}", title);
|
||||
// runtime errors are kept in SYSTEM_ERRORS (like the legacy system)
|
||||
var ip = http.Connection.RemoteIpAddress;
|
||||
if (ip is { IsIPv4MappedToIPv6: true }) ip = ip.MapToIPv4();
|
||||
await systemErrors.LogAsync(exception, http.User.FindFirst(AppClaims.UserId)?.Value, ip?.ToString(),
|
||||
http.Request.Headers.UserAgent.ToString(), $"{http.Request.Method} {http.Request.Path}{http.Request.QueryString}");
|
||||
}
|
||||
if (status >= 500) logger.LogError(exception, "Unhandled error: {Title}", title);
|
||||
else logger.LogWarning("Request failed {Status}: {Title} - {Message}", status, title, exception.Message);
|
||||
|
||||
ProblemDetails problem = errors is null
|
||||
|
|
@ -57,12 +47,11 @@ 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", string.Join(" - ", v.Errors.Select(e => e.ErrorMessage).Distinct()),
|
||||
ValidationException v when v.Errors.Any() => (400, "Validation failed", null,
|
||||
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),
|
||||
// Business rules: Title/Detail carry the legacy (Arabic) user-facing message; "code" extension is stable.
|
||||
TooManyAttemptsException tm => (429, tm.Message, tm.Message, null),
|
||||
AuthenticationFailedException af => (401, af.Message, af.Message, null),
|
||||
ForbiddenException fe => (403, fe.Message, fe.Message, null),
|
||||
BusinessException be => (422, be.Message, be.Message, null),
|
||||
|
|
|
|||
|
|
@ -48,29 +48,6 @@ var app = builder.Build();
|
|||
var oracle = app.Services.GetRequiredService<IOptions<OracleOptions>>().Value;
|
||||
app.Logger.LogInformation("Oracle connection: {ConnectionString}", oracle.ToSafeString());
|
||||
|
||||
// Browser hardening headers on every response (API and the web app it serves). The CSP fits the built web app: own scripts only,
|
||||
// MUI inline styles, the Cairo font from Google Fonts, PDFs shown in a blob: iframe. Not applied in Development (Vite hot reload).
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
const string csp = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
|
||||
"font-src 'self' data: https://fonts.gstatic.com; img-src 'self' data: blob:; connect-src 'self'; " +
|
||||
"frame-src 'self' blob:; object-src 'self' blob:; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
|
||||
app.Use(async (ctx, next) =>
|
||||
{
|
||||
ctx.Response.OnStarting(() =>
|
||||
{
|
||||
var h = ctx.Response.Headers;
|
||||
h["X-Content-Type-Options"] = "nosniff";
|
||||
h["X-Frame-Options"] = "DENY";
|
||||
h["Referrer-Policy"] = "same-origin";
|
||||
h["Content-Security-Policy"] = csp;
|
||||
if (ctx.Request.IsHttps) h["Strict-Transport-Security"] = "max-age=31536000"; // https is known from X-Forwarded-Proto
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
await next();
|
||||
});
|
||||
}
|
||||
|
||||
app.UseCors("Frontend"); // first, so error responses also carry CORS headers
|
||||
app.UseExceptionHandler();
|
||||
app.UseStatusCodePages();
|
||||
|
|
|
|||
|
|
@ -2,10 +2,6 @@
|
|||
"Auth": {
|
||||
"SuperUsers": [ "samer", "QA", "MATHHER" ]
|
||||
},
|
||||
// the job scheduler never runs on a developer machine (a shared database would run its jobs twice); "run now" still works
|
||||
"Jobs": { "SchedulerEnabled": false },
|
||||
// no pushes or SMS from a developer machine (SEND_SMS_GN_DIST = 0)
|
||||
"Grains": { "Permits": { "Notifications": { "Enabled": false, "SendSmsToOwnersWithoutApp": false } } },
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
|
|
|
|||
|
|
@ -20,36 +20,5 @@
|
|||
"Oracle": {
|
||||
"MinPoolSize": 5,
|
||||
"MaxPoolSize": 100
|
||||
},
|
||||
|
||||
// Attachments of trucks / trailers / drivers are read and written on the shared folder /mnt/NTPFiles
|
||||
// (mounted into the container, see deploy/prod/docker-compose.yml). Stored files go to
|
||||
// <UploadedFilesPath>/ntp_trucks_files | ntp_trailers_files | ntp_drivers_files; uploads wait in TempUploadPath until Save.
|
||||
"Grains": {
|
||||
"Registry": {
|
||||
"UploadedFilesPath": "/mnt/NTPFiles",
|
||||
"TempUploadPath": "/mnt/NTPFiles/tempuploadedfiles"
|
||||
},
|
||||
|
||||
// الاتصال الصوتي button (ارساليات التموين): starts the IVR calls. The ?wsdl address is turned into a call of callAPI.
|
||||
"Permits": {
|
||||
// truck ownership codes (MOT_TRUCKS.OWNERSHIPCODE) that may be added to company 327 (individuals) / to every other company;
|
||||
// legacy application.GN_BadyahOwnership = 3,2 and GN_OthersOwnership = 1,2. Empty list = check skipped.
|
||||
"BadiyaOwnershipCodes": [ "3", "2" ],
|
||||
"OtherOwnershipCodes": [ "1", "2" ],
|
||||
|
||||
// push on; SMS to owners without the app on (legacy SEND_SMS_GN_DIST = 1). The SMS account (Sms:UserName / Sms:Password) comes from the
|
||||
// server .env: Grains__Permits__Notifications__Sms__UserName / __Password. Until they are set the SMS is skipped with a warning.
|
||||
"Notifications": {
|
||||
"Enabled": true,
|
||||
"SendSmsToOwnersWithoutApp": true,
|
||||
"Sms": { "Enabled": true, "Provider": "JORMALL" }
|
||||
},
|
||||
|
||||
"AutoCall": {
|
||||
"Enabled": true,
|
||||
"IvrUrl": "http://aqtcs.nafith.net/IVR/callivr.cfc?wsdl"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,13 +21,6 @@
|
|||
"SuperUsers": [ "samer", "QA", "MATHHER" ]
|
||||
},
|
||||
|
||||
// Push notifications on, SMS off (legacy SEND_SMS_GN_DIST = 0 in QA).
|
||||
"Grains": {
|
||||
"Permits": {
|
||||
"Notifications": { "Enabled": true, "SendSmsToOwnersWithoutApp": false }
|
||||
}
|
||||
},
|
||||
|
||||
"Oracle": {
|
||||
"MinPoolSize": 2,
|
||||
"MaxPoolSize": 50
|
||||
|
|
|
|||
|
|
@ -27,19 +27,6 @@
|
|||
"AllowedOrigins": [ "http://localhost:5173" ]
|
||||
},
|
||||
|
||||
// Mobile notifications (legacy MobileNotifications.cfc). Off here: a switched-on environment pushes to the real devices of USERDEVICEINFO.
|
||||
// QA and production switch it on in their own files. Sms:UserName / Sms:Password are secrets (env vars Grains__Permits__Notifications__Sms__UserName ...).
|
||||
"Grains": {
|
||||
"Permits": {
|
||||
"Notifications": {
|
||||
"Enabled": false,
|
||||
"PushUrl": "http://aqtcs.nafith.net/backend/common/MobileNotification.cfc?wsdl",
|
||||
"SendSmsToOwnersWithoutApp": false,
|
||||
"Sms": { "Enabled": false, "Provider": "JORMALL", "SenderId": "Nafith" }
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Primary connection = NAFITHTCS schema; NtpSchema = NTP schema (both required). Real values go in appsettings.Local.json / env vars
|
||||
// (ConnectionStrings__NAFITHTCS, ConnectionStrings__NtpSchema). Option A - full connection strings (take priority):
|
||||
"ConnectionStrings": {
|
||||
|
|
@ -61,17 +48,5 @@
|
|||
"ConnectionTimeoutSeconds": 15,
|
||||
"StatementCacheSize": 50,
|
||||
"CommandTimeoutSeconds": 30
|
||||
},
|
||||
|
||||
// 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 }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +0,0 @@
|
|||
namespace NTP.Application.Abstractions;
|
||||
|
||||
/// <summary>Saves runtime (unexpected) errors into the NTP-schema table SYSTEM_ERRORS (legacy logs.cfc logSysError). Never throws.</summary>
|
||||
public interface ISystemErrorLogger
|
||||
{
|
||||
Task LogAsync(Exception exception, string? userId, string? ipAddress, string? browser, string? requestInfo);
|
||||
}
|
||||
|
|
@ -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 partial class PermissionKeys
|
||||
public static class PermissionKeys
|
||||
{
|
||||
// Screens (menu keys)
|
||||
public const string OrdersList = "grains.orders.list";
|
||||
|
|
@ -47,11 +47,6 @@ public static partial 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
|
||||
|
|
@ -59,7 +54,6 @@ public static partial class PermissionKeys
|
|||
public const string PermitsActivation = "grains.permits.activation"; // legacy activateOrders.cfm
|
||||
public const string PermitsManualEntry = "grains.permits.manualEntry"; // legacy ManualInput.cfm
|
||||
public const string PermitsAbsence = "grains.permits.absence"; // legacy activeOrInactiveAbsenceFeature.cfm
|
||||
public const string PermitsVoiceCall = "grains.permits.voiceCall"; // legacy GNPermits.cfm "نظام الاتصال الصوتي" (action 96)
|
||||
|
||||
// Report screens outside the business sheet allow-list: SU only (no seed rows)
|
||||
public const string ReportsDashboard = "grains.reports.dashboard";
|
||||
|
|
@ -87,34 +81,31 @@ public static class PermissionDefaults
|
|||
{
|
||||
public static readonly IReadOnlyDictionary<string, string[]> RolesByResource = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[PermissionKeys.PermitsList] = ["GTO", "CO", "GGO", "GOO", "GPO", "DISP"], // ارسالية عطاء التموين (DISP: own company only)
|
||||
[PermissionKeys.RegistryTrucks] = ["GTO", "CO", "GOO", "GPO"], // شاشة القاطرات
|
||||
[PermissionKeys.RegistryTrailers] = ["GTO", "CO", "GOO", "GPO"], // شاشة المقطورات
|
||||
[PermissionKeys.RegistryDrivers] = ["GTO", "CO", "GOO", "GPO"], // شاشة السائقين المسجلين
|
||||
[PermissionKeys.OrdersList] = ["GTO", "CO", "GOO"], // الطلبيات
|
||||
[PermissionKeys.OrdersCreate] = ["GTO", "CO"], // طلبية جديدة (GOO was removed again; add a row per role to grant it)
|
||||
[PermissionKeys.PermitsWeighbridge] = ["GTO", "CO", "GGO"], // شاشة القبان
|
||||
[PermissionKeys.PermitsClose] = ["GTO", "CO", "GGO", "GOO", "GPO"], // اغلاق إرسالية
|
||||
[PermissionKeys.PermitsTruckOrder] = ["GTO", "CO"], // طلبية لسيارة
|
||||
[PermissionKeys.RegistryBlacklist] = ["GTO", "CO", "GOO", "GPO"], // شاشة الأيقاف والإنتظار
|
||||
[PermissionKeys.PermitsDistribution] = ["GTO", "CO", "GOO"], // طلبية التموين
|
||||
[PermissionKeys.OrdersSupply] = ["GTO", "CO", "GOO"], // طلبية التموين (orders menu)
|
||||
[PermissionKeys.PermitsTruckStatus] = ["GTO", "CO", "GOO"], // استعلام عن حالة التوزيع لسيارة
|
||||
[PermissionKeys.PermitsActivation] = ["GTO", "CO"], // شاشة تفعيل الطلبية
|
||||
[PermissionKeys.PermitsManualEntry] = ["GTO", "CO"], // شاشة الادخال اليدوي
|
||||
[PermissionKeys.PermitsAbsence] = ["GTO", "CO"], // إيقاف\تفعيل الاستنكاف
|
||||
[PermissionKeys.PermitsVoiceCall] = ["GTO", "CO"], // الاتصال الصوتي
|
||||
[PermissionKeys.PermitsList] = ["GTO", "GGO", "GOO", "GPO", "DISP"], // ارسالية عطاء التموين (DISP: own company only)
|
||||
[PermissionKeys.RegistryTrucks] = ["GTO", "GOO", "GPO"], // شاشة القاطرات
|
||||
[PermissionKeys.RegistryTrailers] = ["GTO", "GOO", "GPO"], // شاشة المقطورات
|
||||
[PermissionKeys.RegistryDrivers] = ["GTO", "GOO", "GPO"], // شاشة السائقين المسجلين
|
||||
[PermissionKeys.OrdersList] = ["GTO", "GOO"], // الطلبيات
|
||||
[PermissionKeys.OrdersCreate] = ["GTO"], // طلبية جديدة (GOO was removed again; add a row per role to grant it)
|
||||
[PermissionKeys.PermitsWeighbridge] = ["GTO", "GGO"], // شاشة القبان
|
||||
[PermissionKeys.PermitsClose] = ["GTO", "GGO", "GOO", "GPO"], // اغلاق إرسالية
|
||||
[PermissionKeys.PermitsTruckOrder] = ["GTO"], // طلبية لسيارة
|
||||
[PermissionKeys.RegistryBlacklist] = ["GTO", "GOO", "GPO"], // شاشة الأيقاف والإنتظار
|
||||
[PermissionKeys.PermitsDistribution] = ["GTO", "GOO"], // طلبية التموين
|
||||
[PermissionKeys.OrdersSupply] = ["GTO", "GOO"], // طلبية التموين (orders menu)
|
||||
[PermissionKeys.PermitsTruckStatus] = ["GTO", "GOO"], // استعلام عن حالة التوزيع لسيارة
|
||||
[PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية
|
||||
[PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي
|
||||
[PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف
|
||||
[PermissionKeys.OrdersInvoiceCheck] = ["GNAC"], // التأكد من الفواتير
|
||||
[PermissionKeys.OrdersFines] = ["GNAC"], // الغرامات
|
||||
[PermissionKeys.OrdersWages] = ["GNAC"], // الأجور
|
||||
[PermissionKeys.OrdersWeights] = ["GTO", "CO"], // تثبيت أوزان التحميل
|
||||
[PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "CO", "GOO"], // تقارير حركات قبان التحميل والتفريغ
|
||||
[PermissionKeys.ReportTable("companies-turn")] = ["GTO", "CO", "GOO"], // تقرير دور الشركات
|
||||
[PermissionKeys.ReportTable("owners-turn")] = ["GTO", "CO"], // تقرير دور الأفراد
|
||||
[PermissionKeys.ReportTable("loading-weights")] = ["GTO", "CO"], // تقرير أوزان التحميل
|
||||
[PermissionKeys.ReportTable("closed-permits")] = ["GTO", "CO"], // الارساليات المكتملة
|
||||
[PermissionKeys.ReportTable("tender-order")] = ["GTO", "CO"], // ارسالية عطاء التموين
|
||||
[PermissionKeys.ReportTable("distribution-summary")] = ["GTO", "CO"], // ملخص التوزيع
|
||||
[PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل
|
||||
[PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "GOO"], // تقارير حركات قبان التحميل والتفريغ
|
||||
[PermissionKeys.ReportTable("companies-turn")] = ["GTO", "GOO"], // تقرير دور الشركات
|
||||
[PermissionKeys.ReportTable("owners-turn")] = ["GTO"], // تقرير دور الأفراد
|
||||
[PermissionKeys.ReportTable("loading-weights")] = ["GTO"], // تقرير أوزان التحميل
|
||||
[PermissionKeys.ReportTable("closed-permits")] = ["GTO"], // الارساليات المكتملة
|
||||
[PermissionKeys.OrdersCompanyDest] = ["GOO"], // وجهات الشركات
|
||||
[PermissionKeys.PermitsDestinations] = ["GOO"], // تحديد وجهة ارسالية تموين
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,14 +0,0 @@
|
|||
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";
|
||||
}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
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)
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
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";
|
||||
}
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
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)
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
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";
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -22,10 +22,8 @@ public sealed class AuthService(
|
|||
ICurrentUser currentUser,
|
||||
IValidator<LoginRequest> loginValidator,
|
||||
IValidator<ChangePasswordRequest> changePasswordValidator,
|
||||
IValidator<SetLanguageRequest> languageValidator,
|
||||
LoginThrottle throttle) : IAuthService
|
||||
IValidator<SetLanguageRequest> languageValidator) : IAuthService
|
||||
{
|
||||
private const string TooManyAttemptsMessage = "محاولات دخول خاطئة كثيرة، يرجى المحاولة بعد {0} دقيقة";
|
||||
// Legacy messages (kept verbatim).
|
||||
public const string InvalidLoginMessage = "معلومات الدخول خاطئة ... حاول مرة أخرى";
|
||||
private const string NoActiveBoothMessage = "لا يمكنك الدخول, يرجى مراجعة رئيس الشفت";
|
||||
|
|
@ -45,25 +43,6 @@ public sealed class AuthService(
|
|||
{
|
||||
await loginValidator.ValidateAndThrowAsync(request, ct);
|
||||
|
||||
var throttleKey = request.UserName.Trim().ToLowerInvariant();
|
||||
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))));
|
||||
|
||||
try
|
||||
{
|
||||
var result = await SignInAsync(request, client, ct);
|
||||
throttle.RecordSuccess(throttleKey);
|
||||
return result;
|
||||
}
|
||||
catch (AuthenticationFailedException ex) when (ex.Code == "INVALID_CREDENTIALS")
|
||||
{
|
||||
throttle.RecordFailure(throttleKey, client.IpAddress);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
|
|
@ -119,9 +98,6 @@ public sealed class AuthService(
|
|||
Lang: "AR",
|
||||
IsStaff: profile.CompanyId == StaffCompanyId);
|
||||
|
||||
// the company-queue cursor of the distribution screen lived in the session: a new sign-in starts from 1 again
|
||||
NTP.Application.Grains.Permits.DistributionCursor.Reset(user.UserId);
|
||||
|
||||
// Logging (addlog 1) - legacy swallows logging errors.
|
||||
await TryAsync(() => repository.InsertLogAsync(
|
||||
new AuditLogEntry(user.UserId, client.IpAddress, user.RoleCode, LogSignIn, user.Name, client.UserAgent), ct));
|
||||
|
|
|
|||
|
|
@ -15,12 +15,8 @@ public sealed class ChangePasswordRequestValidator : AbstractValidator<ChangePas
|
|||
{
|
||||
public ChangePasswordRequestValidator()
|
||||
{
|
||||
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().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("كلمة السر الجديدة يجب أن تختلف عن القديمة");
|
||||
RuleFor(x => x.OldPassword).NotEmpty().MaximumLength(200);
|
||||
RuleFor(x => x.NewPassword).NotEmpty().MaximumLength(200);
|
||||
RuleFor(x => x.ConfirmNewPassword)
|
||||
.Equal(x => x.NewPassword).When(x => x.ConfirmNewPassword is not null)
|
||||
.WithMessage("كلمة السر الجديدة غير متطابقة");
|
||||
|
|
|
|||
|
|
@ -1,71 +0,0 @@
|
|||
using System.Collections.Concurrent;
|
||||
|
||||
namespace NTP.Application.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Slows down password guessing: after <see cref="MaxPerLogin"/> failed sign-ins of one login (or <see cref="MaxPerIp"/> from one address)
|
||||
/// inside <see cref="Window"/>, further attempts are refused until the oldest failure leaves the window. A success clears the login.
|
||||
/// In memory per API instance (one container in production). The login key does not depend on the client address, so a forged
|
||||
/// X-Forwarded-For header cannot get around the per-login limit.
|
||||
/// </summary>
|
||||
public sealed class LoginThrottle(TimeProvider clock)
|
||||
{
|
||||
public const int MaxPerLogin = 5;
|
||||
public const int MaxPerIp = 30;
|
||||
public static readonly TimeSpan Window = TimeSpan.FromMinutes(15);
|
||||
|
||||
private readonly ConcurrentDictionary<string, Queue<DateTimeOffset>> _failures = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private static string LoginKey(string login) => "L:" + login;
|
||||
private static string IpKey(string? ip) => "I:" + (ip ?? "?");
|
||||
|
||||
/// <summary>How long the caller must wait, or null when the attempt may proceed.</summary>
|
||||
public TimeSpan? BlockedFor(string login, string? ip) =>
|
||||
Max(Remaining(LoginKey(login), MaxPerLogin), Remaining(IpKey(ip), MaxPerIp));
|
||||
|
||||
public void RecordFailure(string login, string? ip)
|
||||
{
|
||||
Add(LoginKey(login));
|
||||
Add(IpKey(ip));
|
||||
}
|
||||
|
||||
public void RecordSuccess(string login) => _failures.TryRemove(LoginKey(login), out _);
|
||||
|
||||
private TimeSpan? Remaining(string key, int max)
|
||||
{
|
||||
if (!_failures.TryGetValue(key, out var q)) return null;
|
||||
lock (q)
|
||||
{
|
||||
Trim(q);
|
||||
if (q.Count < max) return null;
|
||||
return q.Peek() + Window - clock.GetUtcNow();
|
||||
}
|
||||
}
|
||||
|
||||
private void Add(string key)
|
||||
{
|
||||
var q = _failures.GetOrAdd(key, _ => new Queue<DateTimeOffset>());
|
||||
lock (q)
|
||||
{
|
||||
Trim(q);
|
||||
q.Enqueue(clock.GetUtcNow());
|
||||
}
|
||||
if (_failures.Count > 20_000) Sweep();
|
||||
}
|
||||
|
||||
private void Trim(Queue<DateTimeOffset> q)
|
||||
{
|
||||
var limit = clock.GetUtcNow() - Window;
|
||||
while (q.Count > 0 && q.Peek() <= limit) q.Dequeue();
|
||||
}
|
||||
|
||||
private void Sweep()
|
||||
{
|
||||
foreach (var (key, q) in _failures)
|
||||
{
|
||||
lock (q) { Trim(q); if (q.Count == 0) _failures.TryRemove(key, out _); }
|
||||
}
|
||||
}
|
||||
|
||||
private static TimeSpan? Max(TimeSpan? a, TimeSpan? b) => a is null ? b : b is null ? a : a > b ? a : b;
|
||||
}
|
||||
|
|
@ -20,8 +20,5 @@ public class BusinessException(string code, string message) : Exception(message)
|
|||
/// <summary>Credentials / account state rejected (HTTP 401). Same shape as <see cref="BusinessException"/>.</summary>
|
||||
public sealed class AuthenticationFailedException(string code, string message) : BusinessException(code, message);
|
||||
|
||||
/// <summary>Too many failed sign-ins (HTTP 429).</summary>
|
||||
public sealed class TooManyAttemptsException(string code, string message) : BusinessException(code, message);
|
||||
|
||||
/// <summary>Authenticated but the role/rules do not allow the action (HTTP 403).</summary>
|
||||
public sealed class ForbiddenException(string code, string message) : BusinessException(code, message);
|
||||
|
|
|
|||
|
|
@ -15,8 +15,6 @@ public static class DependencyInjection
|
|||
var assembly = typeof(DependencyInjection).Assembly;
|
||||
services.AddValidatorsFromAssembly(assembly, includeInternalTypes: true);
|
||||
services.AddConventionalServices(assembly);
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.AddSingleton<NTP.Application.Auth.LoginThrottle>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,107 +19,66 @@ public interface IBillingService
|
|||
public sealed class BillingService(
|
||||
IBillingRepository repository,
|
||||
IUnitOfWork unitOfWork,
|
||||
IEventLogger events,
|
||||
ICurrentUser user,
|
||||
IValidator<AddBillingRequest> validator) : IBillingService
|
||||
{
|
||||
private static string? Date(DateTime? d) => d?.ToString("yyyy-MM-dd");
|
||||
|
||||
/// <summary>Port of getBillingInfo (2023 version): empty PN, billing already entered, permit not found.</summary>
|
||||
public async Task<BillingPermitDto> GetPermitAsync(long pn, long? scac, CancellationToken ct)
|
||||
{
|
||||
if (await repository.PnExistsAsync(pn, ct)) throw OrdersErrors.BillingExists();
|
||||
var info = await repository.GetPermitBillingInfoAsync(pn, user.UserId, ct) ?? throw OrdersErrors.InvalidPn();
|
||||
var info = await repository.GetPermitBillingInfoAsync(pn, ct) ?? throw OrdersErrors.InvalidPn();
|
||||
if (scac.HasValue && scac.Value != info.Scac) throw OrdersErrors.PnNotOfCompany();
|
||||
|
||||
var lnw = BillingCalculator.NetWeight(info.Lgw, info.Ltw);
|
||||
var dnw = BillingCalculator.NetWeight(info.Dgw, info.Dtw);
|
||||
|
||||
// Prices shown on the screen are the ones addBillingInfo will store: the destination's wage rate and the
|
||||
// cargo type's fine rate, both valid on the loading date.
|
||||
decimal? price = null, finePrice = null;
|
||||
if (info.LoadDate.HasValue)
|
||||
{
|
||||
if (info.Destination.HasValue)
|
||||
price = (await repository.GetWageRateAsync(info.Destination.Value, info.LoadDate.Value.Date, ct))?.Wage;
|
||||
if (info.CargoType.HasValue)
|
||||
finePrice = (await repository.GetFineRateAsync(info.CargoType.Value, info.LoadDate.Value.Date, ct))?.Fine;
|
||||
}
|
||||
return new BillingPermitDto(
|
||||
info.Pn, info.Scac, info.CompanyName, info.CargoType, info.Tn, info.Destination,
|
||||
Date(info.LoadDate), Date(info.DischargeDate), lnw,
|
||||
dnw == 0 ? null : dnw, // the legacy page left the received-weight box empty when it was 0
|
||||
info.LastInvoice, price, finePrice);
|
||||
info.LastInvoice,
|
||||
BillingPrices.Get(info.Destination), BillingPrices.Get(info.CargoType));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Port of addBillingInfo (Invoice.cfc, 2023) with the field mapping corrected on request: "رقم المطالبة" is the invoice
|
||||
/// number (INVOICE / GRAINS_BILLING.INVOICENUMBER) and "رقم المستند" is stored in GRAINS_BILLING.SERIALNO.
|
||||
/// (The legacy CFC had the two swapped.)
|
||||
/// </summary>
|
||||
public async Task<OrdersResult> AddAsync(AddBillingRequest request, CancellationToken ct)
|
||||
{
|
||||
await validator.ValidateAndThrowAsync(request, ct);
|
||||
var invoiceNumber = request.InvoiceNumber;
|
||||
var serialNo = long.Parse(request.SerialNo.Trim());
|
||||
|
||||
// 1. an invoice keeps one family of cargo types (38 / 74 / 39+41)
|
||||
var invoiceCargo = await repository.GetInvoiceCargoTypeAsync(request.Scac, invoiceNumber, ct);
|
||||
if (invoiceCargo.HasValue && !BillingCalculator.IsCargoAllowedOnInvoice(invoiceCargo.Value, request.CargoType))
|
||||
throw OrdersErrors.InvoiceCargoMismatch();
|
||||
// Weights are re-read server side (legacy trusted hidden form fields).
|
||||
var info = await repository.GetPermitBillingInfoAsync(request.Pn, ct) ?? throw OrdersErrors.InvalidPn();
|
||||
if (info.Scac != request.Scac) throw OrdersErrors.PnNotOfCompany();
|
||||
|
||||
// 2. archived invoices take no new billing
|
||||
var invoiceStatus = await repository.GetInvoiceStatusAsync(request.Scac.ToString(), invoiceNumber.ToString(), ct);
|
||||
if (string.Equals(invoiceStatus, "ARCHIVED", StringComparison.OrdinalIgnoreCase)) throw OrdersErrors.InvoiceArchived();
|
||||
|
||||
// 3. one billing per permit
|
||||
if (await repository.PnExistsAsync(request.Pn, ct)) throw OrdersErrors.BillingExists();
|
||||
|
||||
// page JS rules kept as server checks
|
||||
if (!BillingCalculator.IsDischargeAfterLoad(request.LoadDate, request.DischargeDate)) throw OrdersErrors.DischargeBeforeLoad();
|
||||
var lnw = request.Lnw;
|
||||
var dnw = request.Dnw;
|
||||
if (dnw <= 0) throw OrdersErrors.ReceivedWeightMissing();
|
||||
|
||||
var lnw = BillingCalculator.NetWeight(info.Lgw, info.Ltw);
|
||||
var dnw = BillingCalculator.NetWeight(info.Dgw, info.Dtw);
|
||||
if (dnw == 0) throw OrdersErrors.ReceivedWeightMissing();
|
||||
if (!BillingCalculator.IsSentWeightInRange(lnw)) throw OrdersErrors.SentWeightRange();
|
||||
|
||||
// 4. PRICE = wage rate of the destination on the loading date, FINEPRICE = fine rate of the cargo type on that
|
||||
// date; if either is missing the billing cannot be added.
|
||||
var wage = await repository.GetWageRateAsync(request.Destination, request.LoadDate.Date, ct);
|
||||
var fine = await repository.GetFineRateAsync(request.CargoType, request.LoadDate.Date, ct);
|
||||
if (wage is null || fine is null) throw OrdersErrors.PriceNotDefined();
|
||||
|
||||
var wageAmount = BillingCalculator.Wage(wage.Wage, lnw);
|
||||
var loseFine = BillingCalculator.ShortageFine(lnw, dnw, fine.Allowance, fine.Fine);
|
||||
var finalCost = wageAmount - loseFine;
|
||||
|
||||
var companyName = await repository.GetTenderCompanyNameAsync(request.Scac, ct);
|
||||
var permit = await repository.GetPermitRefAsync(request.Pn, ct) ?? throw OrdersErrors.InvalidPn();
|
||||
// PRICE / FINEPRICE come from the static price table (legacy: readonly inputs filled from the same table).
|
||||
var price = BillingPrices.Get(request.Destination);
|
||||
var finePrice = BillingPrices.Get(request.CargoType);
|
||||
if (price is null || finePrice is null) throw OrdersErrors.PriceNotDefined();
|
||||
|
||||
return await unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
// first billing of the invoice creates it
|
||||
if (invoiceStatus is null) await repository.InsertInvoiceAsync(invoiceNumber, request.Scac, token);
|
||||
var wage = await repository.GetWageRateAsync(request.Destination, request.LoadDate.Date, token);
|
||||
var fine = await repository.GetFineRateAsync(request.LoadDate.Date, token);
|
||||
if (wage is null || fine is null) throw OrdersErrors.RatesNotFound();
|
||||
|
||||
// a permit that is not CLOSE yet is closed by the system when it is billed
|
||||
if (!string.Equals(permit.ShipmentStatusCode, "CLOSE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await repository.ClosePermitAsync(permit.Id, token);
|
||||
await events.AddAsync(new EventEntry(
|
||||
"PERMITID", permit.Id, permit.ShipmentStatusCode, "CLOSE", "SYSTEM", "OVRD", "GN", null, "NTP", null,
|
||||
new Dictionary<string, object?> { ["REMARKS"] = "Billing Close." }), token);
|
||||
}
|
||||
var finalCost = BillingCalculator.Wage(wage.Wage, lnw);
|
||||
var loseFine = BillingCalculator.ShortageFine(lnw, dnw, fine.Allowance, fine.Fine);
|
||||
|
||||
var id = await repository.InsertAsync(new NewGrainsBilling(
|
||||
request.Pn, serialNo, request.Tn.Trim(), request.CargoType, request.Destination,
|
||||
request.LoadDate.Date, request.DischargeDate.Date, dnw, lnw,
|
||||
request.Scac, companyName, invoiceNumber, GrainsOrderConstants.BillingOriginId,
|
||||
wage.Wage, fine.Fine, finalCost, loseFine, user.UserId, request.DemurrageFine, request.OtherFine), token);
|
||||
request.Pn, request.SerialNo.Trim(), request.Tn.Trim(), request.CargoType, request.Destination,
|
||||
request.LoadDate.Date, request.DischargeDate.Date,
|
||||
info.Dtw, info.Dgw, dnw, info.Ltw, info.Lgw, lnw,
|
||||
request.Scac, request.InvoiceNumber, GrainsOrderConstants.BillingOriginId,
|
||||
price.Value, finePrice.Value, finalCost, loseFine, user.UserId), token);
|
||||
|
||||
return new OrdersResult(OrdersErrors.Success, id);
|
||||
}, ct);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>Legacy returned an empty grid when no filter was supplied.</summary>
|
||||
public async Task<PagedResult<BillingDto>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -7,8 +7,7 @@ namespace NTP.Application.Grains.Orders;
|
|||
public interface IOrderReportService
|
||||
{
|
||||
Task<TenderOrderReportDto> GetTenderOrderReportAsync(DateTime orderDate, CancellationToken ct);
|
||||
/// <summary>The legacy tenderOrderReport_xls.cfm Excel (an HTML table opened by Excel).</summary>
|
||||
Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, CancellationToken ct);
|
||||
Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, 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>
|
||||
|
|
@ -63,40 +62,30 @@ public sealed class OrderReportService(IOrderReportRepository repository, ICurre
|
|||
destRows.Sum(x => x.Individuals), destRows.Sum(x => x.Companies));
|
||||
}
|
||||
|
||||
/// <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)
|
||||
public async Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct)
|
||||
{
|
||||
var r = await GetTenderOrderReportAsync(orderDate, ct);
|
||||
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 };
|
||||
string TypeLabel(string? t) => t switch
|
||||
{
|
||||
TenderOrderType.Individuals => L("افراد", "Individuals"),
|
||||
TenderOrderType.Company => L("شركات", "Companies"),
|
||||
_ => string.Empty
|
||||
};
|
||||
|
||||
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 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 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");
|
||||
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}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ financial billing
|
||||
|
|
|
|||
|
|
@ -47,14 +47,14 @@ public sealed record TenderOrderDto(
|
|||
bool? MobileShow,
|
||||
bool CanDelete);
|
||||
|
||||
// Shift (optional): Mobile shift: 1 morning, 2 evening, 3 night (legacy form field SHIFT).
|
||||
// Shift: 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);
|
||||
|
|
@ -97,8 +97,6 @@ public sealed class PermitBillingInfo
|
|||
public decimal Dtw { get; set; }
|
||||
public decimal Dgw { get; set; }
|
||||
public long? LastInvoice { get; set; }
|
||||
/// <summary>PERMITS.SHIPMENTSTATUSCODE (legacy BILLINGSTATUS).</summary>
|
||||
public string? ShipmentStatusCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Billing screen prefill (page JS getAllInformation + price table).</summary>
|
||||
|
|
@ -116,21 +114,9 @@ public sealed record AddBillingRequest(
|
|||
DateTime DischargeDate,
|
||||
long Destination,
|
||||
long CargoType,
|
||||
string Tn,
|
||||
decimal Lnw = 0,
|
||||
decimal Dnw = 0,
|
||||
decimal DemurrageFine = 0,
|
||||
decimal OtherFine = 0);
|
||||
string Tn);
|
||||
|
||||
/// <summary>GRAINS_WAGE row valid on the loading date: <c>Wage</c> is the price per ton (legacy PRICE).</summary>
|
||||
public sealed record WageRate(decimal Wage);
|
||||
|
||||
/// <summary>Permit identity needed to close it when a billing is entered.</summary>
|
||||
public sealed class PermitRef
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? ShipmentStatusCode { get; set; }
|
||||
}
|
||||
public sealed record FineRate(decimal Allowance, decimal Fine);
|
||||
|
||||
public sealed record BillingQuery(string? Tn, long? Pn, long? Scac, string? InvoiceNumber = null)
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ public interface IOrderLookupRepository
|
|||
/// <summary>LOCATIONS where DOMAIN='GN', STATUS=1 and TYPE = EN (loading) or EX (destination).</summary>
|
||||
Task<IReadOnlyList<LookupOptionDto>> GetLocationsAsync(string type, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Invoice.cfc getLocations: every active GN exit location (STATUS=1), AREA NULL first.</summary>
|
||||
/// <summary>Invoice.cfc getLocations: GN exit locations with AREA IS NULL and STATUS=1.</summary>
|
||||
Task<IReadOnlyList<LookupOptionDto>> GetBillingDestinationsAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>register.getDistination: GN exit locations of GN_TYPE 'PCKD', ordered by SORTORDER.</summary>
|
||||
|
|
@ -58,19 +58,9 @@ public interface IQuotaRepository
|
|||
|
||||
public interface IBillingRepository
|
||||
{
|
||||
/// <summary>getBillingInfo: <paramref name="userId"/> scopes the "last invoice" to the user's own billings.</summary>
|
||||
Task<PermitBillingInfo?> GetPermitBillingInfoAsync(long pn, string userId, CancellationToken ct = default);
|
||||
/// <summary>Any non-deleted billing already entered for the permit.</summary>
|
||||
Task<bool> PnExistsAsync(long pn, CancellationToken ct = default);
|
||||
/// <summary>CARGOTYPE of the first non-deleted billing of the invoice (null when the invoice has none).</summary>
|
||||
Task<long?> GetInvoiceCargoTypeAsync(long scac, long invoiceNumber, CancellationToken ct = default);
|
||||
Task InsertInvoiceAsync(long invoiceNumber, long scac, CancellationToken ct = default);
|
||||
/// <summary>NTP_TENDERS_COMPANIES.NAME for the company in the last two tenders.</summary>
|
||||
Task<string?> GetTenderCompanyNameAsync(long scac, CancellationToken ct = default);
|
||||
Task<PermitRef?> GetPermitRefAsync(long pn, CancellationToken ct = default);
|
||||
Task ClosePermitAsync(long permitId, CancellationToken ct = default);
|
||||
Task<PermitBillingInfo?> GetPermitBillingInfoAsync(long pn, CancellationToken ct = default);
|
||||
Task<WageRate?> GetWageRateAsync(long destination, DateTime loadDate, CancellationToken ct = default);
|
||||
Task<FineRate?> GetFineRateAsync(long cargoType, DateTime loadDate, CancellationToken ct = default);
|
||||
Task<FineRate?> GetFineRateAsync(DateTime loadDate, CancellationToken ct = default);
|
||||
Task<long> InsertAsync(NewGrainsBilling billing, CancellationToken ct = default);
|
||||
Task<PagedResult<BillingRow>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<BillingDetailRow?> GetDetailAsync(long id, CancellationToken ct = default);
|
||||
|
|
|
|||
|
|
@ -34,19 +34,10 @@ public static class OrdersErrors
|
|||
new("BILLING_DNW_MISSING", "الوزن المستلم مطلوب");
|
||||
|
||||
public static BusinessException SentWeightRange() =>
|
||||
new("BILLING_LNW_RANGE", "يجب أن يكون الوزن بين 0 - 60000");
|
||||
new("BILLING_LNW_RANGE", "يجب أن يكون الوزن بين 0 - 50000");
|
||||
|
||||
public static BusinessException PriceNotDefined() =>
|
||||
new("BILLING_PRICE_NOT_DEFINED", "لا تسطيع الإضافة - السعر لهذه الوجهة غير معرف");
|
||||
|
||||
public static BusinessException InvoiceCargoMismatch() =>
|
||||
new("BILLING_INVOICE_CARGO_MISMATCH", "لا يجوز ادخال نوع مادة مختلف على نفس الفاتورة");
|
||||
|
||||
public static BusinessException InvoiceArchived() =>
|
||||
new("BILLING_INVOICE_ARCHIVED", "لا تسطيع أضافة مطالبة جديدة لفاتورة مؤرشفة");
|
||||
|
||||
public static BusinessException BillingExists() =>
|
||||
new("BILLING_ALREADY_EXISTS", "المطالبة مدخلة مسبقا");
|
||||
new("BILLING_PRICE_NOT_DEFINED", "لا يوجد سعر محدد لهذه الوجهة أو نوع المادة");
|
||||
|
||||
public static BusinessException RatesNotFound() =>
|
||||
new("BILLING_RATES_NOT_FOUND", "لا توجد أجور أو غرامات محددة لهذه الوجهة في تاريخ التحميل");
|
||||
|
|
@ -148,15 +139,6 @@ public static class BillingCalculator
|
|||
{
|
||||
private static decimal Round3(decimal v) => Math.Round(v, 3, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <summary>Cargo types that may share an invoice: 38 only with 38, 74 only with 74, 39 and 41 together; others are free.</summary>
|
||||
public static bool IsCargoAllowedOnInvoice(long invoiceCargo, long cargo) => invoiceCargo switch
|
||||
{
|
||||
38 => cargo == 38,
|
||||
74 => cargo == 74,
|
||||
39 or 41 => cargo is 39 or 41,
|
||||
_ => true,
|
||||
};
|
||||
|
||||
/// <summary>Net weight: gross minus tare.</summary>
|
||||
public static decimal NetWeight(decimal gross, decimal tare) => gross - tare;
|
||||
|
||||
|
|
@ -176,8 +158,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 60000 (legacy limit was 50000).</summary>
|
||||
public static bool IsSentWeightInRange(decimal lnw) => lnw >= 0 && lnw <= 60000;
|
||||
/// <summary>Page JS checkNumber: sent weight between 0 and 50000.</summary>
|
||||
public static bool IsSentWeightInRange(decimal lnw) => lnw >= 0 && lnw <= 50000;
|
||||
}
|
||||
|
||||
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).When(x => x.Shift.HasValue).WithMessage("الفترة غير صحيحة");
|
||||
RuleFor(x => x.Shift).InclusiveBetween(1, 3).WithMessage("الفترة مطلوبة");
|
||||
RuleFor(x => x.Quantity)
|
||||
.Must(TenderOrderRules.IsQuantityValid).WithMessage("عدد السيارات يجب ان يكون بين 1 - 200");
|
||||
RuleFor(x => x.Type)
|
||||
|
|
@ -40,15 +40,12 @@ public sealed class AddBillingValidator : AbstractValidator<AddBillingRequest>
|
|||
RuleFor(x => x.Pn).GreaterThan(0).WithMessage("رقم الارسالية مطلوب");
|
||||
RuleFor(x => x.Scac).GreaterThan(0).WithMessage("اسم الشركة مطلوب");
|
||||
RuleFor(x => x.InvoiceNumber).GreaterThan(0).WithMessage("رقم المطالبة مطلوب");
|
||||
// GRAINS_BILLING.SERIALNO is numeric, so the document number must be digits
|
||||
RuleFor(x => x.SerialNo).NotEmpty().Matches(@"^[0-9]{1,12}$").WithMessage("رقم المستند مطلوب");
|
||||
RuleFor(x => x.SerialNo).NotEmpty().MaximumLength(30).WithMessage("رقم المستند مطلوب");
|
||||
RuleFor(x => x.LoadDate).NotEmpty().WithMessage("تاريخ التحميل مطلوب");
|
||||
RuleFor(x => x.DischargeDate).NotEmpty().WithMessage("تاريخ التفريغ مطلوب");
|
||||
RuleFor(x => x.Destination).GreaterThan(0).WithMessage("الى مطلوب");
|
||||
RuleFor(x => x.CargoType).GreaterThan(0).WithMessage("نوع المادة مطلوب");
|
||||
RuleFor(x => x.Tn).NotEmpty().MaximumLength(20).WithMessage("رقم السيارة مطلوب");
|
||||
RuleFor(x => x.DemurrageFine).GreaterThanOrEqualTo(0).WithMessage("غرامة التاخير غير صحيحة");
|
||||
RuleFor(x => x.OtherFine).GreaterThanOrEqualTo(0).WithMessage("غرامات أخرى غير صحيحة");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ public interface IDestinationService
|
|||
Task<LocationGroupsDto> GetLocationGroupsAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<CompanyOption>> GetCompaniesAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<long>> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> SaveCompanyDestinationsAsync(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> AssignByPnAsync(AssignByPnRequest request, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<string>> GetOrderDatesAsync(CancellationToken ct = default);
|
||||
|
|
@ -52,6 +53,18 @@ public sealed class DestinationService(
|
|||
public Task<IReadOnlyList<CompanyOption>> GetCompaniesAsync(CancellationToken ct = default) => repo.GetCompaniesAsync(ct);
|
||||
public Task<IReadOnlyList<long>> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default) => repo.GetCompanyLocationsAsync(scac, ct);
|
||||
|
||||
public async Task<PermitOperationResult> SaveCompanyDestinationsAsync(long scac, SaveCompanyDestinationsRequest r, CancellationToken ct = default)
|
||||
{
|
||||
if (scac == options.BadiyaScac)
|
||||
throw new BusinessException("COMPANY_NOT_ALLOWED", "لا يمكن تحديد وجهات للأفراد من هذه الشاشة");
|
||||
await uow.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await repo.ReplaceCompanyLocationsAsync(scac, r.Destinations.Distinct().ToList(), user.UserId, token);
|
||||
return true;
|
||||
}, ct);
|
||||
return PermitOperationResult.Ok(PermitOperationResult.DefaultOk);
|
||||
}
|
||||
|
||||
public async Task<PermitOperationResult> AssignByPnAsync(AssignByPnRequest r, CancellationToken ct = default)
|
||||
{
|
||||
new AssignByPnValidator().ValidateAndThrow(r);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using FluentValidation;
|
||||
using NTP.Application.Abstractions;
|
||||
|
|
@ -36,20 +35,16 @@ public interface IDistributionService
|
|||
}
|
||||
|
||||
/// <summary>Per-user position in the company queue between two "distribute companies" runs (legacy session.QueueStart).</summary>
|
||||
public static class DistributionCursor
|
||||
internal static class DistributionCursor
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, long> Positions = new(StringComparer.OrdinalIgnoreCase);
|
||||
public static long Get(string user) => Positions.GetValueOrDefault(user, 1);
|
||||
public static void Set(string user, long value) => Positions[user] = value;
|
||||
|
||||
/// <summary>Legacy kept it in the session, so every new sign-in starts again from 1.</summary>
|
||||
public static void Reset(string user) => Positions.TryRemove(user, out _);
|
||||
}
|
||||
|
||||
public sealed class DistributionService(
|
||||
IDistributionRepository repo,
|
||||
IDestinationRepository destinations,
|
||||
IDestinationService destinationLookup,
|
||||
IPermitRepository permits,
|
||||
IPhoneEventRepository phoneRepo,
|
||||
IPermitService permitService,
|
||||
|
|
@ -64,8 +59,6 @@ public sealed class DistributionService(
|
|||
|
||||
// ------------------------------------------------------------------------------------------------ distributePackedBulk
|
||||
|
||||
private static BusinessException StateChanged() => new("PERMIT_BAD_STATE", "حالة الارسالية غير صحيحة");
|
||||
|
||||
private sealed record ReleaseOutcome(string ErrorMsg, long? Scac = null, string? CargoLabel = null);
|
||||
|
||||
public async Task<PermitOperationResult> DistributeAsync(DistributeRequest r, CancellationToken ct = default)
|
||||
|
|
@ -144,17 +137,11 @@ public sealed class DistributionService(
|
|||
return true;
|
||||
}, ct);
|
||||
|
||||
// the queue position is saved first: the distribution is already committed, so nothing after this may undo it
|
||||
if (cat.Request is "BULK_COMP" or "BULK_GALLAB_COMP")
|
||||
DistributionCursor.Set(user.UserId, companyCounter == 0 ? start + queueAvailable : 1);
|
||||
|
||||
// notifications are fire-and-forget (legacy ran them in a thread inside try/catch): a failure never fails the run
|
||||
try
|
||||
{
|
||||
await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS", new Dictionary<string, object?> { ["NOTIFICATIONARY"] = ownerNotes }, ct);
|
||||
await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_COMP", companyNotes, ct);
|
||||
}
|
||||
catch (Exception) when (!ct.IsCancellationRequested) { /* already logged by the gateway */ }
|
||||
|
||||
if (cat.Request is "BULK_COMP" or "BULK_GALLAB_COMP")
|
||||
DistributionCursor.Set(user.UserId, companyCounter == 0 ? start + queueAvailable : 1);
|
||||
|
||||
return PermitOperationResult.Ok($"تم توزيع {companyCounter} شركات - {ownerCounter} أفراد ، من أصل{queueAvailable}",
|
||||
data: new Dictionary<string, object?> { ["companies"] = companyCounter, ["owners"] = ownerCounter, ["available"] = queueAvailable });
|
||||
|
|
@ -189,7 +176,7 @@ public sealed class DistributionService(
|
|||
return new("noDist");
|
||||
}
|
||||
|
||||
if (await repo.SetRequestedWithOrderAsync(permit.Id, order.Id, ct) == 0) return new("INVALID PERMITID"); // no longer OPEN (another run took it)
|
||||
await repo.SetRequestedWithOrderAsync(permit.Id, order.Id, ct);
|
||||
var d = await destinations.GetOrderDetailsAsync(order.Id, ct);
|
||||
await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
|
||||
$"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: ct);
|
||||
|
|
@ -231,14 +218,14 @@ public sealed class DistributionService(
|
|||
}
|
||||
if (orderId == 0) throw new BusinessException("NO_ORDERS_AVAILABLE", "لا توجد طلبيات متاحة");
|
||||
|
||||
if (await repo.SetRequestedWithOrderAsync(permit.Id, orderId, token) == 0) throw StateChanged();
|
||||
await repo.SetRequestedWithOrderAsync(permit.Id, orderId, token);
|
||||
var d = await destinations.GetOrderDetailsAsync(orderId, token);
|
||||
await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
|
||||
$"تحميل: {d?.Location} / {d?.CargoType}", ct: token);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (await repo.SetRequestedAsync(permit.Id, token) == 0) throw StateChanged();
|
||||
await repo.SetRequestedAsync(permit.Id, token);
|
||||
await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token);
|
||||
}
|
||||
return true;
|
||||
|
|
@ -253,11 +240,6 @@ public sealed class DistributionService(
|
|||
if (permit.ShipmentStatusCode != PermitStatus.Open)
|
||||
throw new BusinessException("PERMIT_BAD_STATE", "حالة الارسالية غير صحيحة");
|
||||
|
||||
// legacy offered only getAllowedDestinationsByDate(pn, date) in a dropdown; the server now enforces the same list
|
||||
var allowed = await destinationLookup.GetAllowedDestinationsAsync(r.Pn, r.OrderDate, ct);
|
||||
if (!allowed.Any(a => a.OrderId == r.Locations))
|
||||
throw new BusinessException("ORDER_NOT_ALLOWED", "الوجهة المختارة غير مسموحة لهذه الارسالية في هذا التاريخ");
|
||||
|
||||
var order = await repo.GetOrderForManualAsync(r.Locations, ct) ?? throw new NotFoundException("Order", r.Locations);
|
||||
var d = await destinations.GetOrderDetailsAsync(r.Locations, ct);
|
||||
var orderDate = PermitDates.ParseLegacy(r.OrderDate) ?? DateTime.Today;
|
||||
|
|
@ -273,7 +255,7 @@ public sealed class DistributionService(
|
|||
if (order.Ct == GrainsCargo.BulkGallab && scac != options.BadiyaScac)
|
||||
await repo.IncrementCompanyQueueAsync(scac, "GALLAB", "COMP", token);
|
||||
|
||||
if (await repo.SetRequestedManualAsync(permit.Id, r.Locations, queueId, token) == 0) throw StateChanged();
|
||||
await repo.SetRequestedManualAsync(permit.Id, r.Locations, queueId, token);
|
||||
await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
|
||||
$"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: token);
|
||||
|
||||
|
|
@ -312,15 +294,14 @@ public sealed class DistributionService(
|
|||
|
||||
if (await repo.IsLocationAllowedForCompanyAsync(p.CompanyCode ?? 0, order.Destenation, ct))
|
||||
{
|
||||
var changed = await uow.ExecuteInTransactionAsync(async token =>
|
||||
await uow.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
if (await repo.SetRequestedWithOrderAsync(p.Id, order.Id, token) == 0) return false; // taken meanwhile
|
||||
await repo.SetRequestedWithOrderAsync(p.Id, order.Id, token);
|
||||
var d = await destinations.GetOrderDetailsAsync(order.Id, token);
|
||||
await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override,
|
||||
$"تحميل: {d?.Location} / {d?.CargoType}", ct: token);
|
||||
return true;
|
||||
}, ct);
|
||||
if (!changed) continue;
|
||||
done++;
|
||||
if (done >= r.Count) break;
|
||||
}
|
||||
|
|
@ -339,7 +320,7 @@ public sealed class DistributionService(
|
|||
?? throw new BusinessException("TN_INVALID", "TN is invalid");
|
||||
await uow.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
if (await repo.SetRequestedAsync(permit.Id, token) == 0) throw StateChanged();
|
||||
await repo.SetRequestedAsync(permit.Id, token);
|
||||
await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token);
|
||||
return true;
|
||||
}, ct);
|
||||
|
|
@ -367,8 +348,7 @@ 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);
|
||||
// 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));
|
||||
result.CompanyLocations = string.Concat(names.Select(n => " - " + n.Name));
|
||||
|
||||
var orders = await repo.GetActiveOrdersInWindowAsync(new ShiftWindow
|
||||
{
|
||||
|
|
@ -450,7 +430,6 @@ public sealed class DistributionService(
|
|||
public async Task<PermitOperationResult> SendAutoCallFileAsync(AutoCallRequest r, CancellationToken ct = default)
|
||||
{
|
||||
// staff choose the company, company users are limited to their own (GrainsFactoryWeb.autoCallService2)
|
||||
if (user.IsCompany(options) && user.CompanyCodeNo() is null) throw new ForbiddenException("FORBIDDEN", "غير مصرح لك بهذه العملية");
|
||||
var company = user.IsCompany(options) ? user.CompanyCodeNo()?.ToString(CultureInfo.InvariantCulture) : r.CompanyCode;
|
||||
var filter = r with { CompanyCode = company };
|
||||
var tender = PermitService.ParseTenderOrder(r.TenderOrder);
|
||||
|
|
@ -462,13 +441,10 @@ public sealed class DistributionService(
|
|||
: PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي");
|
||||
}
|
||||
|
||||
public async Task<PermitOperationResult> TriggerIvrAsync(CancellationToken ct = default) => await autoCall.TriggerIvrAsync(ct) switch
|
||||
{
|
||||
IvrTriggerResult.Done => PermitOperationResult.Ok(PermitOperationResult.DefaultOk),
|
||||
IvrTriggerResult.Started => PermitOperationResult.Ok("بدأ الاتصال الصوتي وقد تستغرق العملية عدة دقائق"),
|
||||
IvrTriggerResult.Busy => PermitOperationResult.Fail("IVR_RUNNING", "الاتصال الصوتي قيد التنفيذ حاليا، يرجى الانتظار حتى ينتهي"),
|
||||
_ => PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي")
|
||||
};
|
||||
public async Task<PermitOperationResult> TriggerIvrAsync(CancellationToken ct = default) =>
|
||||
await autoCall.TriggerIvrAsync(ct)
|
||||
? PermitOperationResult.Ok(PermitOperationResult.DefaultOk)
|
||||
: PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي");
|
||||
|
||||
/// <summary>writeCallingDriverFile: CSV consumed by the auto dialer.</summary>
|
||||
internal static byte[] BuildCallingFile(IReadOnlyList<AutoCallDriverRow> rows)
|
||||
|
|
@ -489,13 +465,8 @@ public sealed class DistributionService(
|
|||
return new UTF8Encoding(false).GetBytes(sb.ToString());
|
||||
}
|
||||
|
||||
public bool IsValidDialerApiKey(string? key)
|
||||
{
|
||||
var expected = options.AutoCall.ApiKey;
|
||||
if (string.IsNullOrEmpty(expected) || string.IsNullOrEmpty(key)) return false;
|
||||
// constant time: compare fixed-length hashes
|
||||
return CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(key)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
|
||||
}
|
||||
public bool IsValidDialerApiKey(string? key) =>
|
||||
!string.IsNullOrEmpty(options.AutoCall.ApiKey) && string.Equals(key, options.AutoCall.ApiKey, StringComparison.Ordinal);
|
||||
|
||||
/// <summary>autoCallResponse.cfc autoDail: CONFIRMED -> phone accept, POSTPONED -> phone reject for N days, NO_ANSWER -> postpone one day.</summary>
|
||||
public async Task<AutoCallCallbackResult> HandleDialerCallbackAsync(AutoCallResponse r, CancellationToken ct = default)
|
||||
|
|
@ -514,17 +485,12 @@ public sealed class DistributionService(
|
|||
break;
|
||||
case "POSTPONED":
|
||||
{
|
||||
// the manual reject offers 1..30 days; anything larger is a dialer error (and AddDays would overflow)
|
||||
var days = 0;
|
||||
if (!decimal.TryParse(r.Value, NumberStyles.Number, CultureInfo.InvariantCulture, out var dd) || (days = (int)dd) <= 0 || days > MaxPostponeDays)
|
||||
return new("500", "invalid value");
|
||||
if (!int.TryParse(r.Value, out var days) || days <= 0) return new("500", "invalid value");
|
||||
await permitService.PhoneRejectCoreAsync(permitId.Value, $" تم التأجيل {days} يوم", days, "SYSTEM", ct);
|
||||
break;
|
||||
}
|
||||
case "NO_ANSWER":
|
||||
{
|
||||
// a late callback must not reopen a permit that has moved on (confirmed, closed ...)
|
||||
if (permit is null || permit.ShipmentStatusCode != PermitStatus.Requested) return new("200", "IGNORED_STATUS");
|
||||
if (await phoneRepo.HasPhoneEventTodayAsync(permitId.Value, ct)) return new("200", "ALREADY_HAS_PHONE_EVENT");
|
||||
await NoAnswerAsync(permit!, ct);
|
||||
return new("200", "NO_ANSWER");
|
||||
|
|
@ -538,17 +504,15 @@ public sealed class DistributionService(
|
|||
}
|
||||
}
|
||||
|
||||
private const int MaxPostponeDays = 30;
|
||||
|
||||
private async Task NoAnswerAsync(PermitRow permit, CancellationToken ct)
|
||||
{
|
||||
// legacy cleared SCRN before calling BL_addToBlacklist, so its shift lookup found no order and always used shift 1
|
||||
var sh = options.DistributionShift(1);
|
||||
var order = permit.Scrn is long o ? await destinations.GetOrderAsync(o, ct) : null;
|
||||
var sh = options.DistributionShift(order?.Shift ?? 1);
|
||||
await uow.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.NoAnswer,
|
||||
"تم التأجيل ليوم واحد", ct: token);
|
||||
await permits.ReopenClearingOrderAsync(permit.Id, token); // legacy: status + SCRN only (trackingno and audit columns stay)
|
||||
await permits.ResetToOpenAsync(permit.Id, "SYSTEM", token);
|
||||
await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, PermitStatus.Open, PermitEventType.Override, ct: token);
|
||||
await phoneRepo.InsertBlacklistAsync(new NewBlacklistEntry
|
||||
{
|
||||
|
|
|
|||
|
|
@ -77,48 +77,14 @@ public sealed class AutoCallOptions
|
|||
public string ApiKey { get; set; } = string.Empty;
|
||||
|
||||
public int TimeoutSeconds { get; set; } = 30;
|
||||
|
||||
/// <summary>How long the voice-call button waits for the IVR service before it reports "started" (the service answers only when it has dialed everybody).</summary>
|
||||
public int IvrWaitSeconds { get; set; } = 20;
|
||||
|
||||
/// <summary>Longest time one IVR call may keep running in the background before it is abandoned.</summary>
|
||||
public int IvrTimeoutMinutes { get; set; } = 15;
|
||||
}
|
||||
|
||||
/// <summary>Mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage).</summary>
|
||||
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;
|
||||
|
||||
public string Url { get; set; } = string.Empty;
|
||||
public int TimeoutSeconds { get; set; } = 15;
|
||||
|
||||
/// <summary>Legacy application.SEND_SMS_GN_DIST: an SMS (with the app download link) goes to a truck owner / driver who has an account
|
||||
/// but no app installed, when the truck is distributed. 0 in development and QA, 1 in production.</summary>
|
||||
public bool SendSmsToOwnersWithoutApp { get; set; }
|
||||
|
||||
/// <summary>App download link added to that SMS (legacy hard-coded http://onelink.to/bhbrvb).</summary>
|
||||
public string AppLink { get; set; } = "http://onelink.to/bhbrvb";
|
||||
|
||||
public SmsOptions Sms { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <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
|
||||
{
|
||||
/// <summary>Legacy application.SEND_SMS = 'enabled'.</summary>
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>JORMALL (josms.net) or UNIFONIC. UNVERIFIED for this application: the sibling AqabaTCS app uses JorMall.</summary>
|
||||
public string Provider { get; set; } = "JORMALL";
|
||||
|
||||
public string SenderId { get; set; } = "Nafith";
|
||||
public string UserName { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>External weighbridge database (legacy datasource GrainsWeighbridge, table CARGO).</summary>
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@ public interface IDistributionRepository
|
|||
Task<PermitRow?> GetOpenPermitWithFirmsAsync(string pn, long scac, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<long>> GetAllowedLocationsForReleaseAsync(PermitRow permit, long scac, long badiyaScac, CancellationToken ct = default);
|
||||
Task<NextOrderPick?> GetNextOrderAsync(IReadOnlyList<long> locations, string cargoCode, string? queueType, CancellationToken ct = default);
|
||||
Task<int> SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default);
|
||||
Task SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default);
|
||||
Task UpdateLastPermitAsync(long orderId, long badiyaScac, CancellationToken ct = default);
|
||||
Task SetLastPermitAsync(long orderId, long permitId, CancellationToken ct = default);
|
||||
Task DeletePendingDistributionAsync(long permitId, string tn, long? orderId, CancellationToken ct = default);
|
||||
|
|
@ -86,10 +86,10 @@ public interface IDistributionRepository
|
|||
Task<PermitRow?> GetFirstOpenPermitByTnAsync(string tn, string? cargoType, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<NextOrderPick>> GetNextOrdersForTruckAsync(string tn, CancellationToken ct = default);
|
||||
Task<bool> IsLocationAllowedForCompanyAsync(long scac, long location, CancellationToken ct = default);
|
||||
Task<int> SetRequestedAsync(long permitId, CancellationToken ct = default);
|
||||
Task SetRequestedAsync(long permitId, CancellationToken ct = default);
|
||||
Task<OrderForPermitRow?> GetOrderForManualAsync(long orderId, CancellationToken ct = default);
|
||||
Task<long?> PickQueueIdAsync(long scac, string code, string? type, CancellationToken ct = default);
|
||||
Task<int> SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default);
|
||||
Task SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<PermitRow>> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default);
|
||||
Task<NextOrderPick?> GetAnyNextOrderAsync(CancellationToken ct = default);
|
||||
|
||||
|
|
|
|||
|
|
@ -96,9 +96,6 @@ public interface IPermitRepository
|
|||
Task SetStatusAsync(long id, string newStatus, string userId, CancellationToken ct = default);
|
||||
Task ResetTruckValidationAsync(string tn, string userId, CancellationToken ct = default);
|
||||
Task ResetToOpenAsync(long id, string userId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>NO_ANSWER of the dialer (autoCallResponse.cfc): only the status goes back to OPEN and the order link (SCRN) is cleared; nothing else changes.</summary>
|
||||
Task ReopenClearingOrderAsync(long id, CancellationToken ct = default);
|
||||
Task RevokeNextOpenPermitsAsync(long permitId, string userId, CancellationToken ct = default);
|
||||
Task<ActiveConflictRow?> FindOpenConflictForReactivationAsync(PermitRow permit, CancellationToken ct = default);
|
||||
Task<PermitRow?> FindClosablePermitAsync(string pn, CancellationToken ct = default);
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
namespace NTP.Application.Grains.Permits;
|
||||
|
||||
/// <summary>NOTIFICATIONMESSAGETEMPLATE row (title and text with VAR1..VARn placeholders), looked up by TYPE.</summary>
|
||||
public sealed class NotificationTemplateRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Title { get; set; }
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>USERDEVICEINFO row of an ACTIVE device.</summary>
|
||||
public sealed class DeviceRow
|
||||
{
|
||||
public string? FcmToken { get; set; }
|
||||
public string? Os { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Phone number and company (TCSCAC) of a registered truck.</summary>
|
||||
public sealed class TruckContactRow
|
||||
{
|
||||
public string? Phone { get; set; }
|
||||
public long? Scac { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One push message to one device (the legacy SendNotificationToFirebase arguments).</summary>
|
||||
public sealed record PushMessage(string Token, string Message, string Title, long UserId, string Os, long TemplateId, string Phone, string Tn);
|
||||
|
||||
/// <summary>Reads for the mobile notifications (legacy NTP.components.MobileNotifications): users, devices, templates, SMS log.</summary>
|
||||
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);
|
||||
|
||||
Task<IReadOnlyList<DeviceRow>> GetActiveDevicesAsync(long userId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The GN truck that is not revoked: its owner / driver phone and its company.</summary>
|
||||
Task<TruckContactRow?> GetTruckContactAsync(string tn, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Login of the active dispatcher (role DISP) of a company.</summary>
|
||||
Task<string?> GetCompanyDispatcherLoginAsync(long scac, 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>
|
||||
public interface IPushGatewayService
|
||||
{
|
||||
Task<bool> SendAsync(PushMessage message, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>SMS provider (legacy NTP.components.SMS.sendSMS); also writes USER_SMS_LOGS.</summary>
|
||||
public interface ISmsGatewayService
|
||||
{
|
||||
/// <param name="mobile">International format with a leading plus, e.g. +9627...</param>
|
||||
Task SendAsync(string mobile, string text, string userId, string serviceType, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
using System.Collections;
|
||||
using System.Globalization;
|
||||
|
||||
namespace NTP.Application.Grains.Permits;
|
||||
|
||||
/// <summary>Pure rules of the mobile notifications (legacy MobileNotifications.cfc), kept apart so they can be tested.</summary>
|
||||
public static class NotificationRules
|
||||
{
|
||||
/// <summary>Template types (NOTIFICATIONMESSAGETEMPLATE.TYPE) used by the grains screens.</summary>
|
||||
public const string DistributeOwners = "DISTRIBUTE_PACKED_BULK_OWNERS";
|
||||
public const string DistributeOwnersCompanies = "DISTRIBUTE_PACKED_BULK_OWNERS_COMPANIES";
|
||||
public const string DistributeCompanies = "DISTRIBUTE_PACKED_BULK_COMP";
|
||||
public const string ConfirmPn = "CONFIRM_PN";
|
||||
public const string PhoneReject = "PHONE_REJECT";
|
||||
public const string DelayPn = "DELAY_PN";
|
||||
public const string SmsWithoutApp = "DISTRIBUTE_GRAINS_SMS_TO_USER_WITHNO_APP";
|
||||
|
||||
/// <summary>Driver and truck-owner app accounts are found by the truck's phone number.</summary>
|
||||
public static readonly string[] PhoneRoles = ["DRVR", "TRKOWNER"];
|
||||
|
||||
/// <summary>Company dispatchers (role DISP) are found by a login that contains {SCAC}DSP.</summary>
|
||||
public const string DispatcherRole = "DISP";
|
||||
|
||||
/// <summary>
|
||||
/// ColdFusion <c>Replace(msg, 'VAR1', value)</c> for VAR1..VARn: each placeholder is replaced once (first occurrence), in order.
|
||||
/// </summary>
|
||||
public static string Fill(string template, params object?[] values)
|
||||
{
|
||||
var text = template;
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
{
|
||||
var key = "VAR" + (i + 1).ToString(CultureInfo.InvariantCulture);
|
||||
var at = text.IndexOf(key, StringComparison.Ordinal);
|
||||
if (at >= 0) text = string.Concat(text.AsSpan(0, at), Text(values[i]), text.AsSpan(at + key.Length));
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>Value as the legacy string concatenation would show it (dates as dd/MM/yyyy, no culture dependence).</summary>
|
||||
public static string Text(object? v) => v switch
|
||||
{
|
||||
null => string.Empty,
|
||||
string s => s,
|
||||
DateTime d => d.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
|
||||
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
|
||||
_ => v.ToString() ?? string.Empty
|
||||
};
|
||||
|
||||
/// <summary>SMS_toUsersWithNoMobileApplication: 0791234567 -> +962791234567 (mid(phone, 2, 15)); a number without a leading 0 only gets the prefix.</summary>
|
||||
public static string SmsNumber(string phone)
|
||||
{
|
||||
var p = phone.Trim();
|
||||
return p.StartsWith('0') ? "+962" + (p.Length > 16 ? p[1..16] : p[1..]) : "+962" + p;
|
||||
}
|
||||
|
||||
/// <summary>The message plus the app download link, as SMS_toUsersWithNoMobileApplication builds it.</summary>
|
||||
public static string SmsText(string template, string appLink) => template + "، للتفاصيل الرجاء الضغط على الرابط" + appLink;
|
||||
|
||||
/// <summary>Items of NOTIFICATIONARY as string maps (the callers pass dictionaries of mixed value types).</summary>
|
||||
public static IReadOnlyList<IReadOnlyDictionary<string, string>> Entries(IReadOnlyDictionary<string, object?> payload)
|
||||
{
|
||||
var list = new List<IReadOnlyDictionary<string, string>>();
|
||||
if (!payload.TryGetValue("NOTIFICATIONARY", out var raw) || raw is not IEnumerable items || raw is string) return list;
|
||||
foreach (var item in items)
|
||||
{
|
||||
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (item is IEnumerable<KeyValuePair<string, object?>> pairs)
|
||||
foreach (var (k, v) in pairs) map[k] = Text(v);
|
||||
list.Add(map);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static string Get(IReadOnlyDictionary<string, string> map, string key) => map.TryGetValue(key, out var v) ? v : string.Empty;
|
||||
|
||||
public static string Get(IReadOnlyDictionary<string, object?> map, string key) => map.TryGetValue(key, out var v) ? Text(v) : string.Empty;
|
||||
}
|
||||
|
|
@ -613,34 +613,6 @@ public sealed class AutoCallDriverRow
|
|||
}
|
||||
|
||||
/// <summary>Body of the dialer's callback (autoDail): referenceId = PN, key = CONFIRMED | POSTPONED | NO_ANSWER.</summary>
|
||||
public sealed record AutoCallResponse(string? ReferenceId, string? Key, string? Value)
|
||||
{
|
||||
/// <summary>
|
||||
/// autoCallResponse.cfc read the raw body as UTF-8 and deserialized it, so field names are case-insensitive and a number is as good as a
|
||||
/// string (the provider may send referenceId or value as a JSON number). Throws <see cref="System.Text.Json.JsonException"/> on bad JSON.
|
||||
/// </summary>
|
||||
public static AutoCallResponse FromJson(string json)
|
||||
{
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(json);
|
||||
if (doc.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) throw new FormatException("The body is not a JSON object");
|
||||
string? Get(string name)
|
||||
{
|
||||
foreach (var p in doc.RootElement.EnumerateObject())
|
||||
{
|
||||
if (!string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
return p.Value.ValueKind switch
|
||||
{
|
||||
System.Text.Json.JsonValueKind.String => p.Value.GetString(),
|
||||
System.Text.Json.JsonValueKind.Number => p.Value.GetRawText(),
|
||||
System.Text.Json.JsonValueKind.True => "true",
|
||||
System.Text.Json.JsonValueKind.False => "false",
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return new AutoCallResponse(Get("referenceId"), Get("key"), Get("value"));
|
||||
}
|
||||
}
|
||||
public sealed record AutoCallResponse(string? ReferenceId, string? Key, string? Value);
|
||||
|
||||
public sealed record AutoCallCallbackResult(string Code, string Message);
|
||||
|
|
|
|||
|
|
@ -1,50 +0,0 @@
|
|||
using NTP.Application.Abstractions;
|
||||
using NTP.Domain.Grains.Permits;
|
||||
|
||||
namespace NTP.Application.Grains.Permits;
|
||||
|
||||
/// <summary>A permit that jobs/GRAINS_Close_Old_Permits.cfm closes.</summary>
|
||||
public sealed class OldPermitRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Status { get; set; }
|
||||
}
|
||||
|
||||
public interface IPermitJobsRepository
|
||||
{
|
||||
/// <summary>The four groups of jobs/GRAINS_Close_Old_Permits.cfm (see the repository for the rules).</summary>
|
||||
Task<IReadOnlyList<OldPermitRow>> GetOldPermitsToCloseAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Sets CLOSE only while the permit still has the status it was found with; returns the rows changed.</summary>
|
||||
Task<int> CloseAsync(long permitId, string previousStatus, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IPermitJobsService
|
||||
{
|
||||
/// <summary>jobs/GRAINS_Close_Old_Permits.cfm. Returns the number of permits closed.</summary>
|
||||
Task<int> CloseOldPermitsAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public sealed class PermitJobsService(IPermitJobsRepository repo, IEventLogger events, IUnitOfWork uow) : IPermitJobsService
|
||||
{
|
||||
public async Task<int> CloseOldPermitsAsync(CancellationToken ct = default)
|
||||
{
|
||||
var rows = await repo.GetOldPermitsToCloseAsync(ct);
|
||||
var seen = new HashSet<long>();
|
||||
var closed = 0;
|
||||
foreach (var row in rows)
|
||||
{
|
||||
// the legacy query is a UNION ALL: one permit can appear in several groups and was then closed (and logged) several times
|
||||
if (!seen.Add(row.Id)) continue;
|
||||
var previous = row.Status ?? string.Empty;
|
||||
var done = await uow.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
if (await repo.CloseAsync(row.Id, previous, token) == 0) return false; // its status changed since the query
|
||||
await events.LogAsAsync("SYSTEM", null, row.Id, previous, PermitStatus.Closed, PermitEventType.Override, "System Close.", ct: token);
|
||||
return true;
|
||||
}, ct);
|
||||
if (done) closed++;
|
||||
}
|
||||
return closed;
|
||||
}
|
||||
}
|
||||
|
|
@ -203,8 +203,8 @@ public sealed class PermitService(
|
|||
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
|
||||
EnsureCompanyAccess(permit.CompanyCode);
|
||||
|
||||
// only a requested turn is submitted (legacy: the button exists for REQST only); through the API any other status used to pass
|
||||
if (permit.ShipmentStatusCode != PermitStatus.Requested)
|
||||
// legacy: an order already ACCPT / RESD cannot be submitted again.
|
||||
if (permit.ShipmentStatusCode is PermitStatus.Released or PermitStatus.Accepted)
|
||||
throw new BusinessException("PERMIT_BAD_STATE", PermitAssignmentRules.BadStatus);
|
||||
|
||||
await ValidateAssignmentAsync(permit, r.Tn, r.Trn, r.Nnpn, isSubmit: true, ct);
|
||||
|
|
@ -294,7 +294,6 @@ public sealed class PermitService(
|
|||
|
||||
public async Task<PermitOperationResult> AcceptAsync(long id, CancellationToken ct = default)
|
||||
{
|
||||
EnsureStaff();
|
||||
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
|
||||
EnsureCompanyAccess(permit.CompanyCode);
|
||||
if (permit.ShipmentStatusCode != PermitStatus.Planned)
|
||||
|
|
@ -332,7 +331,6 @@ public sealed class PermitService(
|
|||
|
||||
public async Task<PermitOperationResult> RevokeAsync(long id, CancellationToken ct = default)
|
||||
{
|
||||
EnsureStaff();
|
||||
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
|
||||
EnsureCompanyAccess(permit.CompanyCode);
|
||||
if (permit.ShipmentStatusCode != PermitStatus.Planned)
|
||||
|
|
@ -350,7 +348,6 @@ public sealed class PermitService(
|
|||
|
||||
public async Task<PermitOperationResult> RevokeAcceptedAsync(long id, CancellationToken ct = default)
|
||||
{
|
||||
EnsureStaff();
|
||||
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
|
||||
EnsureCompanyAccess(permit.CompanyCode);
|
||||
if (permit.ShipmentStatusCode is not (PermitStatus.Accepted or PermitStatus.Released))
|
||||
|
|
@ -386,7 +383,6 @@ public sealed class PermitService(
|
|||
|
||||
public async Task<PermitOperationResult> CancelOrderAsync(long id, ReasonRequest r, CancellationToken ct = default)
|
||||
{
|
||||
EnsureOperator();
|
||||
new ReasonValidator().ValidateAndThrow(r);
|
||||
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
|
||||
// Deviation: the legacy button exists for RESD only (action 106) but the CFC had no check.
|
||||
|
|
@ -406,7 +402,6 @@ public sealed class PermitService(
|
|||
|
||||
public async Task<PermitOperationResult> RevokePermitAsync(long id, ReasonRequest r, CancellationToken ct = default)
|
||||
{
|
||||
EnsureOperator();
|
||||
new ReasonValidator().ValidateAndThrow(r);
|
||||
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
|
||||
// Deviation: legacy button exists for OPEN only (action 167); enforced here.
|
||||
|
|
@ -424,10 +419,7 @@ public sealed class PermitService(
|
|||
|
||||
public async Task<PermitOperationResult> ReactivateAsync(long id, CancellationToken ct = default)
|
||||
{
|
||||
// legacy: only the reactivation login, and only for the Badiya company permits (the button is hidden otherwise)
|
||||
if (user.IsCompany(options) || !user.IsInAnyRole("SU", "GTO", "CO")) throw NotAllowed();
|
||||
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
|
||||
if (permit.CompanyCode != options.BadiyaScac) throw NotAllowed();
|
||||
if (permit.ShipmentStatusCode != PermitStatus.Revoked)
|
||||
throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة");
|
||||
|
||||
|
|
@ -447,7 +439,6 @@ public sealed class PermitService(
|
|||
|
||||
public async Task<PermitOperationResult> CancelGrainsPermitAsync(long id, CancellationToken ct = default)
|
||||
{
|
||||
EnsureOperator();
|
||||
var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id);
|
||||
if (permit.ShipmentStatusCode != PermitStatus.Released)
|
||||
throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة");
|
||||
|
|
@ -479,15 +470,11 @@ public sealed class PermitService(
|
|||
|
||||
// ------------------------------------------------------------------------------------------------ phone events
|
||||
|
||||
public Task<PermitOperationResult> PhoneAcceptAsync(long id, PhoneAcceptRequest r, CancellationToken ct = default)
|
||||
{
|
||||
EnsureOperator(); // the dialer callback uses PhoneAcceptCoreAsync directly, not this entry point
|
||||
return PhoneAcceptCoreAsync(id, r.Remarks, user.UserId, ct);
|
||||
}
|
||||
public Task<PermitOperationResult> PhoneAcceptAsync(long id, PhoneAcceptRequest r, CancellationToken ct = default) =>
|
||||
PhoneAcceptCoreAsync(id, r.Remarks, user.UserId, ct);
|
||||
|
||||
public Task<PermitOperationResult> PhoneRejectAsync(long id, PhoneRejectRequest r, CancellationToken ct = default)
|
||||
{
|
||||
EnsureOperator();
|
||||
new PhoneRejectValidator().ValidateAndThrow(r);
|
||||
return PhoneRejectCoreAsync(id, r.Reason.Trim(), r.ExpiryDays, user.UserId, ct);
|
||||
}
|
||||
|
|
@ -638,26 +625,11 @@ public sealed class PermitService(
|
|||
|
||||
private IReadOnlyList<string> ActionsFor(string? status, long? companyCode) =>
|
||||
PermitActionRules.For(status, companyCode, user.IsCompany(options), user.IsInAnyRole(GrainsRoles.Operators.Split(',')),
|
||||
user.IsInAnyRole(GrainsRoles.ConvertToResd.Split(',')), user.IsInAnyRole("SU", "GTO", "CO"), options.BadiyaScac);
|
||||
|
||||
private static ForbiddenException NotAllowed() => new("FORBIDDEN", "غير مصرح لك بهذه العملية");
|
||||
|
||||
/// <summary>Staff-only actions (phone confirmation, cancel / revoke): back-office operators, never a company user or dispatcher.</summary>
|
||||
private void EnsureOperator()
|
||||
{
|
||||
if (user.IsCompany(options) || !user.IsInAnyRole(GrainsRoles.Operators.Split(','))) throw NotAllowed();
|
||||
}
|
||||
|
||||
/// <summary>Confirming a turn (accept / reject / cancel the confirmation) is back-office work: legacy actions 74, 85, 88 are not held by company dispatchers.</summary>
|
||||
private void EnsureStaff()
|
||||
{
|
||||
if (user.IsCompany(options)) throw NotAllowed();
|
||||
}
|
||||
user.IsInAnyRole(GrainsRoles.ConvertToResd.Split(',')), user.IsInAnyRole("SU", "GTO"), options.BadiyaScac);
|
||||
|
||||
private void EnsureCompanyAccess(long? permitCompany)
|
||||
{
|
||||
// a company user without a company code owns nothing (null == null must not pass)
|
||||
if (user.IsCompany(options) && (user.CompanyCodeNo() is not long mine || permitCompany != mine))
|
||||
if (user.IsCompany(options) && permitCompany != user.CompanyCodeNo())
|
||||
throw new ForbiddenException("PERMIT_FOREIGN_COMPANY", "لا تملك صلاحية على هذه الإرسالية");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -11,16 +11,16 @@ namespace NTP.Application.Grains.Permits;
|
|||
public static class GrainsRoles
|
||||
{
|
||||
/// <summary>Back-office operators: distribution, phone confirmation, manual operations, queue creation.</summary>
|
||||
public const string Operators = "SU,GPO,GNSU,GNCO,GTO,CO";
|
||||
public const string Operators = "SU,GPO,GNSU,GNCO,GTO";
|
||||
|
||||
/// <summary>Weighbridge / gate users plus operators.</summary>
|
||||
public const string Weighbridge = "SU,GPO,GNSU,GNCO,GTO,CO,GATEIN,GATEOUT,THRU";
|
||||
public const string Weighbridge = "SU,GPO,GNSU,GNCO,GTO,GATEIN,GATEOUT,THRU";
|
||||
|
||||
/// <summary>ConvertToResd button: legacy checks role SU or GPO only.</summary>
|
||||
public const string ConvertToResd = "SU,GPO";
|
||||
|
||||
/// <summary>Supervisors: configuration of destinations, activation of orders, absence feature.</summary>
|
||||
public const string Supervisors = "SU,GPO,GNSU,GTO,CO";
|
||||
public const string Supervisors = "SU,GPO,GNSU,GTO";
|
||||
}
|
||||
|
||||
/// <summary>Helpers that replace legacy session.* lookups.</summary>
|
||||
|
|
@ -100,10 +100,8 @@ public static class PermitActionRules
|
|||
|
||||
if (isCompany)
|
||||
{
|
||||
// Company users never see the staff-only buttons. Confirming (accept / reject / cancel the confirmation) is staff work in
|
||||
// legacy too: actions 74, 85 and 88 belong to the staff groups, the company dispatcher group DISP only holds submit (73).
|
||||
a.RemoveAll(x => x is PhoneAccept or PhoneReject or CancelOrder or RevokePermit or Reactivate or ConvertToResd
|
||||
or Accept or Reject or RevokeAccepted);
|
||||
// Company users never see the staff-only phone / cancel / revoke / reactivate buttons.
|
||||
a.RemoveAll(x => x is PhoneAccept or PhoneReject or CancelOrder or RevokePermit or Reactivate or ConvertToResd);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
|
@ -147,21 +145,8 @@ public interface IAutoCallGatewayService
|
|||
/// <summary>POSTs {"TYPE":"TEST","FILE":base64} to the configured dialer URL; false when not reachable / not 200.</summary>
|
||||
Task<bool> SendCallFileAsync(byte[] csv, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Calls the IVR web service (callAPI). That call dials every requested truck one by one and can take minutes.</summary>
|
||||
Task<IvrTriggerResult> TriggerIvrAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Outcome of <see cref="IAutoCallGatewayService.TriggerIvrAsync"/>.</summary>
|
||||
public enum IvrTriggerResult
|
||||
{
|
||||
/// <summary>The IVR service answered OK.</summary>
|
||||
Done,
|
||||
/// <summary>The IVR service accepted the call and is still dialing (it answers when it has finished).</summary>
|
||||
Started,
|
||||
/// <summary>A previous call is still running: a second one would dial every truck twice.</summary>
|
||||
Busy,
|
||||
/// <summary>Disabled, not configured, unreachable or refused.</summary>
|
||||
Failed
|
||||
/// <summary>Calls the IVR web service (callAPI).</summary>
|
||||
Task<bool> TriggerIvrAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Reads new rows from the external weighbridge database (legacy datasource GrainsWeighbridge).</summary>
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ public sealed class BlacklistService(
|
|||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user) : IBlacklistService
|
||||
{
|
||||
private static readonly string[] CancelRoles = ["GNSU", "GNCO", "GTO", "CO"];
|
||||
private static readonly string[] CancelRoles = ["GNSU", "GNCO", "GTO"];
|
||||
|
||||
public async Task<PagedResult<BlacklistGridRowDto>> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
|
|
@ -54,9 +54,8 @@ public sealed class BlacklistService(
|
|||
permitId = await repository.FindPermitIdByNumberAsync(number, ct)
|
||||
?? throw new BusinessException(RegistryErrors.PermitNotFound, RegistryMessages.PermitNotFound(number));
|
||||
entityId = permitId.ToString(CultureInfo.InvariantCulture);
|
||||
// Legacy BL_addToBlacklist looks the shift up with "p.id = ENTITYNUM": that matches only when the permit id itself was sent
|
||||
// (IsId). A typed permit number never matches, so it always used shift 1.
|
||||
if (request.IsId) shift = await repository.GetPermitShiftAsync(permitId, ct) ?? 1;
|
||||
// shift of the tender order of the permit (default 1)
|
||||
shift = await repository.GetPermitShiftAsync(permitId, ct) ?? 1;
|
||||
}
|
||||
|
||||
var (start, end) = settings.ShiftHours(shift);
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ public sealed class RegistryAccessService(
|
|||
|
||||
public void EnsureCompanyAccess(long? recordTcscac)
|
||||
{
|
||||
if (IsCompanyUser && (CompanyCodeNo is null || recordTcscac != CompanyCodeNo))
|
||||
if (IsCompanyUser && recordTcscac != CompanyCodeNo)
|
||||
throw new NotFoundException("Registry record", "-");
|
||||
}
|
||||
|
||||
|
|
@ -87,9 +87,9 @@ public sealed class RegistryAccessService(
|
|||
CanAcceptTrailer = await HasActionAsync(RegistryActions.AcceptTrailer, ct),
|
||||
CanAcceptDriver = await HasActionAsync(RegistryActions.AcceptDriver, ct),
|
||||
CanManageDestinations = await HasActionAsync(RegistryActions.Destinations, ct),
|
||||
CanExportTruckReport = user.IsInAnyRole("GTO", "CO", "GOO", "GNAC"),
|
||||
CanExportDriverReport = user.IsInAnyRole("GTO", "CO", "GOO"),
|
||||
CanCancelBlacklist = user.IsInAnyRole("GNSU", "GNCO", "GTO", "CO")
|
||||
CanExportTruckReport = user.IsInAnyRole("GTO", "GOO", "GNAC"),
|
||||
CanExportDriverReport = user.IsInAnyRole("GTO", "GOO"),
|
||||
CanCancelBlacklist = user.IsInAnyRole("GNSU", "GNCO", "GTO")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,23 +15,8 @@ public interface IRegistryAttachmentService
|
|||
}
|
||||
|
||||
public sealed class RegistryAttachmentService(
|
||||
IRegistryRepository repository, IRegistryFileStoreService store, IRegistrySettingsService settings, IRegistryAccessService access)
|
||||
: IRegistryAttachmentService
|
||||
IRegistryRepository repository, IRegistryFileStoreService store, IRegistrySettingsService settings) : IRegistryAttachmentService
|
||||
{
|
||||
/// <summary>GRAINS_FILES.ORIGINALNAME is VARCHAR2(100).</summary>
|
||||
public const int OriginalNameMaxBytes = 100;
|
||||
|
||||
/// <summary>Shortens a file name to the column size (UTF-8 bytes), keeping the extension.</summary>
|
||||
public static string FitOriginalName(string name)
|
||||
{
|
||||
name = name.Trim();
|
||||
if (System.Text.Encoding.UTF8.GetByteCount(name) <= OriginalNameMaxBytes) return name;
|
||||
var ext = Path.GetExtension(name);
|
||||
var stem = name[..^ext.Length];
|
||||
while (stem.Length > 0 && System.Text.Encoding.UTF8.GetByteCount(stem + ext) > OriginalNameMaxBytes) stem = stem[..^1];
|
||||
return stem + ext;
|
||||
}
|
||||
|
||||
public const string KindTruck = "truck";
|
||||
public const string KindTrailer = "trailer";
|
||||
public const string KindDriver = "driver";
|
||||
|
|
@ -74,7 +59,7 @@ public sealed class RegistryAttachmentService(
|
|||
?? throw new BusinessException(RegistryErrors.AttachmentMissing, RegistryMessages.AttachmentsIncomplete);
|
||||
var ext = Path.GetExtension(original);
|
||||
var stored = $"{Guid.NewGuid():N}{ext.ToLowerInvariant()}";
|
||||
await repository.InsertFileAsync(type, entityId, FitOriginalName(original), stored, ct);
|
||||
await repository.InsertFileAsync(type, entityId, original, stored, ct);
|
||||
await store.PromoteAsync(id, folder, stored, ct);
|
||||
}
|
||||
}
|
||||
|
|
@ -91,14 +76,6 @@ public sealed class RegistryAttachmentService(
|
|||
var (type, folder) = Map(kind);
|
||||
// The name must be a registered file of this type (also keeps path traversal out).
|
||||
var row = await repository.FindFileAsync(type, fileName, ct) ?? throw new NotFoundException("Attachment", fileName);
|
||||
// a company user may only read the files of its own trucks / trailers / drivers
|
||||
long? owner = kind.ToLowerInvariant() switch
|
||||
{
|
||||
KindTruck => (await repository.GetTruckAsync(row.EntityId, ct))?.Tcscac,
|
||||
KindTrailer => (await repository.GetTrailerAsync(row.EntityId, ct))?.Tcscac,
|
||||
_ => (await repository.GetDriverAsync(row.EntityId, ct))?.Tcscac
|
||||
};
|
||||
access.EnsureCompanyAccess(owner);
|
||||
var stream = await store.OpenAsync(folder, row.FileName, ct) ?? throw new NotFoundException("Attachment", fileName);
|
||||
return new RegistryDownload(stream, ContentTypeOf(row.FileName), string.IsNullOrWhiteSpace(row.OriginalName) ? row.FileName : row.OriginalName);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,92 +0,0 @@
|
|||
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");
|
||||
}
|
||||
}
|
||||
|
|
@ -182,36 +182,9 @@ public static class RegistryRules
|
|||
public static DateTime BlacklistExpiry(DateTime now, int days, int shiftStartHour, int shiftEndHour) =>
|
||||
now.AddHours(-(24 + shiftStartHour)).Date.AddDays(days).AddHours(shiftEndHour);
|
||||
|
||||
/// <summary>GRAINSBLACKLIST.REMARKS is VARCHAR2(500): the limit is in bytes, and an Arabic letter takes two.</summary>
|
||||
public const int BlacklistRemarksMaxBytes = 500;
|
||||
|
||||
/// <summary>Cuts a text to at most <paramref name="maxBytes"/> UTF-8 bytes without splitting a character.</summary>
|
||||
public static string FitBytes(string? text, int maxBytes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return string.Empty;
|
||||
if (System.Text.Encoding.UTF8.GetByteCount(text) <= maxBytes) return text;
|
||||
var sb = new System.Text.StringBuilder();
|
||||
var used = 0;
|
||||
foreach (var rune in text.EnumerateRunes())
|
||||
{
|
||||
var n = rune.Utf8SequenceLength;
|
||||
if (used + n > maxBytes) break;
|
||||
sb.Append(rune.ToString());
|
||||
used += n;
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remarks text stored with the entry (legacy appends the automatic release date, mm/dd/yyyy HH:mm). The typed text is shortened,
|
||||
/// never the release-date suffix, so that the whole text fits the column.
|
||||
/// </summary>
|
||||
public static string BlacklistRemarks(string? remarks, DateTime expiry)
|
||||
{
|
||||
var suffix = $"، سيتم فك الانتظار بشكل تلقائي بتاريخ {expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)}";
|
||||
var room = Math.Max(0, BlacklistRemarksMaxBytes - System.Text.Encoding.UTF8.GetByteCount(suffix));
|
||||
return FitBytes(remarks, room) + suffix;
|
||||
}
|
||||
/// <summary>Remarks text stored with the entry (legacy appends the automatic release date, mm/dd/yyyy HH:mm).</summary>
|
||||
public static string BlacklistRemarks(string? remarks, DateTime expiry) =>
|
||||
$"{remarks}، سيتم فك الانتظار بشكل تلقائي بتاريخ {expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)}";
|
||||
|
||||
/// <summary>Parses the legacy "start,end" application setting; falls back to the defaults.</summary>
|
||||
public static (int Start, int End) ParseShiftHours(string? setting, int defaultStart = 0, int defaultEnd = 24)
|
||||
|
|
|
|||
|
|
@ -92,9 +92,9 @@ public static class RegistryValidation
|
|||
MaxLen(f, nameof(r.ChasesNumber), r.ChasesNumber, 20);
|
||||
MaxLen(f, nameof(r.OwnerName), r.OwnerName, 50);
|
||||
MaxLen(f, nameof(r.OwnerNnpn), r.OwnerNnpn, 20);
|
||||
MaxLen(f, nameof(r.Color), r.Color, 20);
|
||||
MaxLen(f, nameof(r.Model), r.Model, 20);
|
||||
MaxLen(f, nameof(r.HeadType), r.HeadType, 20);
|
||||
MaxLen(f, nameof(r.Color), r.Color, 30);
|
||||
MaxLen(f, nameof(r.Model), r.Model, 30);
|
||||
MaxLen(f, nameof(r.HeadType), r.HeadType, 30);
|
||||
MaxLen(f, nameof(r.PhoneNumber), r.PhoneNumber, 10);
|
||||
Digits(f, nameof(r.PhoneNumber), r.PhoneNumber, 10);
|
||||
return f;
|
||||
|
|
|
|||
|
|
@ -12,8 +12,7 @@ public interface ITrailerRegistryService
|
|||
Task<RegistryResult> CreateAsync(SaveTrailerRequest request, CancellationToken ct);
|
||||
Task<RegistryResult> UpdateAsync(long id, SaveTrailerRequest request, CancellationToken ct);
|
||||
Task<RegistryResult> AcceptAsync(long id, CancellationToken ct);
|
||||
/// <param name="truckId">The truck whose page the revoke was made from (legacy tnID); only then does the truck go back to REGREQST.</param>
|
||||
Task<RegistryResult> RevokeAsync(long id, long? truckId, CancellationToken ct);
|
||||
Task<RegistryResult> RevokeAsync(long id, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of register.cfc saveTrailerDetails / editTrailerDetails / getTrailerInfo / getTrailerGrid / revokeTrailer / acceptTrailer.</summary>
|
||||
|
|
@ -132,9 +131,8 @@ public sealed class TrailerRegistryService(
|
|||
|
||||
var tempIds = await attachments.EnsureTempFilesAsync(request.AttachmentIds, ct);
|
||||
var stored = (await attachments.ListAsync(RegistryAttachmentService.KindTrailer, id, ct)).Count;
|
||||
// legacy editTrailer counted the child nodes of the file list, and a stored file already renders as several nodes, so in practice
|
||||
// one document (stored or new) is enough on edit
|
||||
if (!RegistryRules.HasEnoughAttachments(tempIds.Count, stored, required: 1))
|
||||
// legacy editTrailer: at least 2 attached files (it counted only the files added in that session; stored files count here)
|
||||
if (!RegistryRules.HasEnoughAttachments(tempIds.Count, stored))
|
||||
throw new BusinessException(RegistryErrors.AttachmentsIncomplete, RegistryMessages.AttachmentsIncomplete);
|
||||
|
||||
var is327 = current.Tcscac == settings.BadiyaScac;
|
||||
|
|
@ -171,7 +169,7 @@ public sealed class TrailerRegistryService(
|
|||
return new RegistryResult(RegistryMessages.Accepted, id);
|
||||
}
|
||||
|
||||
public async Task<RegistryResult> RevokeAsync(long id, long? truckId, CancellationToken ct)
|
||||
public async Task<RegistryResult> RevokeAsync(long id, CancellationToken ct)
|
||||
{
|
||||
await access.RequireActionAsync(RegistryActions.RevokeTrailer, false, ct);
|
||||
if (access.IsBadiyaCompany)
|
||||
|
|
@ -185,10 +183,8 @@ public sealed class TrailerRegistryService(
|
|||
await unitOfWork.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await repository.RevokeTrailerAsync(id, user.UserId, token);
|
||||
// Legacy revokeTrailer posts tnID only when the trailer page was opened from the truck page (the trailer grid opens it without),
|
||||
// and only then does the truck go back to "awaiting registration" (was INCOMP until 30 Dec 2020).
|
||||
// Kept stricter than legacy: it must be this trailer's own truck, and a revoked truck is not brought back.
|
||||
if (truckId is not null && trailer.TnId == truckId)
|
||||
// the truck goes back to "awaiting registration" (was INCOMP until 30 Dec 2020)
|
||||
if (trailer.TnId is not null)
|
||||
{
|
||||
var truck = await repository.GetTruckAsync(trailer.TnId.Value, token);
|
||||
if (truck is not null && RegistryRules.CanRevoke(truck.StatusCode))
|
||||
|
|
|
|||
|
|
@ -157,11 +157,7 @@ public sealed class ReportsService(IReportsRepository repo, IReportExcelService
|
|||
[
|
||||
C("turn", "الدور", "Turn", "number"), C("scac", "رقم الشركة", "Company code"), C("company", "اسم الشركة", "Company"),
|
||||
C("code", "نوع المادة", "Cargo"), C("type", "نوع التوزيع", "Distribution"), C("counter", "العداد", "Counter", "number")
|
||||
], rowFix: r =>
|
||||
{
|
||||
r["code"] = r["code"] switch { "BULK" => "سائب", "PCKD" => "مشول", "GALLAB" => "سائب - قلاب", var v => v };
|
||||
r["type"] = r["type"] switch { "COMP" => "شركات", "AHALI" => "أفراد", var v => v };
|
||||
});
|
||||
]);
|
||||
case ReportKeys.OwnersTurn:
|
||||
return Make(key, "تقرير دور الأفراد", "Individuals turn", [$"نوع المادة: {f.ShipmentMode} الوجهة: {f.DestAddressId}"], raw,
|
||||
[
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
using NTP.Application.Grains.Permits;
|
||||
|
||||
namespace NTP.Application.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// The jobs the scheduler can run (ports of the legacy jobs\*.cfm files). To add one: add an entry here and make sure its code is safe to
|
||||
/// run repeatedly. Everything about WHEN it runs lives in the database (screen "المهام المجدولة", SU only).
|
||||
/// </summary>
|
||||
public static class JobCatalog
|
||||
{
|
||||
private static T Get<T>(IServiceProvider sp) where T : class => (T)(sp.GetService(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} is not registered"));
|
||||
|
||||
public static readonly IReadOnlyList<JobDefinition> All =
|
||||
[
|
||||
new("activate-company-destinations",
|
||||
"تفعيل وجهات الشركات المعلقة", "Activate pending company destinations",
|
||||
"jobs/activateGrainsDestination.cfm: الوجهات التي مضى على تقديمها أكثر من 3 أيام (معلقة) تصبح فعالة، وتلغى الوجهات الفعالة السابقة لنفس القاطرة.",
|
||||
"jobs/activateGrainsDestination.cfm: destinations pending for more than 3 days become active and the truck's previous active destinations are deactivated.",
|
||||
async (sp, ct) =>
|
||||
{
|
||||
var n = await Get<IDestinationService>(sp).ActivatePendingCompanyDestinationsAsync(ct);
|
||||
return new JobOutcome(n, $"تم تفعيل {n} وجهة");
|
||||
}),
|
||||
|
||||
new("close-old-permits",
|
||||
"إغلاق الارساليات القديمة", "Close old permits",
|
||||
"jobs/GRAINS_Close_Old_Permits.cfm: إغلاق الارساليات التي مضى على تحميلها 48 ساعة، أو التي أكملت التفريغ ولم تغلق، أو المكررة لنفس القاطرة، بحدث \"System Close.\".",
|
||||
"jobs/GRAINS_Close_Old_Permits.cfm: closes permits loaded more than 48 hours ago, finished but not closed, or duplicated for the same truck, with the event \"System Close.\".",
|
||||
async (sp, ct) =>
|
||||
{
|
||||
var n = await Get<IPermitJobsService>(sp).CloseOldPermitsAsync(ct);
|
||||
return new JobOutcome(n, $"تم إغلاق {n} إرسالية");
|
||||
}),
|
||||
|
||||
new("fill-company-shares",
|
||||
"استكمال ارساليات الشركات حسب الحصة", "Top up company permits to their share",
|
||||
"jobs/parseGrainsPermits.cfm: لكل شركة، إنشاء إرساليات مفتوحة (على الدور) لتساوي حصتها من الدور في المشول والسائب.",
|
||||
"jobs/parseGrainsPermits.cfm: for every company, creates open permits (on the turn) up to its queue share, for packed and bulk.",
|
||||
async (sp, ct) =>
|
||||
{
|
||||
var n = await Get<IQueueService>(sp).FillCompanySharesAsync(ct);
|
||||
return new JobOutcome(n, $"تم إنشاء {n} إرسالية");
|
||||
}),
|
||||
];
|
||||
|
||||
public static JobDefinition? Find(string key) => All.FirstOrDefault(j => string.Equals(j.Key, key, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
|
@ -1,119 +0,0 @@
|
|||
using System.Globalization;
|
||||
|
||||
namespace NTP.Application.Jobs;
|
||||
|
||||
/// <summary>Pure scheduling rules (no clock, no database), so they can be tested exactly.</summary>
|
||||
public static class JobScheduleRules
|
||||
{
|
||||
public const int MinIntervalMinutes = 1;
|
||||
public const int MaxIntervalMinutes = 7 * 24 * 60;
|
||||
public const int DefaultIntervalMinutes = 60;
|
||||
|
||||
/// <summary>A daily time that was missed (application stopped, restart) still runs once if it is at most this late.</summary>
|
||||
public static readonly TimeSpan CatchUp = TimeSpan.FromMinutes(30);
|
||||
|
||||
public static bool TryParseTime(string? text, out TimeOnly time) =>
|
||||
TimeOnly.TryParseExact(text?.Trim(), "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out time);
|
||||
|
||||
/// <summary>"02:00,13:30" -> times (invalid parts are ignored).</summary>
|
||||
public static IReadOnlyList<TimeOnly> ParseTimes(string? csv)
|
||||
{
|
||||
var list = new List<TimeOnly>();
|
||||
foreach (var part in (csv ?? string.Empty).Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
|
||||
if (TryParseTime(part, out var t)) list.Add(t);
|
||||
return list.Distinct().OrderBy(t => t).ToList();
|
||||
}
|
||||
|
||||
public static IReadOnlyList<string> SplitTimes(string? csv) => ParseTimes(csv).Select(t => t.ToString("HH:mm", CultureInfo.InvariantCulture)).ToList();
|
||||
|
||||
public static string JoinTimes(IEnumerable<string>? times) =>
|
||||
string.Join(',', (times ?? []).Select(x => TryParseTime(x, out var t) ? t : (TimeOnly?)null).Where(t => t.HasValue)
|
||||
.Select(t => t!.Value).Distinct().OrderBy(t => t).Select(t => t.ToString("HH:mm", CultureInfo.InvariantCulture)));
|
||||
|
||||
/// <summary>Returns an Arabic error text, or null when the schedule is valid.</summary>
|
||||
public static string? Validate(string? scheduleType, int? intervalMinutes, IReadOnlyList<string>? dailyTimes)
|
||||
{
|
||||
switch (scheduleType)
|
||||
{
|
||||
case JobScheduleTypes.Interval:
|
||||
if (intervalMinutes is null || intervalMinutes < MinIntervalMinutes || intervalMinutes > MaxIntervalMinutes)
|
||||
return "الفترة يجب أن تكون بين دقيقة واحدة و 7 أيام";
|
||||
return null;
|
||||
case JobScheduleTypes.Daily:
|
||||
if (dailyTimes is null || dailyTimes.Count == 0) return "يرجى تحديد وقت واحد على الأقل";
|
||||
if (dailyTimes.Any(x => !TryParseTime(x, out _))) return "صيغة الوقت غير صحيحة، استخدم HH:mm";
|
||||
return null;
|
||||
default:
|
||||
return "نوع الجدولة غير صحيح";
|
||||
}
|
||||
}
|
||||
|
||||
private static DateTime? Latest(DateTime? a, DateTime? b) => a is null ? b : b is null ? a : a > b ? a : b;
|
||||
|
||||
/// <summary>The most recent configured daily time that is not in the future (today or yesterday), if any.</summary>
|
||||
private static DateTime? LatestOccurrence(IReadOnlyList<TimeOnly> times, DateTime now)
|
||||
{
|
||||
DateTime? latest = null;
|
||||
foreach (var day in new[] { -1, 0 })
|
||||
foreach (var t in times)
|
||||
{
|
||||
var occurrence = now.Date.AddDays(day) + t.ToTimeSpan();
|
||||
if (occurrence <= now && (latest is null || occurrence > latest)) latest = occurrence;
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
/// <summary>Is the job due at <paramref name="now"/>? A job that is stopped or still running never is.</summary>
|
||||
public static bool IsDue(JobSettingsRow s, DateTime now)
|
||||
{
|
||||
if (!s.IsEnabled || s.IsRunning) return false;
|
||||
|
||||
// a run (or saving / starting the job) closes the window of everything that was due before it
|
||||
var floor = Latest(s.LastStart, s.UpdatedDate);
|
||||
|
||||
if (s.ScheduleType == JobScheduleTypes.Interval)
|
||||
{
|
||||
if (s.IntervalMinutes is not > 0) return false;
|
||||
var anchor = floor ?? now;
|
||||
return now >= anchor.AddMinutes(s.IntervalMinutes.Value);
|
||||
}
|
||||
|
||||
if (s.ScheduleType == JobScheduleTypes.Daily)
|
||||
{
|
||||
var times = ParseTimes(s.DailyTimes);
|
||||
var latest = LatestOccurrence(times, now);
|
||||
if (latest is null || now - latest > CatchUp) return false;
|
||||
return floor is null || latest > floor;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>When the job runs next (null when it is stopped or has no valid schedule). A job that is due now returns <paramref name="now"/>.</summary>
|
||||
public static DateTime? NextRun(JobSettingsRow s, DateTime now)
|
||||
{
|
||||
if (!s.IsEnabled) return null;
|
||||
if (IsDue(s, now)) return now;
|
||||
|
||||
if (s.ScheduleType == JobScheduleTypes.Interval)
|
||||
{
|
||||
if (s.IntervalMinutes is not > 0) return null;
|
||||
var anchor = Latest(s.LastStart, s.UpdatedDate) ?? now;
|
||||
var next = anchor.AddMinutes(s.IntervalMinutes.Value);
|
||||
return next < now ? now : next;
|
||||
}
|
||||
|
||||
if (s.ScheduleType == JobScheduleTypes.Daily)
|
||||
{
|
||||
var times = ParseTimes(s.DailyTimes);
|
||||
DateTime? next = null;
|
||||
foreach (var day in new[] { 0, 1 })
|
||||
foreach (var t in times)
|
||||
{
|
||||
var occurrence = now.Date.AddDays(day) + t.ToTimeSpan();
|
||||
if (occurrence > now && (next is null || occurrence < next)) next = occurrence;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,107 +0,0 @@
|
|||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Jobs;
|
||||
|
||||
public interface IJobService
|
||||
{
|
||||
Task<IReadOnlyList<JobDto>> ListAsync(CancellationToken ct = default);
|
||||
Task<JobDto> SaveScheduleAsync(string key, SaveJobScheduleRequest request, CancellationToken ct = default);
|
||||
Task<JobDto> StartAsync(string key, CancellationToken ct = default);
|
||||
Task<JobDto> StopAsync(string key, CancellationToken ct = default);
|
||||
Task<JobActionResult> RunNowAsync(string key, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<JobRunDto>> RunsAsync(string key, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Keys of the jobs that are due now (used by the scheduler loop).</summary>
|
||||
Task<IReadOnlyList<string>> GetDueKeysAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public sealed class JobService(IJobRepository repo, IJobRunner runner, ICurrentUser user) : IJobService
|
||||
{
|
||||
private static JobDefinition Def(string key) =>
|
||||
JobCatalog.Find(key) ?? throw new NotFoundException("Job", key);
|
||||
|
||||
/// <summary>The settings of a job that was never saved: stopped, every hour.</summary>
|
||||
private static JobSettingsRow Defaults(string key) => new()
|
||||
{
|
||||
JobKey = key, Enabled = 0, ScheduleType = JobScheduleTypes.Interval, IntervalMinutes = JobScheduleRules.DefaultIntervalMinutes
|
||||
};
|
||||
|
||||
private static JobDto ToDto(JobDefinition d, JobSettingsRow s, DateTime now) => new(
|
||||
d.Key, d.TitleAr, d.TitleEn, d.DescriptionAr, d.DescriptionEn,
|
||||
s.IsEnabled, s.ScheduleType ?? JobScheduleTypes.Interval, s.IntervalMinutes ?? JobScheduleRules.DefaultIntervalMinutes,
|
||||
JobScheduleRules.SplitTimes(s.DailyTimes), s.IsRunning, s.LastStart, s.LastEnd, s.LastStatus, s.LastMessage, s.LastCount,
|
||||
JobScheduleRules.NextRun(s, now));
|
||||
|
||||
private async Task<(DateTime Now, Dictionary<string, JobSettingsRow> Rows)> LoadAsync(CancellationToken ct)
|
||||
{
|
||||
var now = await repo.GetServerNowAsync(ct);
|
||||
var rows = (await repo.GetAllAsync(ct)).ToDictionary(r => r.JobKey, StringComparer.OrdinalIgnoreCase);
|
||||
return (now, rows);
|
||||
}
|
||||
|
||||
private async Task<JobDto> OneAsync(string key, CancellationToken ct)
|
||||
{
|
||||
var def = Def(key);
|
||||
var (now, rows) = await LoadAsync(ct);
|
||||
return ToDto(def, rows.GetValueOrDefault(def.Key) ?? Defaults(def.Key), now);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<JobDto>> ListAsync(CancellationToken ct = default)
|
||||
{
|
||||
var (now, rows) = await LoadAsync(ct);
|
||||
return JobCatalog.All.Select(d => ToDto(d, rows.GetValueOrDefault(d.Key) ?? Defaults(d.Key), now)).ToList();
|
||||
}
|
||||
|
||||
public async Task<JobDto> SaveScheduleAsync(string key, SaveJobScheduleRequest r, CancellationToken ct = default)
|
||||
{
|
||||
var def = Def(key);
|
||||
var error = JobScheduleRules.Validate(r.ScheduleType, r.IntervalMinutes, r.DailyTimes);
|
||||
if (error is not null) throw new BusinessException("JOB_INVALID_SCHEDULE", error);
|
||||
|
||||
var daily = r.ScheduleType == JobScheduleTypes.Daily;
|
||||
await repo.SaveScheduleAsync(def.Key, r.ScheduleType, daily ? null : r.IntervalMinutes,
|
||||
daily ? JobScheduleRules.JoinTimes(r.DailyTimes) : null, user.UserId, ct);
|
||||
return await OneAsync(def.Key, ct);
|
||||
}
|
||||
|
||||
public async Task<JobDto> StartAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
var def = Def(key);
|
||||
var (_, rows) = await LoadAsync(ct);
|
||||
var s = rows.GetValueOrDefault(def.Key) ?? Defaults(def.Key);
|
||||
var error = JobScheduleRules.Validate(s.ScheduleType, s.IntervalMinutes, JobScheduleRules.SplitTimes(s.DailyTimes));
|
||||
if (error is not null) throw new BusinessException("JOB_INVALID_SCHEDULE", error);
|
||||
|
||||
await repo.SetEnabledAsync(def.Key, true, user.UserId, ct);
|
||||
return await OneAsync(def.Key, ct);
|
||||
}
|
||||
|
||||
public async Task<JobDto> StopAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
var def = Def(key);
|
||||
await repo.SetEnabledAsync(def.Key, false, user.UserId, ct);
|
||||
return await OneAsync(def.Key, ct);
|
||||
}
|
||||
|
||||
public async Task<JobActionResult> RunNowAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
var def = Def(key);
|
||||
return await runner.StartAsync(def.Key, user.UserId, ct) == JobStartResult.Started
|
||||
? new JobActionResult(true, "بدأ تشغيل المهمة")
|
||||
: new JobActionResult(false, "المهمة قيد التنفيذ حاليا");
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<JobRunDto>> RunsAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
var def = Def(key);
|
||||
return (await repo.GetRunsAsync(def.Key, 30, ct))
|
||||
.Select(r => new JobRunDto(r.Id, r.StartDate, r.EndDate, r.Status, r.RowsAffected, r.Message, r.TriggeredBy)).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<string>> GetDueKeysAsync(CancellationToken ct = default)
|
||||
{
|
||||
var (now, rows) = await LoadAsync(ct);
|
||||
return JobCatalog.All.Where(d => rows.TryGetValue(d.Key, out var s) && JobScheduleRules.IsDue(s, now)).Select(d => d.Key).ToList();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,103 +0,0 @@
|
|||
namespace NTP.Application.Jobs;
|
||||
|
||||
/// <summary>How a job is scheduled.</summary>
|
||||
public static class JobScheduleTypes
|
||||
{
|
||||
/// <summary>Every N minutes (the screen offers minutes or hours), counted from the last start.</summary>
|
||||
public const string Interval = "INTERVAL";
|
||||
|
||||
/// <summary>At one or more fixed times of the day (HH:mm, server time).</summary>
|
||||
public const string Daily = "DAILY";
|
||||
}
|
||||
|
||||
public static class JobStatuses
|
||||
{
|
||||
public const string Running = "RUNNING";
|
||||
public const string Ok = "OK";
|
||||
public const string Failed = "FAILED";
|
||||
}
|
||||
|
||||
/// <summary>What a job reports when it finishes.</summary>
|
||||
public sealed record JobOutcome(int Count, string? Message = null);
|
||||
|
||||
/// <summary>One job of the catalog: its key, texts and the code that runs it (called in its own DI scope).</summary>
|
||||
public sealed record JobDefinition(
|
||||
string Key, string TitleAr, string TitleEn, string DescriptionAr, string DescriptionEn,
|
||||
Func<IServiceProvider, CancellationToken, Task<JobOutcome>> Run);
|
||||
|
||||
/// <summary>GRAINS_JOBS row (a class: Dapper maps Oracle NUMBER onto properties, not onto positional constructors).</summary>
|
||||
public sealed class JobSettingsRow
|
||||
{
|
||||
public string JobKey { get; set; } = string.Empty;
|
||||
public int? Enabled { get; set; }
|
||||
public string? ScheduleType { get; set; }
|
||||
public int? IntervalMinutes { get; set; }
|
||||
public string? DailyTimes { get; set; }
|
||||
public DateTime? LastStart { get; set; }
|
||||
public DateTime? LastEnd { get; set; }
|
||||
public string? LastStatus { get; set; }
|
||||
public string? LastMessage { get; set; }
|
||||
public int? LastCount { get; set; }
|
||||
public DateTime? UpdatedDate { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
|
||||
public bool IsEnabled => Enabled == 1;
|
||||
public bool IsRunning => string.Equals(LastStatus, JobStatuses.Running, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>GRAINS_JOB_RUNS row.</summary>
|
||||
public sealed class JobRunRow
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string JobKey { get; set; } = string.Empty;
|
||||
public DateTime StartDate { get; set; }
|
||||
public DateTime? EndDate { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public int? RowsAffected { get; set; }
|
||||
public string? Message { get; set; }
|
||||
public string? TriggeredBy { get; set; }
|
||||
}
|
||||
|
||||
public sealed record JobDto(
|
||||
string Key, string TitleAr, string TitleEn, string DescriptionAr, string DescriptionEn,
|
||||
bool Enabled, string ScheduleType, int IntervalMinutes, IReadOnlyList<string> DailyTimes,
|
||||
bool Running, DateTime? LastStart, DateTime? LastEnd, string? LastStatus, string? LastMessage, int? LastCount, DateTime? NextRun);
|
||||
|
||||
public sealed record JobRunDto(long Id, DateTime StartDate, DateTime? EndDate, string? Status, int? RowsAffected, string? Message, string? TriggeredBy);
|
||||
|
||||
public sealed record SaveJobScheduleRequest(string ScheduleType, int? IntervalMinutes, IReadOnlyList<string>? DailyTimes);
|
||||
|
||||
public sealed record JobActionResult(bool Success, string Message);
|
||||
|
||||
public enum JobStartResult { Started, AlreadyRunning }
|
||||
|
||||
/// <summary>Storage of the job settings and of the run history (tables GRAINS_JOBS / GRAINS_JOB_RUNS, script db/grains-jobs.sql).</summary>
|
||||
public interface IJobRepository
|
||||
{
|
||||
/// <summary>Database clock: schedules are judged against it, never against the container clock.</summary>
|
||||
Task<DateTime> GetServerNowAsync(CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<JobSettingsRow>> GetAllAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Saves the schedule (creates the row when missing, jobs start stopped). Restarts the interval cycle.</summary>
|
||||
Task SaveScheduleAsync(string key, string scheduleType, int? intervalMinutes, string? dailyTimes, string userId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Start (true) / stop (false). Restarts the interval cycle, so a started job never fires for a time that is already past.</summary>
|
||||
Task SetEnabledAsync(string key, bool enabled, string userId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Marks the job RUNNING and opens a history row. Returns null when it is already running (a RUNNING mark older than one hour counts as a crash
|
||||
/// and is taken over). The mark lives in the database, so two API instances never run the same job at once.
|
||||
/// </summary>
|
||||
Task<long?> TryBeginRunAsync(string key, string triggeredBy, CancellationToken ct = default);
|
||||
|
||||
Task FinishRunAsync(long runId, string key, string status, int? rows, string? message, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<JobRunRow>> GetRunsAsync(string key, int top, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Starts a job in the background (own DI scope) and records its run. Implemented in Infrastructure.</summary>
|
||||
public interface IJobRunner
|
||||
{
|
||||
Task<JobStartResult> StartAsync(string key, string triggeredBy, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
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";
|
||||
}
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
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;
|
||||
}
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
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");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
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);
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,136 +0,0 @@
|
|||
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");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,291 +0,0 @@
|
|||
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>
|
||||
/// 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));
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,322 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,136 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,83 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,218 +0,0 @@
|
|||
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));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,253 +0,0 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,272 +0,0 @@
|
|||
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);
|
||||
|
|
@ -1,89 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,43 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -1,83 +0,0 @@
|
|||
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; }
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue