commit 0c0b64239cc3b312e0ca5e15d942e95ace3a428f Author: Samer Salameh Date: Wed Nov 11 11:56:48 2026 +0300 Initial commit: NTP V2 (.NET 10 API + React web) with Dev, QA and Production environments Rebuild of the legacy ColdFusion NTP Grains module: Orders, Permits, Registry and Reports on a Dapper/Oracle API with a metadata-driven React front end (Arabic RTL default, English LTR, light and dark). Environments - API: appsettings.{Development,QA,Production}.json carry only non-secret settings. Connection strings, Jwt__Key, CORS origin and super users come from the server environment. Production and QA CORS origins fail closed until set. launchSettings gets a QA profile. - Web: Vite modes qa and production (web/.env.qa, web/.env.production), configurable VITE_API_BASE, scripts build:qa and build:prod. - docs/ENVIRONMENTS.md documents the three environments, required settings and a new-environment checklist. Security and access - Backend-driven permissions (GET /auth/permissions, [RequirePermission]) from GRAINS_SCREEN_PERMISSIONS; SU always allowed. SQL in db/ (grains-screen-permissions.sql, registry-create-permissions.sql). - OracleCredentialGuard stops retrying an account after ORA-01017 so a misconfigured copy cannot lock the database account. Co-Authored-By: Claude Sonnet 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d91e0c1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +bin/ +obj/ +.vs/ +.idea/ +*.user +appsettings.Local.json +appsettings.*.local.json + +# dependencies and build output +node_modules/ +dist/ +*.tsbuildinfo +TestResults/ +*.log + +# local-only files: secrets, per-developer settings, local tool config +.env.local +.env.*.local +*.local +.claude/ + +# stray empty lockfile at the repository root (the real one is web/package-lock.json) +/package-lock.json diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..ec615b1 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,11 @@ + + + net10.0 + enable + enable + latest + false + true + $(NoWarn);CS1591 + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..f998825 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,32 @@ + + + true + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NTP.slnx b/NTP.slnx new file mode 100644 index 0000000..12aac0a --- /dev/null +++ b/NTP.slnx @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..43cf326 --- /dev/null +++ b/README.md @@ -0,0 +1,100 @@ +# NTP API + +.NET 10 Web API over an **existing Oracle 11g** database, built to host the rewritten backend logic. + +## Why this stack + +| Choice | Reason | +|---|---| +| `Oracle.ManagedDataAccess.Core` **3.21.x** (ODP.NET 21c) | Last ODP.NET line that supports DB **11.2.0.4**. The 23.x line needs 19c+. Pinned in `Directory.Packages.props` — only bump within 3.21.x. | +| **Dapper** (not EF Core) | Current EF Core Oracle providers generate 12c+ SQL (OFFSET/FETCH, identity). Dapper keeps SQL explicit and 11g-safe, and fits a database-first legacy schema. | +| Clean layers (Api → Application → Infrastructure → Domain) | Business logic is ported into `Application` services, independent of Oracle. When the DB is upgraded, only `Infrastructure` changes. | + +## Layout + +``` +src/ + NTP.Api/ Controllers (thin), ProblemDetails + ORA-code mapping, versioning, OpenAPI, health + NTP.Application/ Services (business logic), DTOs, FluentValidation, repository interfaces, paging + NTP.Domain/ Entities mapped to existing tables + NTP.Infrastructure/ ODP.NET + Dapper: DbSession (connection/transaction per request), repositories, health check +db/sample-schema.sql Scratch table for the Shipment example only +``` + +## Run it + +```bash +# Requires .NET 10 SDK and network access to the Oracle server +cd src/NTP.Api +cp appsettings.Local.example.json appsettings.Local.json # then edit it +dotnet run +``` + +- Swagger UI: `https://localhost:7180/swagger` (Development only) +- OpenAPI JSON: `/openapi/v1.json` +- Health: `/health/live`, `/health/ready` (runs `SELECT 1 FROM DUAL`) +- The app fails fast at startup if no connection is configured, and logs the target DB (password masked). + +> Environments (Development / QA / Production), the settings each server must provide and the web build modes are described in [docs/ENVIRONMENTS.md](docs/ENVIRONMENTS.md). + +## Configuring the database connection + +Configure them in `src/NTP.Api/appsettings*.json` (secrets only in git-ignored files or env vars). + +The API uses **two** Oracle connections (the two legacy ColdFusion datasources): + +| Key | Schema / legacy datasource | Used by | +|---|---|---| +| `ConnectionStrings:NAFITHTCS` (primary) | `NAFITHTCS` / `nafithtcs` | `IDbSession`, `OracleRepositoryBase`, `IUnitOfWork`: PERMITS, NTP_TRUCKS, EVENTS, GRAINS*, UTT, LOCATIONS, STATUS ... | +| `ConnectionStrings:NtpSchema` (required) | `NTP` / `NTP` | `INtpDbSession`, `NtpRepositoryBase`, `INtpUnitOfWork`: NTPUSERS, ROLES, LOGS, COMPANIES, NATIONALITY ... | + +Example (placeholders only; real passwords go in git-ignored `appsettings.Local.json` or env vars `ConnectionStrings__NAFITHTCS` / `ConnectionStrings__NtpSchema`): +`"NAFITHTCS": "User Id=NAFITHTCS;Password=;Data Source=:1521/"`, `"NtpSchema": "User Id=NTP;Password=;Data Source=:1521/"`. + +The primary connection is resolved in this order (first match wins): + +| # | Where | Example | +|---|---|---| +| 1 | `ConnectionStrings:NAFITHTCS` (then legacy `ConnectionStrings:NTP`) | `"NAFITHTCS": "User Id=NAFITHTCS;Password=;Data Source=db-host:1521/ORCL"` | +| 2 | `Oracle:ConnectionString` | same format, kept with the other Oracle settings | +| 3 | `Oracle:Host`, `Port`, `ServiceName` (or `Sid`), `UserId`, `Password` | built for you, plus pool settings (`MinPoolSize`, `MaxPoolSize`, `ConnectionTimeoutSeconds`, `StatementCacheSize`) | + +Files are layered, later overriding earlier: +`appsettings.json` → `appsettings.{Environment}.json` → user-secrets (Development) → environment variables → `appsettings.Local.json` (git-ignored). + +- **Local dev:** copy `appsettings.Local.example.json` to `appsettings.Local.json` and put your password there. +- **Server / IIS / Docker:** keep the non-secret parts in `appsettings.Production.json`; supply the password with an env var, e.g. `Oracle__Password=...` or the whole string with `ConnectionStrings__NAFITHTCS=...` plus `ConnectionStrings__NtpSchema=...`. +- **SID listeners:** set `Sid` instead of `ServiceName`, or use `Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=db-host)(PORT=1521))(CONNECT_DATA=(SID=ORCL)))`. +- Never commit real passwords to `appsettings.json`. + +## Migrating a table / module (recipe) + +1. **Entity** — `Domain/Entities/.cs`, one property per column (`ORDER_DATE` → `OrderDate`). +2. **Repository interface** — `Application/Abstractions/IRepository.cs`. +3. **Repository** — copy `ShipmentRepository.cs`; explicit column lists, `:Param` binds, `OracleSql.Paginate` for lists, `.NEXTVAL ... RETURNING ... INTO` for inserts. +4. **Service** — port the old business logic into `Application//Service.cs`; wrap multi-statement writes in `unitOfWork.ExecuteInTransactionAsync`. +5. **Validators + DTOs** — keep max lengths in sync with `VARCHAR2` sizes. +6. **Controller** — `Controllers/V1/Controller.cs`, no logic. +7. **Register** — one line each in `Application/DependencyInjection.cs` and `Infrastructure/DependencyInjection.cs`. + +Existing PL/SQL packages can be called from a repository with +`CommandType.StoredProcedure`; ref-cursor outputs need `OracleDynamicParameters` (ask for the helper when needed). + +## Oracle 11g rules baked in + +- **Paging**: `ROWNUM` wrapper, not `OFFSET/FETCH`. Always order by a unique tie-breaker (PK). +- **IDs**: sequences (or the legacy trigger), never identity columns. +- **Booleans**: `NUMBER(1)`; write with `OracleSql.ToNumber(bool)` — ODP.NET 21 cannot bind `bool`. +- **One result set per command**: list endpoints do COUNT + page as two queries. +- **Empty string = NULL** in Oracle; don't rely on `''` vs `NULL` distinctions from the old code. +- **VARCHAR2 lengths are bytes** by default (`NLS_LENGTH_SEMANTICS=BYTE`) — Arabic text uses 2 bytes/char in AL32UTF8. +- **Dates**: `SYSDATE` is DB-server local time; the API returns `DateTime` with `Kind=Unspecified`. +- **Optimistic concurrency** via `ROW_VERSION`; drop those clauses if a legacy table has no such column. +- **Errors**: ORA codes map to HTTP (ORA-00001 → 409, ORA-02292 → 409, ORA-12899 → 400, network ORA-12541/12514/03113 → 503, …) in `GlobalExceptionHandler`. + +## Next steps to align with NafithServices + +- JWT auth (same issuer/audience as the gateway), then add `[Authorize]`. +- OpenTelemetry tracing/metrics (add `OpenTelemetry.Instrumentation.AspNetCore`; ODP.NET 21 has no OTel instrumentation, so wrap repository calls in an `ActivitySource` if DB spans are required). +- Ocelot route for `/api/v1/...` and Dockerfile. +- Integration tests against a disposable Oracle XE container (note: XE 11g images are no longer distributed — use a shared test schema on the 11g server instead). diff --git a/db/grains-screen-permissions.sql b/db/grains-screen-permissions.sql new file mode 100644 index 0000000..7eee46b --- /dev/null +++ b/db/grains-screen-permissions.sql @@ -0,0 +1,95 @@ +-- Screen / module / action permissions per role code (NAFITHTCS schema). +-- NOT executed by the application (the QA connection is read-only for DDL): a DBA runs this once. +-- Until it exists the API uses the same data from NTP.Application/Access/PermissionDefaults.cs. +-- SU is never stored: it is always allowed everything. A resource that has no row for a role is hidden +-- from that role (allow-list). Source of the seed: authorities.xlsx. + +CREATE TABLE GRAINS_SCREEN_PERMISSIONS ( + ROLECODE VARCHAR2(20) NOT NULL, + RESOURCE_KEY VARCHAR2(100) NOT NULL, + CREATEDATE DATE DEFAULT SYSDATE, + CONSTRAINT PK_GRAINS_SCREEN_PERMISSIONS PRIMARY KEY (ROLECODE, RESOURCE_KEY) +); + +COMMENT ON TABLE GRAINS_SCREEN_PERMISSIONS IS 'Role code -> allowed front-end resource (menu key or action key)'; + +-- helper: one INSERT per (resource, role) +INSERT ALL + -- ارسالية عطاء التموين + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.list') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GGO', 'grains.permits.list') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.permits.list') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GPO', 'grains.permits.list') + -- شاشة القاطرات + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.registry.trucks') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.registry.trucks') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GPO', 'grains.registry.trucks') + -- شاشة المقطورات + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.registry.trailers') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.registry.trailers') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GPO', 'grains.registry.trailers') + -- شاشة السائقين المسجلين + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.registry.drivers') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.registry.drivers') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GPO', 'grains.registry.drivers') + -- الطلبيات + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.orders.list') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.orders.list') + -- طلبية جديدة (action of the orders screen) + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.orders.create') + -- شاشة القبان + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.weighbridge') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GGO', 'grains.permits.weighbridge') + -- اغلاق إرسالية + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.close') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GGO', 'grains.permits.close') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.permits.close') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GPO', 'grains.permits.close') + -- طلبية لسيارة + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.truckOrder') + -- شاشة الأيقاف والإنتظار (legacy blackListGrid.cfm) + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.registry.blacklist') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.registry.blacklist') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GPO', 'grains.registry.blacklist') + -- طلبية التموين (legacy distributedOrder.cfm) + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.distribution') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.permits.distribution') + -- استعلام عن حالة التوزيع لسيارة + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.truckStatus') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.permits.truckStatus') + -- شاشة تفعيل الطلبية + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.permits.activation') + -- شاشة الادخال اليدوي + 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.orders.weights') + -- تقارير حركات قبان التحميل والتفريغ + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.weighbridge-events') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.weighbridge-events') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.waybridge-summary') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.waybridge-summary') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.waybridge-details') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.waybridge-details') + -- تقرير دور الشركات + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.companies-turn') + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.reports.t.companies-turn') + -- تقرير دور الأفراد + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GTO', 'grains.reports.t.owners-turn') + -- تقرير أوزان التحميل + 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 ('GOO', 'grains.orders.companyDest') + -- تحديد وجهة ارسالية تموين + INTO GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) VALUES ('GOO', 'grains.permits.destinations') +SELECT 1 FROM DUAL; + +COMMIT; + +-- --------------------------------------------------------------------------------------------------------------------------- +-- Registering (adding) and EDITING a truck / trailer / driver is granted ONLY by rows in this table (SU always can). Nothing is granted by +-- default and there is no exception for any company. The rights are in db/registry-create-permissions.sql (safe to re-run): +-- add: GTO drivers | GOO trucks, trailers | GPO trucks, trailers, drivers; edit trucks and trailers: all roles diff --git a/db/registry-create-permissions.sql b/db/registry-create-permissions.sql new file mode 100644 index 0000000..a253b1e --- /dev/null +++ b/db/registry-create-permissions.sql @@ -0,0 +1,43 @@ +-- Registry action rights (NAFITHTCS schema): who may REGISTER (add) and who may EDIT trucks, trailers and drivers. +-- Run on a database where GRAINS_SCREEN_PERMISSIONS already exists. Safe to re-run: a row is only inserted when it is not there +-- yet. Not executed by the application. SU is never stored: it always has every right. +-- +-- add trucks : GOO, GPO +-- add trailers : GOO, GPO +-- add drivers : GTO, GPO +-- edit trucks : GTO, GGO, GOO, GPO (all roles) +-- edit trailers : GTO, GGO, GOO, GPO (all roles) +-- (drivers cannot be edited after registration in the legacy system) +-- +-- To take a right away later, 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 ( + -- add + SELECT 'GTO' AS rolecode, 'grains.registry.drivers.create' AS resource_key FROM dual UNION ALL + SELECT 'GOO', 'grains.registry.trucks.create' FROM dual UNION ALL + SELECT 'GOO', 'grains.registry.trailers.create' FROM dual UNION ALL + SELECT 'GPO', 'grains.registry.trucks.create' FROM dual UNION ALL + SELECT 'GPO', 'grains.registry.trailers.create' FROM dual UNION ALL + SELECT 'GPO', 'grains.registry.drivers.create' FROM dual UNION ALL + -- edit (all roles) + SELECT 'GTO', 'grains.registry.trucks.edit' FROM dual UNION ALL + SELECT 'GTO', 'grains.registry.trailers.edit' FROM dual UNION ALL + SELECT 'GGO', 'grains.registry.trucks.edit' FROM dual UNION ALL + SELECT 'GGO', 'grains.registry.trailers.edit' FROM dual UNION ALL + SELECT 'GOO', 'grains.registry.trucks.edit' FROM dual UNION ALL + SELECT 'GOO', 'grains.registry.trailers.edit' FROM dual UNION ALL + SELECT 'GPO', 'grains.registry.trucks.edit' FROM dual UNION ALL + SELECT 'GPO', 'grains.registry.trailers.edit' 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 14 rows): +-- SELECT rolecode, resource_key FROM GRAINS_SCREEN_PERMISSIONS +-- WHERE resource_key LIKE 'grains.registry.%.create' OR resource_key LIKE 'grains.registry.%.edit' ORDER BY 2, 1; diff --git a/db/sample-schema.sql b/db/sample-schema.sql new file mode 100644 index 0000000..947897c --- /dev/null +++ b/db/sample-schema.sql @@ -0,0 +1,29 @@ +-- ============================================================================ +-- SAMPLE ONLY - mirrors the Shipment example so you can run the API end-to-end +-- against a scratch 11g schema. For the real migration you map your EXISTING +-- tables instead; do not run this against production. +-- ============================================================================ + +CREATE TABLE SHIPMENTS ( + SHIPMENT_ID NUMBER(18) NOT NULL, + SHIPMENT_NO VARCHAR2(30) NOT NULL, + ORIGIN_CODE VARCHAR2(10), + DESTINATION_CODE VARCHAR2(10), + WEIGHT_KG NUMBER(12,3), + STATUS VARCHAR2(20) DEFAULT 'NEW' NOT NULL, + IS_ACTIVE NUMBER(1) DEFAULT 1 NOT NULL, + CREATED_AT DATE DEFAULT SYSDATE NOT NULL, + UPDATED_AT DATE, + ROW_VERSION NUMBER(10) DEFAULT 0 NOT NULL, + CONSTRAINT PK_SHIPMENTS PRIMARY KEY (SHIPMENT_ID), + CONSTRAINT UQ_SHIPMENTS_NO UNIQUE (SHIPMENT_NO), + CONSTRAINT CK_SHIPMENTS_ACTIVE CHECK (IS_ACTIVE IN (0, 1)) +); + +CREATE SEQUENCE SHIPMENTS_SEQ START WITH 1 INCREMENT BY 1 CACHE 20 NOCYCLE; + +CREATE INDEX IX_SHIPMENTS_STATUS_CREATED ON SHIPMENTS (STATUS, CREATED_AT); + +-- Optional: if the legacy table uses ROW_VERSION-less updates, either add the +-- column (ALTER TABLE ... ADD ROW_VERSION NUMBER(10) DEFAULT 0 NOT NULL) or +-- remove the ROW_VERSION checks from the repository. diff --git a/docs/ENVIRONMENTS.md b/docs/ENVIRONMENTS.md new file mode 100644 index 0000000..158e99d --- /dev/null +++ b/docs/ENVIRONMENTS.md @@ -0,0 +1,87 @@ +# Environments: Development, QA, Production + +One code base, three environments. Everything that differs is configuration; **secrets are never committed**. + +| | Development | QA | Production | +|---|---|---|---| +| `ASPNETCORE_ENVIRONMENT` | `Development` | `QA` | `Production` | +| API settings file | `appsettings.Development.json` | `appsettings.QA.json` | `appsettings.Production.json` | +| Swagger / OpenAPI | on | off | off | +| Log level | Information (`NTP.Infrastructure` Debug) | Information | Warning (`NTP` Information) | +| `Jwt__Key` | optional (random per start) | **required** | **required** | +| Oracle database | QA database (developer machine) | QA database | production database | +| Web build | `npm run dev` (Vite proxy to `https://localhost:7180`) | `npm run build:qa` | `npm run build:prod` | +| Web env file | `.env.local` (optional) | `web/.env.qa` | `web/.env.production` | +| Local launch profile | `https` (port 7180) | `https-qa` (port 7181) | not for local use | + +## How the API is configured + +Settings are layered; later wins: + +1. `appsettings.json` (shared defaults, no secrets) +2. `appsettings.{Environment}.json` (this table) +3. `appsettings.Local.json` (**git-ignored**, a developer's own values; copy `appsettings.Local.example.json`) +4. environment variables, e.g. `Jwt__Key`, `ConnectionStrings__NtpSchema` (`__` is the section separator) + +### What a QA or production server must provide + +Set these in the server's environment (IIS application settings, a Windows service environment, or a secret store), **not** in a file in the repository: + +| Setting | Meaning | +|---|---| +| `ConnectionStrings__NAFITHTCS` | Oracle connection string of the primary schema | +| `ConnectionStrings__NtpSchema` | Oracle connection string of the NTP schema | +| `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://`. 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` | + +Connection string shape (values are examples only): +`User Id=;Password=;Data Source=:1521/;Min Pool Size=1;Max Pool Size=50;Connection Timeout=15;Statement Cache Size=50` + +If Oracle ever rejects a password (ORA-01017) the API stops trying that account until it is restarted, so a wrong password +cannot lock the database account. Fix the setting, then restart the service. `/health/ready` reports the reason. + +Use `/health/live` for load balancer / uptime checks (it does not touch the database); `/health/ready` opens database connections. + +## Database objects + +Apply these scripts once per database (not run by the application), in this order: + +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) + +Roles and their rights live in that table (SU always has everything). Changing a row takes effect within about a minute on the +API and on the user's next page reload or sign-in. + +## How the web app is configured + +Vite reads `web/.env.{mode}`. The files hold only non-secret values, because everything in them ends up in the public JavaScript. + +| Variable | Default | Meaning | +|---|---|---| +| `VITE_API_BASE` | `/api/v1` | API address. Same origin by default: the web server proxies `/api` to the API. For a separate API host use `https:///api/v1` and add the web origin to `Cors__AllowedOrigins__0` | +| `VITE_MOCK` | `0` | `1` runs the in-browser mock API (development only) | + +```bash +cd web +npm ci +npm run build:qa # -> web/dist for QA (mode qa, web/.env.qa) +npm run build:prod # -> web/dist for production (mode production, web/.env.production) +``` + +## Running a QA build of the API locally + +```bash +cd src/NTP.Api +# secrets for the shell session only (PowerShell: $env:Jwt__Key = '...') +export Jwt__Key='' +dotnet run --launch-profile https-qa # https://localhost:7181 +``` + +## Checklist when a new environment is created + +- [ ] database objects applied (see above) and the permission rows reviewed +- [ ] `ConnectionStrings__*`, `Jwt__Key`, `Cors__AllowedOrigins__0` set; super users set if needed +- [ ] `/health/ready` is Healthy +- [ ] web built with the matching mode and published behind the same origin as `/api` (or `VITE_API_BASE` set) +- [ ] sign in as SU and as one limited role and compare the menu with the permission table diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md new file mode 100644 index 0000000..32502d4 --- /dev/null +++ b/docs/MIGRATION.md @@ -0,0 +1,112 @@ +# NTP migration conventions (Grains first) + +Legacy: ColdFusion 9, `C:\inetpub\wwwroot\NTP_LIVE` (read-only reference — NEVER edit it). +Target: `C:\inetpub\wwwroot\NTP_V2` — .NET 10 API (`src/`) + React front end (`web/`). +Legacy Grains code: `NTP_LIVE\services\Grains\` (pages `*.cfm`, logic `cfc\*.cfc`, `Reports\`, `ReadFiles\`), +plus Grains-related code elsewhere (grep `grain` in `NTP_LIVE\jobs`, `NTP_LIVE\services\MOT`, `NTP_LIVE\components`, root `*Grains*.cfm`). + +## Toolchain (Windows, Git Bash or PowerShell) +.NET 10 SDK is installed in a user folder, not on the default PATH: +``` +export PATH="/c/Users/samers/.dotnet-sdk10:$PATH"; export DOTNET_ROOT='C:\Users\samers\.dotnet-sdk10' +dotnet build C:/inetpub/wwwroot/NTP_V2/NTP.slnx +``` +Node 26 / npm available. Web app: `C:\inetpub\wwwroot\NTP_V2\web` (Vite + React + TS + MUI). Type-check with `npx tsc --noEmit`. +A real QA Oracle DB is reachable (see "Database connection notes" at the end). Verify SQL read-only against it and by compiling/type-checking; never run INSERT/UPDATE/DELETE against it. Say what was and was not verified in reports. + +## Backend (follow README.md recipe; Oracle 11g, Dapper, no EF) +- Layers: Domain/Entities -> Application (services, DTOs, FluentValidation, repository interfaces) -> Infrastructure (Dapper repos) -> Api (thin controllers). +- Per module folders (so parallel work never collides): + - `NTP.Domain/Grains//` + - `NTP.Application/Grains//` (interfaces `IRepository`, `IService`, DTOs, validators) + - `NTP.Infrastructure/Persistence/Repositories/Grains//` + - `NTP.Api/Controllers/V1/Grains/Controller.cs`, route `api/v{version}/grains/` +- DI is convention based (foundation provides it): concrete classes named `*Service` / `*Repository` are registered against their `I*` interface by assembly scanning; validators by FluentValidation scanning. Do NOT edit shared DI files per slice. +- Tables are the legacy Oracle tables (e.g. PERMITS, NTP_TRUCKS, NTP_TRAILERS, NTP_DRIVERS, EVENTS, GRAINSTENDERORDER, GRAINS_COMPANIES_QUEUE, GRAINS_COMPANIES_LOCATION, NTP_COMPANY_DISTINATION, TRUCK_DISTRIBUTION_LOG, GRAINSBLACKLIST, ...). Column names come from the legacy SQL — read the CFC queries; never invent columns. Where legacy does `select *`, list the columns the legacy code actually reads/writes. Unqualified table names. The legacy datasources `nafithtcs` and `NTP` are TWO different schemas - see "Database connection notes" (default `IDbSession` = NAFITHTCS; real columns in `docs/schema/*.md`). +- Port business rules faithfully (statuses, validations, event logging via `EVENTS`, sequence names like `SEQ_EVENTS.nextval`). Replace string-concatenated SQL with bind variables. Keep legacy user-facing Arabic messages as the default message text and also return a stable `code`. +- Current user: `ICurrentUser` (UserId, Name, RoleCode, Domain, LocationId, StkId, CompId, CompanyCode, CompanyId, Lang, IsStaff). It replaces legacy `session.*`. Auth is JWT bearer; every Grains endpoint is `[Authorize]`; role gating mirrors legacy role checks (`session.userrolecode`). +- Errors: throw `ValidationException`/`NotFoundException`/business exceptions from `NTP.Application.Common`; GlobalExceptionHandler turns them into ProblemDetails. +- Lists: server-side paging via `PageRequest` / `PagedResult` and `OracleSql.Paginate`; filters as query-string params. + +## Front end (`web/`) +Use the user's skills: `bilingual-rtl-ui`, `metadata-driven-forms-grids`, `ux-conventions-admin-ui`, `replace-legacy-frontend` (in `~/.claude/skills/*/SKILL.md` — read the relevant ones). +- Vite + React + TypeScript + MUI + React Query + react-router. Arabic RTL default, English LTR, light default + dark. Two Emotion caches (stylis-plugin-rtl). Logical CSS props only. +- Built-in typed UI string table (`web/src/i18n/ui.ts`, `{ en, ar }` per key) — every string, label and message is bilingual; no raw keys on screen. +- API client `web/src/api/client.ts` (fetch + bearer token + ProblemDetails -> typed `ApiError`); per-feature hooks in `web/src/features//api.ts`. +- Metadata-driven: grids and forms are generic components (`web/src/components/DataGrid`, `web/src/components/MetaForm`) driven by small declarative TS tables in `web/src/features/grains/meta/.ts` (fields, types, required, sections, conditional rules, grid columns, filters). Entity code = overrides only. +- Routes under `/grains/...`; menu entries registered in `web/src/features/grains/routes.tsx` (each feature exports `RouteObject[]` + `MenuItem[]`; the shell collects them — do not edit shell files per slice). +- UX conventions: equal field widths, sections, confirm dialog before writes + toast with backend message, loading banner text, empty states, status chips + filter drawer, Enter runs search, filters in URL params, one request per action. +- Dev proxy: Vite proxies `/api` to `https://localhost:7180`. + +## Reporting +Every agent ends with: what was built (files), how verified (build/tsc output), what is NOT verified, legacy behaviours skipped or uncertain, and assumptions the user must confirm. + +## Backend foundation notes +Shared plumbing is finished; slice agents should NOT edit any file listed under "Shared (do not edit)". + +### How to add a Grains slice (only new files) +1. `NTP.Application/Grains//`: `IRepository`, `IService` + `Service` (class name MUST end in `Service`, interface MUST be `I`), DTOs, `AbstractValidator` classes. Namespace `NTP.Application.Grains.`. +2. `NTP.Infrastructure/Persistence/Repositories/Grains//Repository.cs`: `internal sealed class Repository(IDbSession session, ILogger<Repository> logger) : OracleRepositoryBase(session, logger), IRepository`. Base helpers: `QueryAsync`, `QueryFirstAsync` (new), `QuerySingleOrDefaultAsync`, `ExecuteScalarAsync`, `ExecuteAsync`. +3. `NTP.Api/Controllers/V1/Grains/Controller.cs`: `[ApiController] [ApiVersion(1.0)] [Route("api/v{version:apiVersion}/grains/")]`, thin. Authenticated by default (see below); add `[Authorize(Roles = "GOP,...")]` for legacy role gating (role claim = legacy `session.userrolecode`, compare case-insensitively via `ICurrentUser.IsInAnyRole`). +4. Registration is automatic: classes ending `Service`/`Repository` (internal ok) are registered scoped against `I` in both Application and Infrastructure (`ConventionRegistration.AddConventionalServices`); validators by FluentValidation assembly scan; controllers by MVC discovery. A class named otherwise (e.g. a `*Job`, `*Logger`) needs manual registration - avoid, or name it `*Service`. +5. Inject `ICurrentUser` (never read HttpContext) and `IEventLogger`; use `IUnitOfWork.ExecuteInTransactionAsync` for multi-statement writes. + +### Shared (do not edit) +- `NTP.Application/DependencyInjection.cs`, `NTP.Infrastructure/DependencyInjection.cs`, `NTP.Api/Program.cs`, `NTP.Api/Auth/*`, `NTP.Api/ErrorHandling/GlobalExceptionHandler.cs`, `Directory.Packages.props` (ask if a new package is needed), `appsettings*.json`, `NTP.Application/Common/*`, `NTP.Application/Auth/*`, `NTP.Application/Lookups/*`, `NTP.Application/Abstractions/*`. + +### Auth +- Every endpoint requires a JWT by default (fallback authorization policy). Only `[AllowAnonymous]` (login, health, openapi) is public. +- `POST api/v1/auth/login` `{ "userName": "ASEZA.50034", "password": "..." }` (legacy `DOMAIN.login`) -> `{ accessToken, tokenType:"Bearer", expiresAtUtc, user, mustChangePassword }`. `GET auth/me`, `POST auth/change-password {oldPassword,newPassword,confirmNewPassword?}`, `POST auth/language {lang:"AR"|"EN"}` (returns a NEW token with the lang claim), `POST auth/logout` (writes LOGS type 2; client drops token). +- Send `Authorization: Bearer `. Config `Jwt` (Key, Issuer, Audience, ExpiryMinutes, ActiveCheckCacheSeconds), `Auth:SuperUsers`, `Cors:AllowedOrigins`. `Jwt:Key` (>= 32 chars) comes from env `Jwt__Key` / user-secrets / `appsettings.Local.json` (see the example file); outside Development the app refuses to start without it; in Development a random per-process key is used if unset. +- Per request, the token's user is re-checked in NTPUSERS (status=1 and same ROLECODE, Application.cfc `qry_validateUser`), cached `Jwt:ActiveCheckCacheSeconds` (default 10 s). Role `SU` only for `Auth:SuperUsers`. +- `ICurrentUser`: `Id` (NTPUSERS.ID), `UserId` (upper-case login = legacy session.userid), `Name`, `RoleCode`, `RoleName`, `Domain`, `LocationId`/`StkId`/`CompId`/`CompanyId` (`long?`), `LocationName`, `CompanyName`, `CompanyCode`, `EmpNo`, `Lang`, `IsStaff` (CompanyId = 15), `IsAuthenticated`, `IsInRole`, `IsInAnyRole`. + +### Errors +Throw from `NTP.Application.Common`: `ValidationException` (FluentValidation, 400 with per-field errors), `NotFoundException` (404), `ConcurrencyException` (409), `BusinessException(code, arabicMessage)` (422, ProblemDetails `detail`/`title` = message, extension `code` = stable code), `AuthenticationFailedException` (401), `ForbiddenException` (403). Keep legacy Arabic text as the message. + +### Event log and lookups +- `IEventLogger.AddAsync(new EventEntry("PERMITID", id, prev, curr, userId, "OVRD", domain, locationId, "NTP", weight, extras))` = legacy `addEvent` (`SEQ_EVENTS.nextval`, binds, DONEBY upper-cased). `AddForCurrentUserAsync(refColumn, refId, prev, curr, eventType, remarks)` fills user/domain/location from `ICurrentUser`. Ref/extra column names are validated as plain identifiers (no whitelist of EVENTS columns - they must exist; legacy uses PERMITID, CRID, ORDERID, WAYBILLID and extra REMARKS). +- Generic lookups (`api/v1/lookups/...`, domain defaults to the caller's): `statuses?domain=&isActive=`, `locations?domain=&type=&includeInactive=`, `cargo-types?domain=`, `companies`, `nationalities`, `cities`. Tables/columns taken from legacy SQL (STATUS, LOCATIONS, CARGOTYPE, COMPANIES, NATIONALITY, CITIES). Grains-specific lookups belong in the slice. +- Tests: `tests/NTP.Tests` (xunit): `dotnet test C:/inetpub/wwwroot/NTP_V2/NTP.slnx`. + +### Auth gaps vs legacy (not ported) +Captcha counters (RECAPTCHA_*), SSO and kiosk/`kiosksLogin`, multi-user single-login (`LoggedInUsers` auto-logout), `session.encryptionKey`, Petroleum dashboard session vars, printer ids (UTT/systemprinters), DISP `USER_ACTIVITIES`, ASEZA `getManagedCompany`/`application.TenderCompanies`, `URL_SECURITY` role rules (they match legacy page URLs; use `[Authorize(Roles=...)]` per endpoint instead), the hardcoded OPOFF/ONO IP-lockout and user/IP exemptions in Application.cfc/checkLogin, `resetPass` (legacy body is `cfabort`ed), `session.companyCodeNO`. ASEZA `application.encryptPwd.doEncryption` (Java `pwd.EncryptPwd`, not in repo) cannot be ported exactly: login accepts a guessed Base64(SHA-1(password)) variant (UNVERIFIED) plus the exact SHA-1(UPPER(login)+password) hex; change-password always writes the SHA-1 form. There is no lockout in legacy (only captcha); failed attempts are not logged anywhere in legacy, so none are here. + +## Front-end foundation notes +Foundation lives in `web/` (Vite 8, React 19, TS strict, MUI 9, React Query 5, react-router 7). Run: `npm run dev` (proxy `/api` -> https://localhost:7180), `npm run typecheck`, `npm run build`. `VITE_MOCK=1 npm run dev` uses the in-browser mock API and shows the `_example` feature (copy it as a template; it is hidden otherwise). Path alias `@/` = `web/src/`. MUI 9 note: system props on `Typography`/`Stack`/`Box` (e.g. `fontWeight`, `alignItems`) are gone; put them in `sx`. + +### How a slice agent adds a feature (never edit shell/foundation files or `i18n/ui.ts`) +Create only files under `web/src/features//` (e.g. `grains`, then sub-slices as sub-folders or extra files): +1. `routes.tsx` - REQUIRED, auto-collected by `src/registry.ts` (`import.meta.glob('./features/*/routes.tsx')`). Exports `routes: RouteObject[]` (absolute paths, `/grains/permits`, `/grains/permits/new`, `/grains/permits/:id`; optional `handle: { crumb: L10n }` for a trailing breadcrumb such as "New"/"Edit") and `menu: MenuItem[]`. + `MenuItem = { key, title:{en,ar}, icon: MuiIconComponent, path?, createPath?, roles?: string[], color?, children?: MenuItem[] }`. Group = `children` (no path). `createPath` shows the "+" on the row (row itself opens the list). `roles` = allowed `roleCode`s (omitted = everyone); filters menu, dashboard links and also guards the URL (403 page) via longest-prefix match on `path`/`createPath`. Several slices can each add their own `routes.tsx` only if the folder differs; for ONE feature with many slices, keep one `routes.tsx` that imports per-slice route/menu arrays (add slice files, edit only that feature's `routes.tsx`). +2. `strings.ts` - feature strings: `export default defineStrings({ 'grains.title': { en, ar }, ... })` (`defineStrings` from `@/i18n/useUi`). Use in components: `const { t, tr, lang } = useFeatureUi(strings)`; `t` accepts the feature keys and the shell keys (`common.save`, `grid.empty`, ...), `tr({en,ar})` picks from inline labels. Auto-merged for backend caption lookups too (toast text that looks like `UPPER_CASE_KEY` is translated if a feature string with that key exists; everything else is shown verbatim). Prefix keys with the feature name to avoid collisions. +3. `meta/.ts(x)` (or `meta.tsx`) - declarative tables, types in `@/components/meta/types`: + - `GridMeta`: `{ key, endpoint | fetcher, rowKey, columns: ColumnMeta[], filters?: FilterMeta[], status?: {param, options: StatusMeta[]}, defaultFilters?, requireFilter?, pageSize?, rowActions?: RowAction[], onRowClick? }`. `ColumnMeta`: `{ key, header:{en,ar}, field?, format?: 'text'|'number'|'date'|'datetime'|'boolean'|'status', statuses?, render?(row,{lang}), ltr?, align?, width?, hideBelow?: 'sm'|'md'|'lg' }`. `StatusMeta`: `{ value, label:{en,ar}, color }`. List endpoints must return `PagedResult` = `{items,page,pageSize,totalCount}`; request params are `page` (1-based), `pageSize` + each active filter name + status param. Filters/status/paging live in URL params (`?f=1` marker only when `defaultFilters` exist), one request per action; defaults are used for the first request. After writes: `queryClient.invalidateQueries({ queryKey: gridKey(meta.key) })` (`gridKey` from `@/components/DataGrid`). + - `FormMeta`: `{ key, sections: [{ key, title?, columns?: 1|2|3, fields: FieldMeta[] }] }`. `FieldMeta`: `{ name, type: 'text'|'number'|'date'|'select'|'autocomplete'|'checkbox'|'textarea'|'attachment', label, required?, readOnly?, hiddenOnCreate?, hiddenWhen?, requiredWhen?, disabledWhen?, defaultValue?, maxLength?, min?, max?, pattern?:{regex,message}, options?, dependsOn?, inputKind?: 'plate'|'phone'|'email'|'code' (forces LTR input), ltr?, span?: 1|2|3|'full', rows?, placeholder?, helper?, attachment?:{endpoint?,accept?} }`. + - Conditional rules are declarative `Rule = {field, op?: eq|ne|in|nin|empty|notEmpty|truthy|falsy, value?} | {all:[]} | {any:[]} | {not: Rule}`; evaluated by ONE function (`isHidden`/`isRequired`/`isDisabled` in `MetaForm/rules.ts`) used by render, validation and payload. Payload = visible, non-read-only fields only (empty string -> null). Dates are `yyyy-mm-dd` strings (display `dd/mm/yyyy`; the native date picker follows the browser locale). + - Options: static `OptionItem[]` (`{value,label: string | {en,ar}}`) or `OptionsLoader { key, load({lang,parent}) => Promise, staleTime? }` (cached by React Query with `lang` in the key; `dependsOn` passes the parent field value and clears the child on change). +4. `api.ts` - React Query hooks via the shared client: `api.get/post/put/patch/delete/upload` from `@/api/client` (bearer token, `ApiError` with `status`, `code`, `message` = ProblemDetails detail/title verbatim, `fieldErrors`). Reads: `useQuery`. Writes: `useWrite(fn, { invalidate: [keys], successMessage? })` from `@/api/hooks` - toasts the response `message` (or default "Saved"), toasts `ApiError.message` on failure, and the client shows the blocking "Saving..." overlay for every non-GET call. Pass `{ silent: true }` as the last arg for background lookups (no progress bar). Language-dependent queries: put `lang` (from `useUi()`) in the key and gate with `useLanguage().langReady` (`useOptions` and `DataGrid` already do). +5. Pages (`pages.tsx`): `PageHeader` + `` for lists; `` for forms (confirm dialog before save is built in, `confirmMessage={false}` skips it; feed `ApiError.fieldErrors` to `serverErrors` to mark+focus the failing field). Other building blocks: `useConfirm()` (`@/providers/ConfirmProvider`), `useToast()` (success/warning/error), `StatusChip`, `LoadingBanner`, `EmptyState`, `FileUpload` (stub, posts to `/files/temp` or `attachment.endpoint`, expects `{id}`), `Logo`. +6. Mock data (optional, dev only): `registerMock('GET', /^\/grains\/permits$/, ({params,body,match}) => ...)` from `@/api/mock`, import it from your `routes.tsx`; active only with `VITE_MOCK=1`. + +Rules: bilingual everything (no raw keys, no English in the Arabic layout); logical CSS props only (`marginInlineStart`, `paddingInlineEnd`, `textAlign:'start'`); `dir="ltr"` for plates/phones/codes; same-width fullWidth controls; auth endpoint shapes are isolated in `web/src/api/auth.ts` (login `{username,password}` -> `{token,user}`, `/auth/me`, `PUT /auth/language {lang:'AR'|'EN'}`, `POST /auth/change-password {currentPassword,newPassword}`) - adjust there if the backend differs. + +## Database connection notes +Real QA Oracle 11.2.0.4 (`qajodb`) with two schemas = the two legacy ColdFusion datasources. **Real column lists are in `docs/schema/NAFITHTCS.md` and `docs/schema/NTP.md` - consult them before writing SQL; legacy CFC queries are the source of intent, the schema docs are the source of truth for names/types/lengths/nullability.** + +### Two sessions (transactions are per connection) +| Session / base / unit of work | Config key | Schema | Tables | +|---|---|---|---| +| `IDbSession` / `OracleRepositoryBase` / `IUnitOfWork` (**primary, default for slices**) | `ConnectionStrings:NAFITHTCS` | NAFITHTCS | PERMITS, NTP_TRUCKS, NTP_TRAILERS, NTP_DRIVERS, EVENTS, GRAINS*, UTT, INVALID_ACCESS_LOG, LOCATIONS_IPS, and LOCATIONS / STATUS / CARGOTYPE / CITIES (the NAFITHTCS copies, which have DOMAIN etc.) | +| `INtpDbSession` / `NtpRepositoryBase` / `INtpUnitOfWork` | `ConnectionStrings:NtpSchema` | NTP | NTPUSERS, ROLES, GROUPS, LOGS, COMPANIES, NATIONALITY, URL_SECURITY and other tables listed only in `docs/schema/NTP.md` | +- A repository that needs both takes both sessions (see `AuthRepository`, `LookupRepository`: derive from `NtpRepositoryBase`/`OracleRepositoryBase` for one and wrap the other in a small private helper subclass). There is no distributed transaction: `IUnitOfWork` covers only the NAFITHTCS connection, `INtpUnitOfWork` only the NTP one. +- NAFITHTCS can only SELECT (+UPDATE NTPUSERS) on NTP objects, so every NTP-owned INSERT (e.g. `LOGS`) must go through the NTP session. Do not rely on same-named tables: NTP.LOCATIONS / NTP.STATUS are different, smaller tables than the NAFITHTCS ones. +- `EventLogger` (EVENTS, `SEQ_EVENTS`) is on the primary connection. Sequences verified present: SEQ_EVENTS, SEQ_INVALID_ACCESS_LOG (NAFITHTCS), SEQ_LOGS (NTP). Check any other sequence in the `## SEQUENCES` section of the schema doc of the schema that owns the table. +- `/health/ready` checks both connections (`oracle` = NAFITHTCS, `oracle-ntp` = NTP). +- Local credentials: git-ignored `src/NTP.Api/appsettings.Local.json` (template: `appsettings.Local.example.json`); never put passwords in tracked files. +- Column-length gotchas seen: `LOGS.IPADDRESS` VARCHAR2(15), `INVALID_ACCESS_LOG.BROWSER` VARCHAR2(300), `EVENTS.PREVSTATUS/CURRENTSTATUS` VARCHAR2(10), `EVENTS.EVENTTYPE` VARCHAR2(20); `EVENTS` has insert triggers (TRG_EVENT_RECORD_DATE, TRG_EVENT_PERMIT_ROUTE). + +### How a slice agent validates its own SQL read-only +1. Check every table/column/type/nullability against `docs/schema/.md` (columns marked `notnull` without a default must be supplied by INSERTs). +2. Optionally confirm against the live DB with a throwaway console project OUTSIDE the solution (e.g. scratchpad; reference `Oracle.ManagedDataAccess.Core` 3.21.130; read the password from an env var or from `appsettings.Local.json`, never write it into a file you create). For each SELECT: open a connection as the owning schema and run `SELECT * FROM () WHERE 1=0` with every `:bind` added as a null `OracleParameter` (`BindByName = true`); a clean execute means tables, columns and syntax are valid. For INSERT/UPDATE: do NOT execute them - select the same columns with `WHERE 1=0`, and query `user_tab_columns` (type, length, NULLABLE, DATA_DEFAULT) and `user_triggers` / `user_sequences` for the target. Never call `NEXTVAL`, DML, DDL or stored procedures that write. +3. Do not guess or brute-force user passwords; the login flow can only be exercised with a bogus user (401). diff --git a/docs/schema/NAFITHTCS.md b/docs/schema/NAFITHTCS.md new file mode 100644 index 0000000..51f9beb --- /dev/null +++ b/docs/schema/NAFITHTCS.md @@ -0,0 +1,3613 @@ +# Schema NAFITHTCS (Oracle 11.2.0.4, qajodb) - columns: NAME TYPE(len/prec,scale) NULLABLE; PK marked + +## ACTIVATIONLOG +ID NUMBER(22) notnull PK +ACTIONDATE DATE(7) notnull +TYPE VARCHAR2(20) notnull +DONEBY VARCHAR2(50) notnull +DONEBYROLE VARCHAR2(10) notnull +ACTIVATIONDATA CLOB(4000) notnull + +## ACTRELEASE_TMP +CONTAINERIDENTIFIER VARCHAR2(20) notnull +ISOCODE VARCHAR2(20) notnull +EXPIRATIONDATE VARCHAR2(20) notnull +ACT_REL_TYPE VARCHAR2(20) null + +## ACTRELEASE_TMP2 +CONTAINERIDENTIFIER VARCHAR2(20) notnull +ISOCODE VARCHAR2(20) notnull +EXPIRATIONDATE VARCHAR2(20) notnull +ACT_REL_TYPE VARCHAR2(20) null +ISDIRECT VARCHAR2(1) notnull + +## ACTRELEASE_TMP3 +CONTAINERIDENTIFIER VARCHAR2(20) notnull +ISOCODE VARCHAR2(20) notnull +EXPIRATIONDATE VARCHAR2(20) notnull +ACT_REL_TYPE VARCHAR2(20) null +ISDIRECT VARCHAR2(1) notnull + +## ACT_CONTAINER_EXPORT +ID NUMBER(22) notnull PK +CONTAINER_ID VARCHAR2(100) null +LINE_OP VARCHAR2(200) null +EXPORT_CLERANCE VARCHAR2(100) null +BOOKING_ID VARCHAR2(100) null +ISOTYPE VARCHAR2(100) null +STATUS_CODE VARCHAR2(100) notnull +CREATION_DATE DATE(7) notnull +LAST_UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(50) null +CREATED_BY VARCHAR2(50) null +SCAC VARCHAR2(50) null +CAN VARCHAR2(50) null +PN NUMBER(22) null +CUSTOMS_EXPORT_ID NUMBER(22) null + +## ACT_CUSTOM_EXPORT +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +STATUS_CODE VARCHAR2(15) notnull +CUSTOM_CENTER VARCHAR2(15) notnull +PERM_YEAR VARCHAR2(15) null +PERM_NO VARCHAR2(50) notnull +PERM_SERIAL VARCHAR2(15) null +PERM_DATE DATE(7) null +CAN VARCHAR2(20) null +CA VARCHAR2(200) null +DEST_CENTER_NO VARCHAR2(15) null +DEST_CENTER_NAME VARCHAR2(200) null +CID VARCHAR2(50) notnull + +## ACT_GATEEVENT_INTEGRATION +NAFITH_PERMIT_NUMBER NUMBER(22) null +CONTAINERNUMBER VARCHAR2(200) null +TRUCK_NO VARCHAR2(200) null +POSITION VARCHAR2(200) null +TR_TYPE VARCHAR2(200) null +PRECHECK VARCHAR2(200) null +INGATE_PICKUP VARCHAR2(200) null +HANDEL VARCHAR2(200) null +EXIT_TIME VARCHAR2(200) null + +## ACT_PREGATE +TR_TYPE VARCHAR2(10) null +TRUCK_LICENSE_NBR NUMBER(22) null +STATUS VARCHAR2(10) null +CTR_NBR VARCHAR2(20) null +TR_DAY DATE(7) null +DI_POS VARCHAR2(10) null +PRECHECK DATE(7) null +INGATE_PICKUP DATE(7) null +HANDEL DATE(7) null +EXIT_TIME DATE(7) null +LASTUPDATETIMESTAMP DATE(7) null +RECORDSTATUS NUMBER(22) null +PRECHECKFILEDATETIME DATE(7) null + +## ACT_PREGATE_ERROR_LOG +ORA_ERR_NUMBER$ NUMBER(22) null +ORA_ERR_MESG$ VARCHAR2(2000) null +ORA_ERR_ROWID$ ROWID(10) null +ORA_ERR_OPTYP$ VARCHAR2(2) null +ORA_ERR_TAG$ VARCHAR2(2000) null +ID VARCHAR2(4000) null +CODE VARCHAR2(4000) null +DESCRIPTION VARCHAR2(4000) null + +## ACT_PREGATE_FILES +ID NUMBER(22) null +FILENAME VARCHAR2(500) null +JOBID NUMBER(22) null +FILETIMESTAMP DATE(7) null + +## ACT_PREGATE_JOBS +ID NUMBER(22) null +LASTEXECUTION DATE(7) null + +## ACT_PREGATE_TEMP +TR_TYPE VARCHAR2(10) null +TRUCK_LICENSE_NBR NUMBER(22) notnull +STATUS VARCHAR2(10) null +CTR_NBR VARCHAR2(20) notnull +TR_DAY DATE(7) null +DI_POS VARCHAR2(10) null +PRECHECK DATE(7) null +INGATE_PICKUP DATE(7) null +HANDEL DATE(7) null +EXIT_TIME DATE(7) null +PRECHECKFILEDATETIME DATE(7) null + +## ACT_TRANSACTIONS_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +DATA CLOB(4000) notnull +OPERATION_NAME VARCHAR2(100) notnull +STATUS_CODE VARCHAR2(15) notnull + +## AI_VEHICLE +TYPE VARCHAR2(10) notnull +HR24 NUMBER(22) notnull + +## AI_VIOLATION_HRS +TYPE VARCHAR2(15) notnull +HR24 NUMBER(22) notnull + +## ARAB_BRIDGE_QUEUE_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) null +STATUS_CODE VARCHAR2(20) null +AB_ID NUMBER(22) null +TN VARCHAR2(20) null +TN_CODE VARCHAR2(20) null +PN VARCHAR2(20) null +QUEUE_DATA CLOB(4000) null +RESULT_MSG CLOB(4000) null +YARD_ID NUMBER(22) null + +## ARAB_BRIDGE_TRUCKS +ID NUMBER(22) notnull PK +TN VARCHAR2(20) null +CREATIONDATE DATE(7) null +EXPIREDATE DATE(7) null +TN_CODE VARCHAR2(20) null +PN VARCHAR2(20) null +STATUS VARCHAR2(20) null + +## ASCII_LETTERS +LETTER NVARCHAR2(6) null +LETTER_ASCII NUMBER(22) null +LETTER_GROUP NVARCHAR2(6) null + +## ASEZA_PERMIT_TYPES +C NUMBER(22) null +SHIPMENTMODETEXT NVARCHAR2(4000) null +SHIPMENTMODEVALUE NVARCHAR2(75) null +FMTT VARCHAR2(4000) null +SMTT VARCHAR2(4000) null +OPERATIONTYPETEXT NVARCHAR2(4000) null +OPERATIONTYPEVALUE NVARCHAR2(75) null +FMINBONDTYPECODE NVARCHAR2(30) null +OPERATIONCATEGORY NVARCHAR2(63) null +INBONDTYPECODE NVARCHAR2(30) null +TT NVARCHAR2(1500) null + +## BLACKLIST +ID NUMBER(22) notnull PK +TYPECODE NVARCHAR2(15) null +VALUE NVARCHAR2(3000) null +TYPEID NUMBER(22) null +REMARKS NVARCHAR2(3000) null +SEVERITY NVARCHAR2(15) null +STATUS VARCHAR2(10) notnull +CREATEUSERID VARCHAR2(15) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(20) null +LASTUPDATETIMESTAMP DATE(7) null +DOMAINNAME VARCHAR2(50) notnull +DURATION NUMBER(22) null +ACTIVATION_TRIGGER VARCHAR2(50) null +EXPIRYDATE DATE(7) null +ACTIVATEDBY VARCHAR2(20) null +ACTIVATIONDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null +REVOKEDATE DATE(7) null +MANUALKIOSKID NUMBER(22) null +TAGGING_BL_TYPE VARCHAR2(50) null +YARDNUMBER NUMBER(22) null +POSTEDTOKIOSKSERVER NUMBER(22) null +BL_CATEGORY VARCHAR2(25) null +BL_DANGER NUMBER(22) null +PERMIT_ID NUMBER(22) null +TROUBLESHOOT_SEQ_NUMBER NUMBER(22) null +CID VARCHAR2(30) null +RUN_OVER_LOCATION NUMBER(22) null +DELEGATED_TO_ROLE VARCHAR2(30) null +CTL_LOCATION NUMBER(22) null + +## BLACKLIST_DANGER +ID NUMBER(22) notnull PK +PERMIT_ID NUMBER(22) notnull +TN VARCHAR2(50) notnull +CREATIONDATE DATE(7) notnull +STATUS_CODE VARCHAR2(10) notnull +BLACKLIST_ID VARCHAR2(8) notnull + +## BLACKLIST_QUEUE_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) null +STATUS_CODE VARCHAR2(20) null +BLACKLIST_ID NUMBER(22) notnull +BLACKLIST_STATUS VARCHAR2(20) null +BLACKLIST_TYPEID NUMBER(22) null +BLACKLIST_ON VARCHAR2(20) null +BLACKLIST_VALUE VARCHAR2(20) null +QUEUE_DATA CLOB(4000) null +RESULT_MSG CLOB(4000) null +YARD_ID NUMBER(22) null + +## BLACKLIST_REASON +ID NUMBER(22) notnull PK +NAME VARCHAR2(250) null +STATUS VARCHAR2(10) notnull +CREATEUSERID VARCHAR2(8) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(8) null +LASTUPDATETIMESTAMP DATE(7) null +DOMAINNAME VARCHAR2(50) notnull + +## BLOCKEDLOCATIONS +ID NUMBER(22) notnull PK +LOCATIONID NUMBER(22) null +CARGOTYPEID VARCHAR2(50) null +REASON VARCHAR2(500) null +CREATEDBY VARCHAR2(50) null +CREATIONDATE DATE(7) null +UPDATEDBY VARCHAR2(50) null +LASTUPDATEDATE DATE(7) null +STATUS NUMBER(22) null +LIMIT NUMBER(22) null +REMAINING NUMBER(22) null + +## CARGORELEASES +ID NUMBER(22) notnull PK +PERM_NO NUMBER(22) null +PERM_SUB NUMBER(22) null +PERM_YEAR NUMBER(22) null +CA_CODE NUMBER(22) null +PERM_DATE DATE(7) null +NUM_ITEMS NUMBER(22) null +NUM_PACK NUMBER(22) null +MANIFEST_NO VARCHAR2(50) null +WEIGHT_TOTAL NUMBER(22) null +EXIT_YETEM DATE(7) null +DEST_CENTRE NUMBER(22) null +DEST_COUNTRY VARCHAR2(2) null +CONTR_NO VARCHAR2(20) null +KEY_CUO VARCHAR2(3) null +KEY_VOY_NBER VARCHAR2(20) null +KEY_DEP_DATE VARCHAR2(10) null +KEY_BOL_REF VARCHAR2(30) null +CAR_CTN_NBR VARCHAR2(20) null +WAYBILLID NUMBER(22) null +ISACTIVE VARCHAR2(5) null +STATUS VARCHAR2(8) null +CREATEDBY VARCHAR2(10) null +CREATEDATE DATE(7) null +UPDATEDBY NVARCHAR2(300) null +LASTUPDATEDATE DATE(7) null +KEY_NBER VARCHAR2(200) null +SAD_REG_SERIAL NUMBER(22) null +KEY_YEAR NUMBER(22) null +DESCRP1 NVARCHAR2(3000) null +UPDATEDTYPE NVARCHAR2(150) null +TOTALQUOTA NUMBER(22) null +TOTALUSEDQUOTA NUMBER(22) null +OPERATIONTYPE VARCHAR2(10) null +SHIPMENTMODE VARCHAR2(10) null +FIRSTDESTINATION VARCHAR2(20) null +CRTYPE VARCHAR2(20) null +BAYANNO VARCHAR2(20) null +MIG NUMBER(22) null +CHI_POLICYNO VARCHAR2(20) null +NOTES VARCHAR2(2000) null +TENDERID NUMBER(22) null +ISOCODE VARCHAR2(10) null +ACT_REL_TYPE VARCHAR2(50) null +VESSELNAME VARCHAR2(100) null +ISDIRECT VARCHAR2(1) null +PREV_DEST_CENTRE NUMBER(22) null +DEST_CENTRE_UPDATETIME DATE(7) null +DEST_CENTRE_UPDATEBY VARCHAR2(20) null +DEST_CENTRE_NOTES NVARCHAR2(600) null +RELATED_CRID NUMBER(22) null +RELATED_PERM_NO NUMBER(22) null + +## CARGORELEASESAUDIT +ID NUMBER(22) notnull PK +CRID NUMBER(22) notnull +PN NUMBER(22) notnull +COMPANYID NUMBER(22) notnull +STATUS NUMBER(22) null +CREATETIMESTAMP DATE(7) null +CREATEUSERID VARCHAR2(15) null +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null + +## CARGORELEASESDELEGATION +ID NUMBER(22) notnull PK +CRID NUMBER(22) null +COMPCODE NUMBER(22) null +ISACTIVE VARCHAR2(1) null +CREATETIMESTAMP DATE(7) null +DONEBY VARCHAR2(15) null +CREATEUSERID VARCHAR2(15) null +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null +QUOTA NUMBER(22) null +USEDQUOTA NUMBER(22) null +DEDUCT NUMBER(22) null +MIG NUMBER(22) null +DELIGATIONTYPE NUMBER(22) null + +## CARGORELEASESDETAILS +ID NUMBER(22) notnull PK +CRID NUMBER(22) null +GOODS_DESC1 NVARCHAR2(3000) null +GOODS_DESC2 NVARCHAR2(3000) null +GOODS_DESC3 NVARCHAR2(3000) null +SUBWEIGHT NUMBER(22) null + +## CARGORELEASESLOG +ID NUMBER(22) notnull PK +CRID NUMBER(22) null +OLDCA NUMBER(22) null +NEWCA NUMBER(22) null +CREATIONDATE DATE(7) notnull +CREATEDBY VARCHAR2(10) null +PERMITNO NUMBER(22) null +YEAR NUMBER(22) null + +## CARGORELEASESPERMITS +ID NUMBER(22) notnull PK +CRID NUMBER(22) null +COMPID NUMBER(22) notnull +PN NUMBER(22) null +PERMITID NUMBER(22) null +ISLOCKED NUMBER(22) notnull +CREATIONDATE DATE(7) notnull +CONFIRMATIONDATE DATE(7) null +CONFIRMEDBY VARCHAR2(10) null +SHIPMENTSTATUSCODE VARCHAR2(8) null +STATUS NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null + +## CARGORELEASESPERMITS_AB +ID NUMBER(22) notnull PK +CRID NUMBER(22) null +COMPID NUMBER(22) notnull +PN NUMBER(22) null +PERMITID NUMBER(22) null +ISLOCKED NUMBER(22) notnull +CREATIONDATE DATE(7) notnull +CONFIRMATIONDATE DATE(7) null +CONFIRMEDBY VARCHAR2(10) null +SHIPMENTSTATUSCODE VARCHAR2(8) null +STATUS NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null + +## CARGORELEASES_AB +ID NUMBER(22) notnull PK +PERM_NO NUMBER(22) null +PERM_SUB NUMBER(22) null +PERM_YEAR NUMBER(22) null +CA_CODE NUMBER(22) null +PERM_DATE DATE(7) null +NUM_ITEMS NUMBER(22) null +NUM_PACK NUMBER(22) null +MANIFEST_NO VARCHAR2(50) null +WEIGHT_TOTAL NUMBER(22) null +EXIT_YETEM DATE(7) null +DEST_CENTRE NUMBER(22) null +DEST_COUNTRY VARCHAR2(2) null +CONTR_NO VARCHAR2(20) null +KEY_CUO VARCHAR2(3) null +KEY_VOY_NBER VARCHAR2(20) null +KEY_DEP_DATE VARCHAR2(10) null +KEY_BOL_REF VARCHAR2(20) null +CAR_CTN_NBR VARCHAR2(20) null +WAYBILLID NUMBER(22) null +ISACTIVE VARCHAR2(5) null +STATUS VARCHAR2(8) null +CREATEDBY VARCHAR2(15) null +CREATEDATE DATE(7) null +UPDATEDBY NVARCHAR2(300) null +LASTUPDATEDATE DATE(7) null +KEY_NBER VARCHAR2(200) null +SAD_REG_SERIAL NUMBER(22) null +KEY_YEAR NUMBER(22) null +DESCRP1 NVARCHAR2(3000) null +UPDATEDTYPE NVARCHAR2(150) null +TOTALQUOTA NUMBER(22) null +TOTALUSEDQUOTA NUMBER(22) null +OPERATIONTYPE VARCHAR2(10) null +SHIPMENTMODE VARCHAR2(10) null +FIRSTDESTINATION VARCHAR2(20) null +CRTYPE VARCHAR2(5) null +BAYANNO VARCHAR2(20) null +MIG NUMBER(22) null +CHI_POLICYNO VARCHAR2(20) null +NOTES VARCHAR2(2000) null +SENDFROM VARCHAR2(200) null +SENDTO VARCHAR2(200) null + +## CARGOTYPE +ID NUMBER(22) notnull PK +NAME NVARCHAR2(150) null +DOMAIN VARCHAR2(10) notnull +SORTORDER NUMBER(22) null +CODE VARCHAR2(25) null + +## CARGOTYPE_MAPPING +ID NUMBER(22) notnull PK +CARGOTYPEID NUMBER(22) notnull +PARENTID NUMBER(22) notnull + +## CAR_BOL_CTN_220 +KEY_CUO VARCHAR2(10) null +KEY_VOY_NBER VARCHAR2(50) null +KEY_DEP_DATE VARCHAR2(50) null +KEY_BOL_REF VARCHAR2(50) null +CAR_CTN_IDENT VARCHAR2(50) null +CAR_CTN_NBR VARCHAR2(50) null +PERM_NO NUMBER(22) null +PERM_YEAR NUMBER(22) null +PERM_FOLLOW_NO VARCHAR2(10) null +CLOSED_FLAG VARCHAR2(20) null +CLOSED_DATE VARCHAR2(50) null +CLOSED_USER_ID VARCHAR2(20) null +PRINTED VARCHAR2(50) null + +## CAR_TRANS_CTN_220 +KEY_CUO VARCHAR2(10) null +KEY_VOY_NBER VARCHAR2(50) null +KEY_DEP_DATE VARCHAR2(50) null +KEY_BOL_REF VARCHAR2(50) null +CAR_CTN_IDENT VARCHAR2(50) null +CAR_CTN_NBR VARCHAR2(50) null +TRANS_NO NUMBER(22) null +TRANS_YEAR NUMBER(22) null +PERM_FOLLOW_NO VARCHAR2(10) null +CLOSED_FLAG VARCHAR2(20) null +CLOSED_DATE VARCHAR2(50) null +CLOSED_USER_ID VARCHAR2(20) null +PRINTED VARCHAR2(50) null +TRANS_ID NUMBER(22) null +DEST_CODE VARCHAR2(50) null +PRINTED_DATE DATE(7) null + +## CHECK_INTERNAL_CONTAINERS +ID NUMBER(22) notnull PK +PERMIT_ID NUMBER(22) null +BLACKLIST_ID NUMBER(22) null +STATUS VARCHAR2(50) null +CID VARCHAR2(50) null +CREATIONDATE DATE(7) null +CREATEUSERID VARCHAR2(50) null +UPDATEDUSERID VARCHAR2(50) null +UPDATEDATE DATE(7) null +CONFIRM NUMBER(22) notnull +CONFIRM_USER VARCHAR2(20) null +CONFIRM_DATE DATE(7) null +CONFIRM_NOTE VARCHAR2(1000) null +CAN_NOT_OPEN NUMBER(22) null +REMARKS VARCHAR2(1000) null + +## CID_EXPORT_EXCEPTIONS +CID VARCHAR2(50) null +CREATION_DATE DATE(7) notnull +CREATED_BY VARCHAR2(33) null + +## CID_HISTORY +ID NUMBER(22) notnull PK +CRID NUMBER(22) null +OLDCID VARCHAR2(20) null +NEWCID VARCHAR2(20) null +CREATEDBY VARCHAR2(50) null +CREATIONDATE DATE(7) null + +## CITIES +ID NUMBER(22) notnull PK +NAME VARCHAR2(20) null +SORTORDER NUMBER(22) null + +## COMPANY_USER_ACTIVITY +ID NUMBER(22) notnull PK +USER_ID NUMBER(22) notnull +ACTIVITY_ID NUMBER(22) notnull +COMPANY_NUMBER NUMBER(22) notnull +CREATION_DATE DATE(7) notnull +STATUS NUMBER(22) notnull +UPDATE_DATE DATE(7) null +UPDATE_USER VARCHAR2(50) null +CREATE_USER VARCHAR2(50) null + +## COMPANY_USER_ACTIVITY_TEMP +ID NUMBER(22) notnull PK +USER_ID NUMBER(22) null +ACTIVITY_ID NUMBER(22) null +COMPANY_NUMBER NUMBER(22) null +CREATION_DATE DATE(7) null +STATUS NUMBER(22) null +UPDATE_DATE DATE(7) null + +## CONTAINERVALIDITY +ID NUMBER(22) notnull PK +DOCUMENTID VARCHAR2(50) notnull +SHIPPINGLINE NVARCHAR2(30) null +CID VARCHAR2(15) null +ISO VARCHAR2(10) null +DTM36 DATE(7) notnull +RECORDDATE DATE(7) notnull +NOTES NVARCHAR2(900) null +RETURNTYPE NVARCHAR2(150) null +DTM132 DATE(7) null +NOTEID NUMBER(22) null +LOCATION NVARCHAR2(150) null +CRN NUMBER(22) null + +## CONTAINERVALIDITYNOTES +SHIPPINGLINEID NUMBER(22) null +NOTES NVARCHAR2(1500) null +ID NUMBER(22) notnull PK + +## CONTAINER_ISO +CODE VARCHAR2(20) null PK +LENGTH VARCHAR2(10) null +HEIGHT VARCHAR2(10) null +DESCRIPTION VARCHAR2(200) null + +## CONTAINER_SHIPPING_LINE +CONTAINERPREFIX VARCHAR2(4) null +SHIPPINGLINECODE VARCHAR2(50) null + +## CTL_ORDERS +ID NUMBER(22) notnull PK +ORDER_NO NUMBER(22) notnull +CREATION_DATE DATE(7) notnull +QUANTITY NUMBER(22) notnull +SHIPPING_LINE VARCHAR2(4) null +ATTACHMENT VARCHAR2(100) null +CONTAINER_SIZE NUMBER(22) null +STATUS_CODE VARCHAR2(10) notnull +CREATE_USERID VARCHAR2(50) null +UPDATE_USERID VARCHAR2(50) null +UPDATE_DATE DATE(7) null +NOTES VARCHAR2(200) null +ORDER_DATE DATE(7) null +ORDER_TYPE VARCHAR2(10) null +USER_TYPE VARCHAR2(40) null + +## CTL_ORDERS_DETAILS +ID NUMBER(22) notnull PK +CTL_ORDER_ID NUMBER(22) notnull +PERMIT_ID NUMBER(22) null +STATUS_CODE NVARCHAR2(30) notnull +CREATION_DATE DATE(7) notnull +CID VARCHAR2(11) notnull +BLACKLIST_ID NUMBER(22) null +UPDATE_USERID VARCHAR2(50) null +UPDATE_DATE DATE(7) null +USER_TYPE VARCHAR2(50) null + +## CUSTOMS_EXPORT +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +STATUS_CODE VARCHAR2(15) notnull +CUSTOM_CENTER VARCHAR2(15) notnull +PERM_YEAR VARCHAR2(15) null +PERM_NO VARCHAR2(50) notnull +PERM_SERIAL VARCHAR2(15) null +PERM_DATE DATE(7) null +CAN VARCHAR2(20) null +CA VARCHAR2(200) null +DEST_CENTER_NO VARCHAR2(15) null +DEST_CENTER_NAME VARCHAR2(200) null +CID VARCHAR2(50) notnull +PERM_TYPE VARCHAR2(50) null +CONNECT_TO_ACT VARCHAR2(5) null +LAST_UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(50) null + +## DELIGATIONTYPE +ID NUMBER(22) notnull PK +NAME VARCHAR2(50) null + +## DEMURAGEVOUCHERS +ID NUMBER(22) notnull PK +PERMITID NUMBER(22) null +CID VARCHAR2(11) notnull +COMPANYID NUMBER(22) null +FEES NUMBER(22) notnull +CREATIONDATE DATE(7) notnull +CREATEDBY VARCHAR2(50) notnull +APPROVALDATE DATE(7) null +APPROVEDBY VARCHAR2(50) null +VOIDDATE DATE(7) null +VOIDBY VARCHAR2(50) null +STATUS VARCHAR2(50) null +SRVCID NUMBER(22) notnull +NOTES NVARCHAR2(900) null + +## DINARK_API_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +STATUS_CODE VARCHAR2(20) notnull +SERVICE_NAME VARCHAR2(20) notnull +EWALLET_NUMBER VARCHAR2(50) notnull +AMOUNT NUMBER(22) notnull +TN VARCHAR2(20) notnull +TRN VARCHAR2(20) notnull +NNPN VARCHAR2(20) notnull +REQUEST_DATA CLOB(4000) notnull +RESPONSE_DATA CLOB(4000) null +PERMIT_REQUEST_ID NUMBER(22) null + +## DRIVERS +ID NUMBER(22) notnull PK +NAME NVARCHAR2(150) notnull +NNPN NUMBER(22) notnull +DLN NUMBER(22) notnull +DRIVERPHONE NUMBER(22) notnull +PHONETYPE VARCHAR2(15) notnull +STATUS VARCHAR2(20) notnull +CREATEDUSERID VARCHAR2(50) notnull +CREATETIMPESTAMP DATE(7) notnull +UPDATEUSERID VARCHAR2(50) null +UPDATETIMPESTAMP DATE(7) null + +## DRIVERS_INFO +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +CREATED_BY VARCHAR2(50) null +STATUS_CODE VARCHAR2(20) notnull +NAME_AR NVARCHAR2(300) null +NAME_EN NVARCHAR2(300) null +NATIONALITY NVARCHAR2(30) null +DATE_OF_BIRTH DATE(7) null +BLOOD_GROUP VARCHAR2(10) null +NNPN VARCHAR2(20) null +ADDRESS NVARCHAR2(750) null +LICENSE_NO VARCHAR2(20) null +LICENSE_ISSUE_DATE DATE(7) null +LICENSE_EXPIRY_DATE DATE(7) null +LAST_UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(50) null +NOTES NVARCHAR2(750) null +REVOKE_REASON VARCHAR2(100) null +GOVERNATE VARCHAR2(100) null +LICENSE_TYPE VARCHAR2(20) null +MOBILE VARCHAR2(15) null + +## EVENTS +ID NUMBER(22) notnull PK +WAYBILLID NUMBER(22) null +CRID NUMBER(22) null +PERMITID NUMBER(22) null +EVENTDATE DATE(7) notnull +EVENTTYPE VARCHAR2(20) null +PREVSTATUS VARCHAR2(10) null +CURRENTSTATUS VARCHAR2(10) null +DONEBY NVARCHAR2(300) null +LOCATIONID NUMBER(22) null +DOMAIN VARCHAR2(10) null +UPDATEDTYPE NVARCHAR2(150) null +REMARKS NVARCHAR2(600) null +FEES NUMBER(22) null +EVENTGROUP NUMBER(22) null +WEIGHT NUMBER(22) null +RECORDDATE DATE(7) null +KIOSKID NUMBER(22) null +KIOSK_READING_TYPE VARCHAR2(30) null +ORDERID VARCHAR2(20) null +INVALID_LOG_ID NUMBER(22) null + +## EVENTS_QUEUE_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +STATUS_CODE VARCHAR2(20) notnull +PERMITID NUMBER(22) notnull +EVENT_TYPE VARCHAR2(20) null +QUEUE_DATA CLOB(4000) null +RESULT_MSG CLOB(4000) null + +## EXCEPTIONS_OWNER +ID NUMBER(22) notnull PK +CODE VARCHAR2(10) notnull + +## EXTERNALDATALOG +MESSAGETYPE VARCHAR2(5) null +DESCRIPTION VARCHAR2(150) null +CREATETIMESTAMP DATE(7) null + +## EXTERNAL_INTEGRATION_QUEUE_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +TYPE VARCHAR2(50) notnull +OPERATION_TYPE VARCHAR2(50) notnull +STATUS_CODE VARCHAR2(20) notnull +PERMIT_ID NUMBER(22) notnull +PERMIT_STATUS_CODE VARCHAR2(20) null +PERMIT_CURRENT_LEG_ID NUMBER(22) notnull +QUEUE_DATA CLOB(4000) null +RESULT_MSG CLOB(4000) null +EVENT_ID NUMBER(22) null + +## FLEET_CARGOTYPE +ID NUMBER(22) notnull PK +NAME NVARCHAR2(150) notnull +SORTORDER NUMBER(22) notnull +CODE VARCHAR2(10) null + +## FLEET_DISTRIBUTION +ID NUMBER(22) notnull PK +ORDER_ID NUMBER(22) null +QUEUE_ID NUMBER(22) null +DISTRIBUTION_NUMBER NUMBER(22) null +TN NUMBER(22) null +STATUSCODE VARCHAR2(10) null +CREATION_DATE DATE(7) null +CREATED_BY VARCHAR2(20) null +RESPONSE_DATE DATE(7) null +RESPONSE_BY VARCHAR2(20) null +DELAY_DAYS NUMBER(22) null +DELAY_EXPIRE_DATE DATE(7) null +PERMIT_ID NUMBER(22) null +TRN NUMBER(22) null +NNPN NUMBER(22) null +DRVR NVARCHAR2(300) null +LASTUPDATEDATE DATE(7) null +LASTUPDATEBY VARCHAR2(20) null +NOTES NVARCHAR2(600) null +STOP_DRVR_ACTION NUMBER(22) null +TRUCKING_COMPANY NVARCHAR2(300) null +CLEARING_AGENT NVARCHAR2(300) null +CARGORELEASE NUMBER(22) null +CARGOTYPE NVARCHAR2(300) null +PN NUMBER(22) null +DESTINATION NVARCHAR2(300) null +NET_WEIGHT NUMBER(22) null +EMPTY_WEIGHT NUMBER(22) null +CLOSE_DATE DATE(7) null +CLOSED_BY NVARCHAR2(300) null + +## FLEET_ORDER +ID NUMBER(22) notnull PK +CR_ID NUMBER(22) notnull +ORDER_NO NUMBER(22) notnull +TN_COUNT NUMBER(22) notnull +STATUSCODE VARCHAR2(10) notnull +CREATION_DATE DATE(7) notnull +CREATED_BY VARCHAR2(20) notnull +UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(20) null +UPLOADED_DATE DATE(7) null +CARGO_TYPE VARCHAR2(20) null +SHIFT VARCHAR2(20) null +PERM_NO NUMBER(22) null +DISTRIBUTION_DATE DATE(7) null +NOTES VARCHAR2(500) null + +## FLEET_ORDER_DETAIL +ID NUMBER(22) notnull PK +ORDER_ID NUMBER(22) notnull +TRAILER_CATEGORY VARCHAR2(50) notnull + +## FLEET_QUEUE +ID NUMBER(22) notnull PK +STATUSCODE VARCHAR2(10) null +TN VARCHAR2(15) null +TRN VARCHAR2(15) null +TRAILER_CATEGORY VARCHAR2(20) null +LAST_PERMIT_DATE DATE(7) notnull +CONTACT_NNPN VARCHAR2(20) notnull +CONTACT_NAME NVARCHAR2(300) notnull +CONTACT_MOBILE NUMBER(22) null +CREATIONDATE DATE(7) notnull +CREATEDBY VARCHAR2(20) notnull +LASTUPDATEDATE DATE(7) null +LASTUPDATEBY VARCHAR2(20) null +NOTES VARCHAR2(200) null +QUEUE_DATE DATE(7) notnull +PREV_QUEUE_DATE DATE(7) notnull +DELAY_DAYS NUMBER(22) null +DELAY_EXPIRE_DATE DATE(7) null + +## FLEET_QUEUE_TEMP +ID NUMBER(22) notnull PK +STATUSCODE VARCHAR2(10) null +TN VARCHAR2(15) null +TRN VARCHAR2(15) null +TRAILER_CATEGORY VARCHAR2(20) null +LAST_PERMIT_DATE DATE(7) notnull +CONTACT_NNPN VARCHAR2(20) notnull +CONTACT_NAME NVARCHAR2(300) notnull +CONTACT_MOBILE NUMBER(22) null +CREATIONDATE DATE(7) notnull +CREATEDBY VARCHAR2(20) notnull +LASTUPDATEDATE DATE(7) null +LASTUPDATEBY VARCHAR2(20) null +NOTES VARCHAR2(200) null +QUEUE_DATE DATE(7) notnull +PREV_QUEUE_DATE DATE(7) notnull +DELAY_DAYS NUMBER(22) null +DELAY_EXPIRE_DATE DATE(7) null + +## FUELTENDERORDER +ID NUMBER(22) notnull PK +CARGOTYPE VARCHAR2(20) null +LOCATION NUMBER(22) null +DESTENATION NUMBER(22) null +ORDERDATE DATE(7) null +SHIFT VARCHAR2(20) null +QUANTITY NUMBER(22) null +STATUSCODE VARCHAR2(20) null +CREATETIMESTAMP DATE(7) null +CREATEUSERID VARCHAR2(50) null +LASTUPDATETIMESTAMP DATE(7) null +LASTUPDATEUSERID VARCHAR2(50) null +SCAC NUMBER(22) null + +## FUEL_BILLING +ID NUMBER(22) notnull PK +SCAC NUMBER(22) null +PN NUMBER(22) null +SERIALNO NUMBER(22) null +CARGOTYPE NUMBER(22) null +TN NUMBER(22) null +ORIGIN NUMBER(22) null +LOADDATE DATE(7) null +LTW NUMBER(22) null +LGW NUMBER(22) null +LNW NUMBER(22) null +DESTINATION NUMBER(22) null +DISCHARGEDATE DATE(7) null +DTW NUMBER(22) null +DGW NUMBER(22) null +DNW NUMBER(22) null +PRICE NUMBER(22) null +FINEPRICE NUMBER(22) null +LOSEFINE NUMBER(22) null +FINALCOST NUMBER(22) null +INVOICENUMBER NUMBER(22) null +COMPANYNAME VARCHAR2(200) null +CREATEUSERID NVARCHAR2(150) null +CREATETIMESTAMP DATE(7) null +STATUSCODE VARCHAR2(10) null +DEMURRAGEFINE NUMBER(22) null +OTHERFINE NUMBER(22) null +UPDATEUSERID NVARCHAR2(150) null +UPDATETIMESTAMP DATE(7) null +REROUTEPRICE NUMBER(22) null +REROUTENAME NVARCHAR2(150) null +CLIENTID NUMBER(22) null + +## FUEL_BILLING_BCKP +ID NUMBER(22) notnull +SCAC NUMBER(22) null +PN NUMBER(22) null +SERIALNO NUMBER(22) null +CARGOTYPE NUMBER(22) null +TN NUMBER(22) null +ORIGIN NUMBER(22) null +LOADDATE DATE(7) null +LTW NUMBER(22) null +LGW NUMBER(22) null +LNW NUMBER(22) null +DESTINATION NUMBER(22) null +DISCHARGEDATE DATE(7) null +DTW NUMBER(22) null +DGW NUMBER(22) null +DNW NUMBER(22) null +PRICE NUMBER(22) null +FINEPRICE NUMBER(22) null +LOSEFINE NUMBER(22) null +FINALCOST NUMBER(22) null +INVOICENUMBER NUMBER(22) null +COMPANYNAME VARCHAR2(200) null +CREATEUSERID NVARCHAR2(150) null +CREATETIMESTAMP DATE(7) null +STATUSCODE VARCHAR2(10) null +DEMURRAGEFINE NUMBER(22) null +OTHERFINE NUMBER(22) null +UPDATEUSERID NVARCHAR2(150) null +UPDATETIMESTAMP DATE(7) null +REROUTEPRICE NUMBER(22) null +REROUTENAME NVARCHAR2(150) null + +## FUEL_CLIENTS +ID NUMBER(22) notnull PK +NAME VARCHAR2(100) notnull + +## FUEL_FILES +ID NUMBER(22) notnull +ENTITYID NUMBER(22) null +ORIGINALNAME VARCHAR2(100) null +FILENAME VARCHAR2(100) null +ATTACHMENTTYPE VARCHAR2(20) null +CREATIONDATE DATE(7) null + +## FUEL_TEMP_DRIVER +NNPN VARCHAR2(100) null + +## FUEL_WAGE +ID NUMBER(22) notnull PK +ORIGINID NUMBER(22) null +DESTID NUMBER(22) null +WAGE NUMBER(22) null +STARTDATE DATE(7) null +ENDDATE DATE(7) null +CARGOTYPE NUMBER(22) null + +## FULLCONTAINERCOUNT +FULLCONTAINERCOUNTID NUMBER(22) null +MAXTNCOUNT NUMBER(22) null +MAXTRNCOUNT NUMBER(22) null +ISACTIVE VARCHAR2(1) null +CREATETIMESTAMP DATE(7) null +LASTUPDATETIMESTAMP DATE(7) null +CARGOTYPE VARCHAR2(10) null + +## GC_BLACKLIST +ID NUMBER(22) notnull PK +TN NUMBER(22) null +CREATIONDATE DATE(7) null +CREATEDBY VARCHAR2(50) null +EXPIRYDATE DATE(7) null +STATUSCODE VARCHAR2(50) null +REMARKS VARCHAR2(500) null +UPDATEDBY VARCHAR2(50) null +UPDATEDATE DATE(7) null + +## GC_FILES +ID NUMBER(22) notnull PK +ENTITYID NUMBER(22) notnull +ORIGINALNAME VARCHAR2(100) notnull +FILENAME VARCHAR2(100) notnull +ATTACHMENTTYPE VARCHAR2(20) notnull +CREATIONDATE DATE(7) notnull + +## GC_LAST_TURN +ID NUMBER(22) notnull PK +TYPE VARCHAR2(20) notnull +TN NUMBER(22) null +USERID VARCHAR2(20) null +UPDATE_DATE DATE(7) null +LASTTURN_DATE DATE(7) null + +## GC_QUEUE +ID NUMBER(22) notnull PK +TN VARCHAR2(15) notnull +LAST_PERMIT_DATE DATE(7) null +PREV_PERMIT_DATE DATE(7) null +HEADTYPE VARCHAR2(15) null + +## GC_TRAILERS +ID NUMBER(22) notnull PK +TRN NVARCHAR2(1500) notnull +TCSCAC NUMBER(22) notnull +STATUSCODE VARCHAR2(20) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) null +AXIALS VARCHAR2(20) null +REG_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +KINDID NUMBER(22) null +DOMAIN VARCHAR2(20) null +CHASESNUMBER VARCHAR2(40) null +CREATEUSERID VARCHAR2(20) null +OWNERNAME VARCHAR2(100) null +OWNERNNPN VARCHAR2(40) null +REVOKEDDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null +ACCEPTEDDATE DATE(7) null +ACCEPTEDBY VARCHAR2(20) null +PHONENUMBER NUMBER(22) null +TN_ID NUMBER(22) null + +## GC_TRUCKS +ID NUMBER(22) notnull PK +TN VARCHAR2(500) notnull +TCSCAC NUMBER(22) notnull +STATUSCODE VARCHAR2(20) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) null +AXIALS VARCHAR2(20) null +REG_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +KINDID NUMBER(22) null +DOMAIN VARCHAR2(20) null +CHASESNUMBER VARCHAR2(40) null +CREATEUSERID VARCHAR2(20) null +OWNERNAME VARCHAR2(100) null +OWNERNNPN VARCHAR2(40) null +COLOR VARCHAR2(20) null +MODEL VARCHAR2(20) null +MANIFACTUREYEAR NUMBER(22) null +REVOKEDDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null +ACCEPTEDDATE DATE(7) null +ACCEPTEDBY VARCHAR2(20) null +PHONENUMBER NUMBER(22) null +HEADTYPE VARCHAR2(20) null +REMARKS NVARCHAR2(1500) null + +## GN_TCS_INTEGRATION +ID NUMBER(22) notnull PK +IPADDRESS VARCHAR2(20) null +TN VARCHAR2(20) null +EVENTDATE DATE(7) null +ARGS CLOB(4000) null + +## GRAINSBLACKLIST +ID NUMBER(22) notnull PK +CATEGORY VARCHAR2(50) null +ENTITYTYPE VARCHAR2(50) null +ENTITYID NUMBER(22) null +CREATIONDATE DATE(7) notnull +CREATEDBY VARCHAR2(50) null +EXPIRYDATE DATE(7) null +STATUSCODE VARCHAR2(50) null +REMARKS VARCHAR2(500) null +LASTUPDATEUSER VARCHAR2(50) null +LASTUPDATEDATE DATE(7) null + +## GRAINSTENDERORDER +ID NUMBER(22) notnull PK +CARGOTYPE VARCHAR2(20) null +LOCATION VARCHAR2(20) null +DESTENATION VARCHAR2(20) null +ORDERDATE DATE(7) null +SHIFT VARCHAR2(20) null +QUANTITY NUMBER(22) null +STATUSCODE VARCHAR2(20) null +CREATETIMESTAMP DATE(7) null +CREATEUSERID VARCHAR2(50) null +LASTUPDATETIMESTAMP DATE(7) null +LASTUPDATEUSERID VARCHAR2(50) null +LASTPERMIT NUMBER(22) null +MOBILE_SHIFT VARCHAR2(20) null +CT VARCHAR2(20) null +TYPE VARCHAR2(20) null +MOBILE_SHOW NUMBER(22) null + +## GRAINS_BAN +ID NUMBER(22) notnull PK +TRN NUMBER(22) notnull +CREATIONDATE DATE(7) notnull +CREATEDBY NVARCHAR2(45) notnull + +## GRAINS_BILLING +ID NUMBER(22) notnull PK +SCAC NUMBER(22) null +PN NUMBER(22) null +SERIALNO NUMBER(22) null +CARGOTYPE NUMBER(22) null +TN NUMBER(22) null +ORIGIN NUMBER(22) null +LOADDATE DATE(7) null +LTW NUMBER(22) null +LGW NUMBER(22) null +LNW NUMBER(22) null +DESTINATION NUMBER(22) null +DISCHARGEDATE DATE(7) null +DTW NUMBER(22) null +DGW NUMBER(22) null +DNW NUMBER(22) null +PRICE NUMBER(22) null +FINEPRICE NUMBER(22) null +LOSEFINE NUMBER(22) null +FINALCOST NUMBER(22) null +INVOICENUMBER NUMBER(22) null +COMPANYNAME VARCHAR2(200) null +CREATEUSERID NVARCHAR2(150) null +CREATETIMESTAMP DATE(7) null +STATUSCODE VARCHAR2(10) null +DEMURRAGEFINE NUMBER(22) null +OTHERFINE NUMBER(22) null +REROUTEPRICE NUMBER(22) null +REROUTENAME NVARCHAR2(150) null + +## GRAINS_COMPANIES_LOCATION +ID NUMBER(22) notnull PK +SCAC NUMBER(22) notnull +LOCATIONID NUMBER(22) notnull + +## GRAINS_COMPANIES_QUEUE +ID NUMBER(22) notnull PK +SCAC NUMBER(22) notnull +COUNTER NUMBER(22) notnull +CODE VARCHAR2(15) notnull +TYPE VARCHAR2(15) notnull + +## GRAINS_COMPANIES_QUEUE_BACKUP +ID NUMBER(22) null +SCAC NUMBER(22) null +COUNTER NUMBER(22) null +CODE VARCHAR2(10) null +TYPE VARCHAR2(15) notnull + +## GRAINS_EXCEPTION +ID NUMBER(22) notnull PK +TRN NUMBER(22) notnull +CREATIONDATE DATE(7) notnull +CREATEDBY NVARCHAR2(45) notnull + +## GRAINS_FILES +ID NUMBER(22) notnull PK +ENTITYID NUMBER(22) null +ORIGINALNAME VARCHAR2(100) null +FILENAME VARCHAR2(100) null +ATTACHMENTTYPE VARCHAR2(20) null +CREATIONDATE DATE(7) null +ENTITYID_BACKUP NUMBER(22) null + +## GRAINS_FINE +ID NUMBER(22) null +CARGOTYPE NUMBER(22) null +ALLOWANCE NUMBER(22) null +FINE NUMBER(22) null +STARTDATE DATE(7) null +ENDDATE DATE(7) null + +## GRAINS_PERMITS_WEIGHTS +ID NUMBER(22) null +EMPTY_WEIGHT NUMBER(22) null +GROSS_WEIGHT NUMBER(22) null +DOCUMENT_NUMBER NUMBER(22) null +PERMIT_ID NUMBER(22) null +CREATION_DATE DATE(7) null +CREATED_BY VARCHAR2(50) null +UPDATE_DATE DATE(7) null +UPDATE_BY VARCHAR2(50) null + +## GRAINS_TEMP +ID NUMBER(22) null +LOCATIONID NUMBER(22) null +WAGE NUMBER(22) null +STARTDATE DATE(7) null +ENDDATE DATE(7) null + +## GRAINS_TRUCKS_VALIDATION +ID NUMBER(22) notnull PK +SCAC NUMBER(22) null +TN NUMBER(22) null +STATUS NUMBER(22) notnull +CREATEDBY NVARCHAR2(300) null +CREATIONDATE DATE(7) notnull +UPDATEDBY NVARCHAR2(300) null +UPDATEDTIMESTAMP DATE(7) null + +## GRAINS_WAGE +ID NUMBER(22) null +LOCATIONID NUMBER(22) null +WAGE NUMBER(22) null +STARTDATE DATE(7) null +ENDDATE DATE(7) null + +## GRAINS_WEIGHBRIDG_CONTROL +ID NUMBER(22) notnull PK +NTP_TRUCKID NUMBER(22) null +LOCATIONID NUMBER(22) null +DOMAIN NVARCHAR2(90) null +NOTES NVARCHAR2(600) null +CREATEDBY NVARCHAR2(150) null +CREATIONDATE DATE(7) null +EXPIEYDATE DATE(7) null + +## HOURSDIMENTION +D DATE(7) null + +## INVALID_ACCESS_LOG +ID NUMBER(22) notnull PK +USER_ID NUMBER(22) notnull +CREATION_DATE DATE(7) notnull +USER_LOCATION_ID NUMBER(22) notnull +ROLE_CODE VARCHAR2(15) null +USER_IP_ADDRESS VARCHAR2(50) null +CURRENT_IP_ADDRESS VARCHAR2(50) notnull +CURRENT_LOCATION_ID NUMBER(22) null +BROWSER VARCHAR2(300) null +REASON_ID NUMBER(22) null +SOURCE_APP VARCHAR2(5) null + +## INVALID_ACCESS_REASONS +ID NUMBER(22) notnull PK +REASON VARCHAR2(100) null + +## INVOICE +ID NUMBER(22) notnull PK +INVOICENUMBER NUMBER(22) null +SCAC NUMBER(22) null +STATUSCODE VARCHAR2(10) null +INVOICEDATE DATE(7) null +DOMAIN VARCHAR2(50) null +INVOICE_END_DATE DATE(7) null + +## INVOICE_DETAILS +ID NUMBER(22) notnull PK +PN NUMBER(22) null +SHIPMENTMODE VARCHAR2(50) null +TN VARCHAR2(20) null +DRVR NVARCHAR2(300) null +SHIPMENTSTATUSCODE VARCHAR2(20) null +CID VARCHAR2(20) null +PERMIT_CREATION_DATE DATE(7) null +CREATEDBY VARCHAR2(100) null +GC_PN NUMBER(22) null +FUEL_PN NUMBER(22) null +INVOICE_NUMBER VARCHAR2(12) null +RCID VARCHAR2(20) null +SERVICE_CODE VARCHAR2(20) null +COMPANY_DESCRIPTION VARCHAR2(50) null +COMPANY_NAME NVARCHAR2(750) null +SCAC NUMBER(22) null +CA_NAME NVARCHAR2(750) null + +## INVOICE_INFO +ID NUMBER(22) notnull PK +INVOICENUMBER NUMBER(22) null +SERVICECODE NVARCHAR2(30) null +PERMITID NUMBER(22) null +WAYBILLID NUMBER(22) null +INVOICEDATE DATE(7) null +CREATIONDATE DATE(7) null +NOTES NVARCHAR2(1500) null +CREATEDBY NVARCHAR2(150) null +FEES NUMBER(22) null +SHIPMENTMODE NVARCHAR2(30) null +SCAC NUMBER(22) null + +## INVOICE_SUMMARY +ID NUMBER(22) notnull +INVOICE_DATE DATE(7) notnull +COMPANY_CODE VARCHAR2(10) notnull +COMPANY_NAME NVARCHAR2(300) notnull +INVOICE_NUMBER VARCHAR2(12) notnull +SERVICE_CODE VARCHAR2(10) notnull +SERVICE_NAME NVARCHAR2(150) notnull +DESCRIPTION NVARCHAR2(150) notnull +NUMBER_OF_PERMITS NUMBER(22) notnull +SERVICE_FEE NUMBER(22) notnull +SERVICE_TOTAL NUMBER(22) notnull +QR_CODE VARCHAR2(100) null + +## ISO_TYPES +ISO_TYPE VARCHAR2(10) notnull PK +DESCREPTION VARCHAR2(500) null +ISREFER NUMBER(22) null +ISFLAT NUMBER(22) null +CONTSIZE NUMBER(22) null + +## IVR_LOG +ID NUMBER(22) notnull PK +PN NUMBER(22) null +PHONE NUMBER(22) null +STATUS VARCHAR2(30) null +ORDERID NUMBER(22) null +CREATEDATE DATE(7) null +RESPONSE CLOB(4000) null + +## JCDCITY +CODE VARCHAR2(3) notnull PK +NAME NVARCHAR2(300) null + +## JCDLOCATION +CODE VARCHAR2(3) notnull PK +LOCATION NVARCHAR2(300) null + +## JOPETROL_INTEGRATION_1 +NF55DOCO NVARCHAR2(36) null +NFTRDJ NVARCHAR2(30) null +NFLALT NVARCHAR2(30) null +NFLDNM NVARCHAR2(150) null +NFMCU NVARCHAR2(150) null +NFAN8 NVARCHAR2(30) null +NF55TRAIL NVARCHAR2(30) null +NF55HEAD NVARCHAR2(30) null +NF55DRNID NVARCHAR2(36) null +NFAN55DR NVARCHAR2(150) null +NFLITM NVARCHAR2(150) null +NF55NITM NVARCHAR2(30) null +NFBFWT NVARCHAR2(150) null +NFAFWT NVARCHAR2(150) null +NFWGTR NVARCHAR2(150) null +NFAMBR NVARCHAR2(150) null +NFSTUM NVARCHAR2(150) null +NFDNTY NVARCHAR2(150) null +NFTEMP NVARCHAR2(150) null +NFEV01 NVARCHAR2(150) null +NF55STATUS NVARCHAR2(30) null +NFUSER NVARCHAR2(150) null +NFUPMJ NVARCHAR2(150) null +NFTDAY NVARCHAR2(36) null +NFPID NVARCHAR2(36) null +NFJOBN NVARCHAR2(36) null + +## JOPETROL_INTEGRATION_2 +ID NUMBER(22) notnull PK +UPLOADDATE DATE(7) null +ORIGINALNAME NVARCHAR2(300) null +FILENAME NVARCHAR2(300) null +TYPE NUMBER(22) null +FAILEDNO VARCHAR2(1000) null +DONEBY VARCHAR2(12) null + +## KIOSKS_BL +ID NUMBER(22) null +TYPECODE NVARCHAR2(15) null +VALUE NVARCHAR2(3000) null +TYPEID NUMBER(22) null +REMARKS NVARCHAR2(3000) null +SEVERITY NVARCHAR2(15) null +STATUS VARCHAR2(10) notnull +CREATEUSERID VARCHAR2(15) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(20) null +LASTUPDATETIMESTAMP DATE(7) null +DOMAINNAME VARCHAR2(50) notnull +DURATION NUMBER(22) null +ACTIVATION_TRIGGER VARCHAR2(50) null +EXPIRYDATE DATE(7) null +ACTIVATEDBY VARCHAR2(20) null +ACTIVATIONDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null +REVOKEDATE DATE(7) null +MANUALKIOSKID NUMBER(22) null +TAGGING_BL_TYPE VARCHAR2(50) null +YARDNUMBER NUMBER(22) null +PERMIT_ID NUMBER(22) null +BL_DANGER NUMBER(22) null +BL_CATEGORY VARCHAR2(25) null +CID VARCHAR2(30) null +RUN_OVER_LOCATION NUMBER(22) null + +## LANES +CODE NVARCHAR2(60) notnull PK +CAPTION NVARCHAR2(300) null +DISPORDER NUMBER(22) null +DOMAIN VARCHAR2(5) notnull PK + +## LOCATIONGROUPS +ID NUMBER(22) notnull PK +LOCATIONID NUMBER(22) null +GROUPID NUMBER(22) null +DOMAIN VARCHAR2(10) null + +## LOCATIONS +ID NUMBER(22) notnull PK +NAME NVARCHAR2(900) null +TYPE VARCHAR2(3) null +DOMAIN VARCHAR2(5) notnull PK +CREATEDBY NVARCHAR2(150) null +CREATEDATE DATE(7) null +UPDATEDBY NVARCHAR2(150) null +LASTUPDATEDATE DATE(7) null +STATUS NUMBER(22) null +CAPACITY NUMBER(22) null +AREA NVARCHAR2(150) null +SHORTNAME NVARCHAR2(150) null +YARDNO NUMBER(22) null +LOCATIONSGROUP NVARCHAR2(210) null +GN_TYPE VARCHAR2(50) null +SORTORDER NUMBER(22) null + +## LOCATIONSERVICES +ID NUMBER(22) notnull +LOCATIONID NUMBER(22) null +DOMAIN VARCHAR2(50) null +SERVICECODE VARCHAR2(50) null +CTID VARCHAR2(500) null +ROLE VARCHAR2(50) null + +## LOCATIONS_IPS +ID NUMBER(22) notnull PK +LOCATION_ID NUMBER(22) notnull +MAC_ADDRESS VARCHAR2(70) null +CREATION_DATE DATE(7) notnull +LAST_UPDATE_DATE DATE(7) null +IP_ADDRESS VARCHAR2(70) null + +## LOG_ACT_CONTAINER_EXPORT +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_CARGORELEASES +ID NUMBER(22) notnull +ENTITIY_ID NUMBER(22) notnull +METHOD_NAME VARCHAR2(100) notnull +LOG_DATE DATE(7) notnull +USER_ID VARCHAR2(100) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_CTL_ORDERS +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) notnull +METHOD_NAME VARCHAR2(100) notnull +LOG_DATE DATE(7) notnull +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_CUSTOMS_EXPORT +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_FLEET_DISTRIBUTION +ID NUMBER(22) notnull +ENTITIY_ID NUMBER(22) notnull +METHOD_NAME VARCHAR2(100) notnull +LOG_DATE DATE(7) notnull +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_FLEET_ORDER +ID NUMBER(22) notnull +ENTITIY_ID NUMBER(22) notnull +METHOD_NAME VARCHAR2(100) notnull +LOG_DATE DATE(7) notnull +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_FLEET_QUEUE +ID NUMBER(22) notnull +ENTITIY_ID NUMBER(22) notnull +METHOD_NAME VARCHAR2(100) notnull +LOG_DATE DATE(7) notnull +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_LOCATIONS +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_PERMITLANES +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_PERMITS +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +USER_ID VARCHAR2(100) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null +LOCATION_ID NUMBER(22) null + +## LOG_PERMITS_RECEIPTS +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) notnull +METHOD_NAME VARCHAR2(100) notnull +LOG_DATE DATE(7) notnull +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null +FILE_NAME VARCHAR2(250) null + +## LOG_PERMIT_REQUEST +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(30) null +LOG_DATE DATE(7) null +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LOG_WASHINGQUEUE +ID NUMBER(22) notnull +ENTITIY_ID NUMBER(22) notnull +METHOD_NAME VARCHAR2(100) notnull +LOG_DATE DATE(7) notnull +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LTRC_CARS +CAR_NUMBER NUMBER(22) notnull PK +CAR_TYPE NUMBER(22) notnull +CATEGORY_USAGE NUMBER(22) null +END_LICENCES_DATE NUMBER(22) null +ACTIVITY_ID NUMBER(22) notnull +OWNER NUMBER(22) notnull +OWNER_NATIONAL_NUMBER NUMBER(22) null +OWNER_NAME NVARCHAR2(600) null +OWNER_PHONE_NUMBER NUMBER(22) null +CAR_UNION VARCHAR2(100) null + +## LTRC_COMPANY +COMPANY_NUMBER NUMBER(22) notnull PK +COMPANY_NAME NVARCHAR2(450) notnull +EXPIRATION_LICENCES_DATE NUMBER(22) notnull +STATUS_ID NUMBER(22) null +CREATION_DATE DATE(7) notnull +UPDATE_DATE DATE(7) null + +## LTRC_COMPANY_ACTIVITY +ID NUMBER(22) notnull PK +COMPANY_NUMBER NUMBER(22) notnull +ACTIVITY_ID NUMBER(22) notnull +CREATION_DATE DATE(7) notnull +UPDATE_DATE DATE(7) null +STATUS NUMBER(22) notnull + +## LTRC_COMPANY_ACTIVITY_TEMP +ID NUMBER(22) notnull PK +COMPANY_NUMBER NUMBER(22) notnull +ACTIVITY_ID NUMBER(22) notnull +CREATION_DATE DATE(7) notnull +UPDATE_DATE DATE(7) null +STATUS NUMBER(22) notnull + +## LTRC_DRIVERS +NAME NVARCHAR2(600) null +DRIVER_MOBILE VARCHAR2(30) null +NATIONALITY_NUMBER NUMBER(22) notnull PK +LICENSE_CATEGORY NUMBER(22) null + +## LTRC_MAPPING +CODE NUMBER(22) notnull PK +NAME NVARCHAR2(450) notnull +MAPPING VARCHAR2(30) notnull PK + +## LT_SHIPPING_LINES +CODE VARCHAR2(5) notnull +SHIPPING_LINE VARCHAR2(5) notnull + +## LT_YARD4_STATISTICS +TYPE VARCHAR2(25) null + +## MAIN_YARD_ORDERS +ID NUMBER(22) notnull PK +QUANTITY NUMBER(22) null +CRN VARCHAR2(50) null +STATUSCODE VARCHAR2(50) null +REMARKS NVARCHAR2(1500) null +CREATEDBY NVARCHAR2(150) null +CREATIONTIMESTAMP DATE(7) null +WFID NUMBER(22) null + +## MAIN_YARD_ORDERS_FILES +ID NUMBER(22) notnull PK +ORDERID NUMBER(22) null +ORIGINALNAME NVARCHAR2(150) null +FILENAME NVARCHAR2(150) null + +## MANUALKIOSKSLOG +ID NUMBER(22) notnull PK +TN VARCHAR2(50) null +NOTES VARCHAR2(500) notnull +KIOSKID NUMBER(22) notnull +CREATIONDATE DATE(7) notnull +PERMITID NUMBER(22) null +USERID VARCHAR2(100) null +EVENTID NUMBER(22) null +BLACKLISTID NUMBER(22) null +KIOSK_READING_TYPE VARCHAR2(30) null +TAGID VARCHAR2(100) null + +## MANUAL_DESTINATIONS +ID NUMBER(22) notnull PK +TN NVARCHAR2(60) null +DESTINATIONID NUMBER(22) null +CREATION_DATE DATE(7) null +STATUS_CODE NVARCHAR2(30) null +USER_ID NVARCHAR2(60) null + +## MINORCODEISOCODE +ID NUMBER(22) notnull PK +MINORCODE VARCHAR2(20) notnull +ISOCODE VARCHAR2(20) notnull +ISACTIVE NUMBER(22) notnull +CREATIONDATE DATE(7) null +LASTUPDATEDATE DATE(7) null + +## MOBILE_ATTACHEMNT +ID NUMBER(22) notnull PK +PID NUMBER(22) null +FILENAME VARCHAR2(50) null +MODULENAME VARCHAR2(50) null +USERID VARCHAR2(50) null +CREATETIMESTAMP DATE(7) null +DOMAIN VARCHAR2(10) null + +## MOTREGTYPE +ID NUMBER(22) notnull PK +NAME NVARCHAR2(300) null + +## MOTTRUCKTYPE +ID NUMBER(22) notnull PK +CODE VARCHAR2(100) null +NAME NVARCHAR2(300) null + +## MOT_ENTITYSPECS +ID NUMBER(22) notnull PK +TNID NUMBER(22) null +TRNID NUMBER(22) null +SPECID NUMBER(22) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +TEMPUPDATEDATE DATE(7) null + +## MOT_ENTITYSPECS_TMP +ID NUMBER(22) notnull +TNID NUMBER(22) null +TRNID NUMBER(22) null +SPECID NUMBER(22) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +TEMPUPDATEDATE DATE(7) null + +## MOT_EXCEPTIONS +ID NUMBER(22) notnull +TN VARCHAR2(20) null +TT VARCHAR2(50) notnull +TCSSCAC NUMBER(10,0) null +PN VARCHAR2(50) null +REASON VARCHAR2(1000) notnull +STATUS VARCHAR2(10) null +EXPCDATE DATE(7) notnull +CREATEUSERID VARCHAR2(15) notnull +EXPIRYDATE DATE(7) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null +DOMAINNAME VARCHAR2(50) notnull +ISACTIVE NUMBER(1,0) null +OWNER VARCHAR2(20) notnull +CID VARCHAR2(20) null + +## MOT_TN_ABROAD_TRIPS +ID NUMBER(22) notnull PK +TN NUMBER(22) notnull +NUMBER_OF_TRIPS NUMBER(22) notnull +LAST_TRIP_DATE DATE(7) null +CREATION_DATE DATE(7) notnull +UPDATE_DATE DATE(7) null +TRN NUMBER(22) null + +## MOT_TRAILERS +ID NUMBER(22) notnull PK +TRN VARCHAR2(20) notnull +TCSCAC VARCHAR2(5) notnull +OWNERSHIPCODE VARCHAR2(10) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +AXIS_NUM NUMBER(22) null +LICENSE_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +EMPTYWGHT NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(10) null +OWNERID NUMBER(22) null +KINDID NUMBER(22) null +SIXMHEAVYLOAD NUMBER(22) null +CONTRACTEXPIRYDATE DATE(7) null +MINORCODE NUMBER(22) null +DOC_STATUS NUMBER(22) null +DOC_NUMBER NUMBER(22) null + +## MOT_TRAILERS_FILES +ID NUMBER(22) notnull PK +TRAILERID NUMBER(22) null +ORIGINALNAME VARCHAR2(100) null +FILENAME VARCHAR2(100) null + +## MOT_TRAILERS_TMP +ID NUMBER(22) notnull +TRN VARCHAR2(20) notnull +TCSCAC VARCHAR2(5) notnull +OWNERSHIPCODE VARCHAR2(10) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +AXIS_NUM NUMBER(22) null +LICENSE_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +EMPTYWGHT NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(10) null +OWNERID NUMBER(22) null +KINDID NUMBER(22) null +SIXMHEAVYLOAD NUMBER(22) null +CONTRACTEXPIRYDATE DATE(7) null +MINORCODE NUMBER(22) null +DOC_STATUS NUMBER(22) null +DOC_NUMBER NUMBER(22) null + +## MOT_TRUCKS +ID NUMBER(22) notnull PK +TN NUMBER(22) notnull +TCSCAC NUMBER(22) notnull +OWNERSHIPCODE NUMBER(22) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +AXIS_NUM NUMBER(22) null +LICENSE_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +OWNERID NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +KINDID NUMBER(22) null +EMPTYWGHT NUMBER(22) null +CONTRACTEXPIRYDATE DATE(7) null +COMPLETIONDATE DATE(7) null +COMPLETIONUSERID VARCHAR2(20) null +TRACKNO NUMBER(22) null +MINORCODE NUMBER(22) null +NNPN VARCHAR2(20) null +DRVR NVARCHAR2(150) null +DRIVERNAT NUMBER(22) null +PROCESS NUMBER(22) null +DOC_STATUS NUMBER(22) null +DOC_NUMBER NUMBER(22) null +EXCEPTION NUMBER(22) null +EXCEPTION_REASON NVARCHAR2(600) null +TN_TYPE NUMBER(22) null +NUMOFENTRYPERMITS NUMBER(22) null +LASTPERMITDATE DATE(7) null +NUMOFENTRYPERMITS_TRN NUMBER(22) null + +## MOT_TRUCKS_FILES +ID NUMBER(22) notnull PK +TRUCKID NUMBER(22) null +ORIGINALNAME VARCHAR2(100) null +FILENAME VARCHAR2(100) null +ATTACHMENTTYPE VARCHAR2(20) null +CREATIONDATE DATE(7) null + +## MOT_TRUCKS_TMP +ID NUMBER(22) notnull +TN NUMBER(22) notnull +TCSCAC NUMBER(22) notnull +OWNERSHIPCODE NUMBER(22) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +AXIS_NUM NUMBER(22) null +LICENSE_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +OWNERID NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +KINDID NUMBER(22) null +EMPTYWGHT NUMBER(22) null +CONTRACTEXPIRYDATE DATE(7) null +COMPLETIONDATE DATE(7) null +COMPLETIONUSERID VARCHAR2(20) null +TRACKNO NUMBER(22) null +MINORCODE NUMBER(22) null +NNPN VARCHAR2(20) null +DRVR NVARCHAR2(150) null +DRIVERNAT NUMBER(22) null +PROCESS NUMBER(22) null +DOC_STATUS NUMBER(22) null +DOC_NUMBER NUMBER(22) null +EXCEPTION NUMBER(22) null +EXCEPTION_REASON NVARCHAR2(600) null +TN_TYPE NUMBER(22) null + +## NEW_PORT_EVENT_INTEGRATION_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +LOCATION VARCHAR2(50) notnull +LOCATION_TYPE VARCHAR2(50) notnull +EVENT_DATE VARCHAR2(50) notnull +PN VARCHAR2(50) notnull +OPERATION_TYPE VARCHAR2(50) notnull +WEIGHT_IN NUMBER(22) notnull +WEIGHT_OUT NUMBER(22) notnull +EXIT_PERMIT NUMBER(22) notnull +CPM NUMBER(22) notnull +REQUEST_DATA CLOB(4000) notnull +RESPONSE_DATA CLOB(4000) notnull +STATUS_CODE VARCHAR2(50) null +PERMIT_ID NUMBER(22) notnull + +## NTP_COMPANY_DISTINATION +ID NUMBER(22) notnull PK +TN NUMBER(22) notnull +STATUSCODE VARCHAR2(20) null +DESTINATION VARCHAR2(2000) null +CREATEUSERID VARCHAR2(20) null +CREATETIMESTAMP DATE(7) null +LASTUPDATEUSERID VARCHAR2(20) null +LASTUPDATETIMESTAMP DATE(7) null +DOMAIN VARCHAR2(20) null +FROMMOBILE NUMBER(22) null + +## NTP_DRIVERS +ID NUMBER(22) notnull PK +NNPN NVARCHAR2(1500) null +NAME VARCHAR2(500) null +DLN NUMBER(22) null +DLED DATE(7) null +TCSCAC NUMBER(22) null +STATUSCODE VARCHAR2(20) null +CREATETIMESTAMP DATE(7) null +LASTUPDATETIMESTAMP DATE(7) null +DOMAIN VARCHAR2(20) null +CREATEUSERID VARCHAR2(100) null +LASTUPDATEUSERID VARCHAR2(100) null +NAT VARCHAR2(20) null +CAT NUMBER(22) null +MOBILE1 NUMBER(22) null +MOBILE2 NUMBER(22) null +REVOKEDDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null +ACCEPTEDDATE DATE(7) null +ACCEPTEDBY VARCHAR2(20) null + +## NTP_ENTITYSPECS +ID NUMBER(22) notnull PK +TNID NUMBER(22) null +TRNID NUMBER(22) null +SPECID NUMBER(22) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +TEMPUPDATEDATE DATE(7) null + +## NTP_TENDER +ID NUMBER(22) notnull PK +STATUS VARCHAR2(20) null +STARTDATE DATE(7) null +EXPIRYDATE DATE(7) null +DOMAIN VARCHAR2(10) null + +## NTP_TENDERS_COMPANIES +ID NUMBER(22) notnull PK +TENDERID NUMBER(22) null +SCAC NUMBER(22) null +STATUSCODE VARCHAR2(10) null +COMPANYSHARE NUMBER(22) null +VALIDATIONTYPE VARCHAR2(100) null +NAME NVARCHAR2(600) null +GALLAB NUMBER(22) null + +## NTP_TRAILERS +ID NUMBER(22) notnull PK +TN NVARCHAR2(1500) null +TCSCAC NUMBER(22) null +STATUSCODE VARCHAR2(20) null +CREATETIMESTAMP DATE(7) null +LASTUPDATETIMESTAMP DATE(7) null +AXIALS VARCHAR2(20) null +REG_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +KINDID NUMBER(22) null +DOMAIN VARCHAR2(20) null +CHASESNUMBER VARCHAR2(40) null +CREATEUSERID VARCHAR2(20) null +OWNERNAME VARCHAR2(200) null +OWNERNNPN VARCHAR2(40) null +REVOKEDDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null +ACCEPTEDDATE DATE(7) null +ACCEPTEDBY VARCHAR2(20) null +PHONENUMBER NUMBER(22) null +TN_ID NUMBER(22) null + +## NTP_TRUCKS +ID NUMBER(22) notnull PK +TN VARCHAR2(500) null +TCSCAC NUMBER(22) null +STATUSCODE VARCHAR2(20) null +CREATETIMESTAMP DATE(7) null +LASTUPDATETIMESTAMP DATE(7) null +AXIALS VARCHAR2(20) null +REG_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +KINDID NUMBER(22) null +DOMAIN VARCHAR2(20) null +CHASESNUMBER VARCHAR2(40) null +CREATEUSERID VARCHAR2(20) null +OWNERNAME VARCHAR2(200) null +OWNERNNPN VARCHAR2(40) null +COLOR VARCHAR2(20) null +MODEL VARCHAR2(20) null +MANIFACTUREYEAR NUMBER(22) null +REVOKEDDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null +ACCEPTEDDATE DATE(7) null +ACCEPTEDBY VARCHAR2(20) null +PHONENUMBER NUMBER(22) null +HEADTYPE VARCHAR2(20) null + +## NTP_TRUCKS_COMPANIES_MAPPING +ID NUMBER(22) notnull PK +ENTITYTYPE VARCHAR2(20) notnull +ENTITYID NUMBER(22) notnull +TCSCAC NUMBER(22) notnull +CREATIONDATE DATE(7) notnull +STATUSCODE VARCHAR2(20) notnull +CREATEDBY VARCHAR2(20) notnull +REVOKEDDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null + +## OPERATIONTYPE +CODE NVARCHAR2(30) notnull PK +CAPTION NVARCHAR2(300) null +DOMAIN VARCHAR2(5) notnull PK +CATEGORY NVARCHAR2(30) null + +## ORDERS +ID NUMBER(22) notnull PK +ORDERTYPE VARCHAR2(50) notnull +YARDNUMBER NUMBER(22) notnull +LOCATIONID NUMBER(22) notnull +CATEGORYTYPE VARCHAR2(20) notnull +CATEGORYVALUE VARCHAR2(20) null +STATUSCODE VARCHAR2(20) notnull +COUNT NUMBER(22) notnull +USED NUMBER(22) null +CREATIONDATE DATE(7) null +CREATEDBY VARCHAR2(20) notnull +LASTUPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(20) null +ACHIVED NUMBER(22) null +AUTOMATIC_ORDER NUMBER(22) null +CARGOTYPE VARCHAR2(20) null +ORDERNUMBER NUMBER(22) null + +## OVERNIGHT_TRUCKS +ID NUMBER(22) notnull PK +TN NVARCHAR2(150) null +STATUS_CODE VARCHAR2(20) null +CREATION_DATE DATE(7) null + +## OWNERS +ID NUMBER(22) notnull PK +NATIONALNUMBER NUMBER(22) null +NAME NVARCHAR2(300) null +PHONE VARCHAR2(10) null +CREATETIMESTAMP DATE(7) null +CREATEUSERID VARCHAR2(15) null +ADDRESSID NUMBER(22) null +CONTRACTDATE DATE(7) null +PHONE2 VARCHAR2(10) null +NAMEINENGLISH VARCHAR2(100) null +CIVILID NUMBER(22) null +CIVILIDEXPIRYDATE DATE(7) null +DRIVELICENSENUM NUMBER(22) null +DRIVELICENSEEXPIRYDATE DATE(7) null +OWNERBIRTHDAY DATE(7) null +OWNERPLACEOFBIRTHID NUMBER(22) null +OWNERSEX VARCHAR2(1) null +OWNERNAT VARCHAR2(20) null +DRIVELICENSECAT NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +LASTUPDATETIMESTAMP DATE(7) null +ACCOUNTNUMBER NUMBER(22) null + +## PERFORMANCESTATS +METHODNAME VARCHAR2(100) null +ELAPSEDTIME NUMBER(22) null +ARGS NVARCHAR2(3000) null +EXCUTION_TS DATE(7) null +USERID VARCHAR2(100) null + +## PERMITLANES +ID NUMBER(22) notnull +NAME NVARCHAR2(900) null +CAPACITY NUMBER(22) null +STATUS VARCHAR2(50) null +DOMAIN VARCHAR2(50) null +CREATEDBY VARCHAR2(50) null +CREATIONDATE DATE(7) null +UPDATEDBY VARCHAR2(50) null +LASTUPDATEDATE DATE(7) null + +## PERMITLANESATTRIBUTES +ID NUMBER(22) notnull +LANEID NUMBER(22) null +CT VARCHAR2(50) null +FMCT VARCHAR2(50) null +ORGADDRESS VARCHAR2(50) null +STATUS VARCHAR2(50) null +DOMAIN VARCHAR2(50) null +CREATEDBY VARCHAR2(50) notnull +CREATIONDATE DATE(7) notnull +UPDATEDBY VARCHAR2(50) null +LASTUPDATEDATE DATE(7) null + +## PERMITROUTES +ID NUMBER(22) notnull PK +PERMITID NUMBER(22) null +ORGID NUMBER(22) null +DESTID NUMBER(22) null +SORTORDER NUMBER(22) null +ORGDEPARTDATE DATE(7) null +DESTARRIVEDATE DATE(7) null +DESTDEPARTDATE DATE(7) null +STATUS VARCHAR2(50) null +DOMAIN VARCHAR2(50) null +PARENTLOCATIONID NUMBER(22) null +ETA DATE(7) null + +## PERMITS +ID NUMBER(22) notnull PK +SHIPMENTMODE NVARCHAR2(30) null +INBONDTYPECODE NVARCHAR2(30) null +FIRMS NVARCHAR2(60) null +ORIGINADDRESSID NUMBER(22) null +DESTINATIONADDRESSID NUMBER(22) null +TN NVARCHAR2(1500) null +TRNAT NVARCHAR2(1500) null +TRN NVARCHAR2(1500) null +TT NVARCHAR2(1500) null +ASRN NVARCHAR2(1500) null +CRN NVARCHAR2(1500) null +CAN NUMBER(22) null +CID NVARCHAR2(1500) null +WBL NUMBER(22) null +SCRN NVARCHAR2(1500) null +CAN2 NUMBER(22) null +CID2 NVARCHAR2(1500) null +WBL2 NUMBER(22) null +DRVR NVARCHAR2(1500) null +CAT NVARCHAR2(1500) null +DLN NVARCHAR2(1500) null +DLED VARCHAR2(500) null +NAT NVARCHAR2(1500) null +NNPN NVARCHAR2(1500) null +DRVRMOBILE NVARCHAR2(1500) null +ROUTINGTEMPLATEID NUMBER(22) null +SHIPMENTSTATUSCODE VARCHAR2(10) null +PN NUMBER(22) null +COMPANYCODE NUMBER(22) null +CREATEDBY NVARCHAR2(150) null +CREATIONDATE DATE(7) null +UPDATEDBY NVARCHAR2(150) null +LASTUPDATEDATE DATE(7) null +ISACTIVE VARCHAR2(1) null +RECORDDATE DATE(7) null +DOMAIN VARCHAR2(10) null +WEIGHT NUMBER(22) null +HEADREGTYPE NUMBER(22) null +TRAILREGTYPE NUMBER(22) null +UPDATEDTYPE NVARCHAR2(150) null +TRACKINGNO NUMBER(22) null +ALLOWEDWGHT NUMBER(22) null +LASTPERMITDATE DATE(7) null +TRIPCOUNTER NUMBER(22) null +FMORIGINADDRESSID NUMBER(22) null +FMDESTINATIONADDRESSID NUMBER(22) null +FMFIRMS NVARCHAR2(60) null +FMROUTINGTEMPLATEID NUMBER(22) null +FMSHIPMENTMODE NVARCHAR2(30) null +FMINBONDTYPECODE NVARCHAR2(30) null +FMSHIPMENTSTATUSCODE VARCHAR2(10) null +NOTES NVARCHAR2(1500) null +WAYBILLID NUMBER(22) null +OWNER_NAME VARCHAR2(200) null +RCID VARCHAR2(15) null +RCID2 VARCHAR2(15) null +CURRENTLEG NUMBER(22) null +DRVR_IDX NVARCHAR2(1500) null +CURRENT_LEG_DATE_TIME DATE(7) null +WAITING_ORDERID NUMBER(22) null +PLND_ORDERID NUMBER(22) null +USER_NOTES VARCHAR2(500) null + +## PERMITSRELATION +ID NUMBER(22) notnull PK +PARENTPERMITID NUMBER(22) null +PERMITID NUMBER(22) null +ISACTIVE NUMBER(22) null + +## PERMITSS +ID NUMBER(22) null + +## PERMITS_BEFORE +ID NUMBER(22) notnull +SHIPMENTMODE NVARCHAR2(30) null +INBONDTYPECODE NVARCHAR2(30) null +FIRMS NVARCHAR2(60) null +ORIGINADDRESSID NUMBER(22) null +DESTINATIONADDRESSID NUMBER(22) null +TN NVARCHAR2(1500) null +TRNAT NVARCHAR2(1500) null +TRN NVARCHAR2(1500) null +TT NVARCHAR2(1500) null +ASRN NVARCHAR2(1500) null +CRN NVARCHAR2(1500) null +CAN NUMBER(22) null +CID NVARCHAR2(1500) null +WBL NUMBER(22) null +SCRN NVARCHAR2(1500) null +CAN2 NUMBER(22) null +CID2 NVARCHAR2(1500) null +WBL2 NUMBER(22) null +DRVR NVARCHAR2(1500) null +CAT NVARCHAR2(1500) null +DLN NVARCHAR2(1500) null +DLED VARCHAR2(500) null +NAT NVARCHAR2(1500) null +NNPN NVARCHAR2(1500) null +DRVRMOBILE NVARCHAR2(1500) null +ROUTINGTEMPLATEID NUMBER(22) null +SHIPMENTSTATUSCODE VARCHAR2(10) null +PN NUMBER(22) null +COMPANYCODE NUMBER(22) null +CREATEDBY NVARCHAR2(150) null +CREATIONDATE DATE(7) null +UPDATEDBY NVARCHAR2(150) null +LASTUPDATEDATE DATE(7) null +ISACTIVE VARCHAR2(1) null +RECORDDATE DATE(7) null +DOMAIN VARCHAR2(10) null +WEIGHT NUMBER(22) null +HEADREGTYPE NUMBER(22) null +TRAILREGTYPE NUMBER(22) null +UPDATEDTYPE NVARCHAR2(150) null +TRACKINGNO NUMBER(22) null +ALLOWEDWGHT NUMBER(22) null +LASTPERMITDATE DATE(7) null +TRIPCOUNTER NUMBER(22) null +FMORIGINADDRESSID NUMBER(22) null +FMDESTINATIONADDRESSID NUMBER(22) null +FMFIRMS NVARCHAR2(60) null +FMROUTINGTEMPLATEID NUMBER(22) null +FMSHIPMENTMODE NVARCHAR2(30) null +FMINBONDTYPECODE NVARCHAR2(30) null +FMSHIPMENTSTATUSCODE VARCHAR2(10) null +NOTES NVARCHAR2(1500) null +WAYBILLID NUMBER(22) null +OWNER_NAME VARCHAR2(100) null +RCID VARCHAR2(15) null +RCID2 VARCHAR2(15) null +CURRENTLEG NUMBER(22) null +DRVR_IDX NVARCHAR2(1500) null +UDATEDATE DATE(7) notnull + +## PERMITS_INVOICES +ID NUMBER(22) notnull PK +INVOICENUMBER NUMBER(22) null +SERVICECODE NVARCHAR2(30) null +PERMITID NUMBER(22) null +WAYBILLID NUMBER(22) null +INVOICEDATE DATE(7) null +CREATIONDATE DATE(7) null +NOTES NVARCHAR2(1500) null +CREATEDBY NVARCHAR2(150) null +FEES NUMBER(22) null +SHIPMENTMODE NVARCHAR2(30) null +SCAC NUMBER(22) null + +## PERMITS_INVOICES_BCKP +ID NUMBER(22) notnull +INVOICENUMBER NUMBER(22) null +SERVICECODE NVARCHAR2(30) null +PERMITID NUMBER(22) null +WAYBILLID NUMBER(22) null +INVOICEDATE DATE(7) null +CREATIONDATE DATE(7) null +NOTES NVARCHAR2(1500) null +CREATEDBY NVARCHAR2(150) null +FEES NUMBER(22) null +SHIPMENTMODE NVARCHAR2(30) null +SCAC NUMBER(22) null + +## PERMITS_INVOICES_SUMMARY +ID NUMBER(22) notnull PK +REFRRANCENUMBER VARCHAR2(15) null +SERVICE VARCHAR2(50) null +COMPANYCODE VARCHAR2(50) null +COMPANYNAME NVARCHAR2(300) null +RECORDDATE DATE(7) notnull +NUMBER_OF_PERMITS NUMBER(22) null +FEES NUMBER(22) null +TOTAL_FEES NUMBER(22) null + +## PERMITS_RECEIPTS +ID NUMBER(22) notnull PK +RECEIPT_NO NUMBER(22) null +PERMIT_ID NUMBER(22) null +PN NUMBER(22) null +SHIPMENTMODE NVARCHAR2(30) null +FMSHIPMENTMODE NVARCHAR2(30) null +CRN NUMBER(22) null +CA_CODE NUMBER(22) null +TN NVARCHAR2(300) null +TRN NVARCHAR2(300) null +DRVR NVARCHAR2(1500) null +NNPN NVARCHAR2(300) null +MOBILE NVARCHAR2(300) null +CREATION_DATE DATE(7) null +CREATED_BY NVARCHAR2(300) null +STATUSCODE NVARCHAR2(300) null +DLN NVARCHAR2(300) null +DLED VARCHAR2(500) null +SCAC NUMBER(22) null +FEES NUMBER(22) null +RECEIPT_TYPE NUMBER(22) null +PERMIT_STATUS NVARCHAR2(300) null +CONFIRMATION_DATE DATE(7) null +CONFIRMATION_BY NVARCHAR2(300) null +REVOKE_DATE DATE(7) null +REVOKE_BY NVARCHAR2(300) null +REJECT_REASON NUMBER(22) null +FMINBOUNDTYPECODE NVARCHAR2(150) null +DESTINATIONADDRESSID NUMBER(22) null +ORIGINADDRESSID NUMBER(22) null +INBOUNDTYPECODE NVARCHAR2(150) null +REJECT_REASON_NOTE NVARCHAR2(1500) null +LASTUPDATEDATE DATE(7) null +LASTUPDATEBY VARCHAR2(500) null +CREDIT NUMBER(22) notnull +REQUEST_ID NUMBER(22) null + +## PERMITS_RECEIPTS_TEMP +ID NUMBER(22) notnull PK +RECEIPT_NO NUMBER(22) null +PERMIT_ID NUMBER(22) null +PN NUMBER(22) null +SHIPMENTMODE NVARCHAR2(30) null +FMSHIPMENTMODE NVARCHAR2(30) null +CRN NUMBER(22) null +CA_CODE NUMBER(22) null +TN NVARCHAR2(300) null +TRN NVARCHAR2(300) null +DRVR NVARCHAR2(1500) null +NNPN NVARCHAR2(300) null +MOBILE NVARCHAR2(300) null +CREATION_DATE DATE(7) null +CREATED_BY NVARCHAR2(300) null +STATUSCODE NVARCHAR2(300) null +DLN NVARCHAR2(300) null +DLED VARCHAR2(500) null +SCAC NUMBER(22) null +FEES NUMBER(22) null +RECEIPT_TYPE NUMBER(22) null +PERMIT_STATUS NVARCHAR2(300) null +CONFIRMATION_DATE DATE(7) null +CONFIRMATION_BY NVARCHAR2(300) null +FMINBOUNDTYPECODE NVARCHAR2(150) null +INBOUNDTYPECODE NVARCHAR2(150) null +ORIGINADDRESSID NUMBER(22) null +DESTINATIONADDRESSID NUMBER(22) null + +## PERMITS_RECEIPTS_TYPE +ID NUMBER(22) notnull PK +FEES NUMBER(22) null +DESCRIPTION NVARCHAR2(1500) null +NOTES NVARCHAR2(1500) null +CAPTION NVARCHAR2(300) null +SCAC NUMBER(22) null +SORTORDER NUMBER(22) null + +## PERMITS_TO_YARD4 +ID NUMBER(22) notnull PK +PN NUMBER(22) notnull +CREATIONDATE DATE(7) notnull +STATUS VARCHAR2(20) notnull +CID VARCHAR2(20) null +OPERATIONTYPE VARCHAR2(10) null +OLD_PN NUMBER(22) null +TN NVARCHAR2(1500) null +DRVR NVARCHAR2(1500) null +NNPN NVARCHAR2(1500) null +SHIPMENTSTATUSCODE VARCHAR2(10) null +PERMIT_ID NUMBER(22) null +QUEUE_STATUS VARCHAR2(10) null + +## PERMITTYPES +ID NUMBER(22) notnull PK +TT NUMBER(22) null +CT1 NUMBER(22) null +CT2 NUMBER(22) null +OPT1 NVARCHAR2(150) null +OPT2 NVARCHAR2(150) null +STATUS NUMBER(22) null +SORTORDER NUMBER(22) null + +## PERMIT_EXCEL_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) null +USER_ID VARCHAR2(50) null +REPORT_FILTER CLOB(4000) null + +## PERMIT_NEXT_ORIGIN +ID NUMBER(22) null +LASTLOCATIONID NUMBER(22) null +NEXTLOCATIONID NUMBER(22) null +DOMAIN VARCHAR2(50) null + +## PERMIT_QUEUE_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +STATUS_CODE VARCHAR2(20) notnull +PERMIT_ID NUMBER(22) notnull +PERMIT_STATUS_CODE VARCHAR2(20) null +CURRENT_LEG_ID NUMBER(22) notnull +QUEUE_DATA CLOB(4000) null +TYPE VARCHAR2(20) notnull +RESULT_MSG CLOB(4000) null +YARD_ID NUMBER(22) null + +## PERMIT_REQUEST +ID NUMBER(22) notnull PK +TN VARCHAR2(10) notnull +TRN VARCHAR2(10) notnull +NNPN VARCHAR2(10) notnull +OPERATION_TYPE NUMBER(22) notnull +ORGIN_ID NUMBER(22) notnull +LOADING_LOCATION NUMBER(22) null +DISCHARGE_LOCATION NUMBER(22) null +CAN NUMBER(22) null +CREATION_DATE DATE(7) notnull +CREATED_BY VARCHAR2(20) notnull +LAST_UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(20) null +EWALLET_NUMBER NUMBER(22) null +STATUS_CODE VARCHAR2(20) notnull +FEES NUMBER(22) notnull +REJECT_REASON VARCHAR2(50) null +REJECT_REASON_NOTE NVARCHAR2(750) null +REVOKE_BY VARCHAR2(25) null +REVOKE_DATE DATE(7) null +RECEIPT_ID NUMBER(22) null +CONFIRMATION_BY VARCHAR2(50) null +CONFIRMATION_DATE DATE(7) null +SCAC NUMBER(22) null +REQUEST_NUMBER VARCHAR2(20) null +DEST_ID NUMBER(22) null + +## PMIS_TRANSACTIONS_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +DATA CLOB(4000) notnull +OPERATION_NAME VARCHAR2(100) notnull + +## QUEUE_LOG_ERROR +ID NUMBER(22) notnull PK +ERROR CLOB(4000) notnull +ERROR_DATE DATE(7) null +QUEUE_TYPE VARCHAR2(20) notnull +TYPEID NUMBER(22) null +QUEUE_DATA CLOB(4000) null + +## QUEUE_WS_FAILED_LOG +ID NUMBER(22) notnull PK +TYPE_NAME VARCHAR2(50) null +TYPE VARCHAR2(50) null +CREATIONDATE DATE(7) null +ERROR CLOB(4000) null +SERVER_IP VARCHAR2(50) null + +## RECEIPT +ID NUMBER(22) notnull PK +WAYBILL_NUMBER NUMBER(22) null +TRUCK_NUMBER NUMBER(22) null +TRUCK_OWNER VARCHAR2(50) null +ORIGINALNAME VARCHAR2(100) null +FILENAME VARCHAR2(100) null +CREATETIMESTAMP DATE(7) null +CREATEUSERID VARCHAR2(10) null +ORIGINALNAME2 VARCHAR2(100) null +FILENAME2 VARCHAR2(100) null + +## RECEIPTS_OPERATION_TYPES +CODE VARCHAR2(25) null +CAPTION VARCHAR2(50) null +DOMAIN VARCHAR2(10) null +SORTORDER NUMBER(22) null + +## RECEIPT_REVOKE_REJECT_REASON +ID NUMBER(22) notnull PK +NAME VARCHAR2(200) null + +## REFINERY_CARDS +ID NUMBER(22) notnull PK +TN NUMBER(22) notnull +CARD_NUMBER VARCHAR2(10) notnull +BOX_NO NUMBER(22) null +CURRENT_BALANCE NUMBER(22) notnull +CREATION_DATE DATE(7) notnull +CREATED_BY VARCHAR2(20) notnull +UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(20) null +STATUS_CODE VARCHAR2(10) notnull +LAST_TRIP_ID NUMBER(22) null + +## REFINERY_CARDS_LOG +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) notnull +METHOD_NAME VARCHAR2(100) notnull +BALANCE_BEFORE NUMBER(10,3) notnull +BALANCE_AFTER NUMBER(10,3) notnull +CREATED_BY VARCHAR2(50) notnull +CREATION_DATE DATE(7) notnull +UPDATED_BY VARCHAR2(50) null +LAST_UPDATE_DATE DATE(7) null +AMOUNT NUMBER(10,3) notnull +PN VARCHAR2(20) null + +## REFINERY_COMMISSION_CLAIM +ID NUMBER(22) notnull PK +COMMISSION_CLAIM_NO NUMBER(22) null +COMMISSION_CLAIM_DATE DATE(7) null +STATUS_CODE VARCHAR2(20) null +CREATED_BY VARCHAR2(50) null +LAST_UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(50) null + +## REFINERY_COMMISSION_CLAIM_LOG +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null +USER_ID VARCHAR2(50) null +USER_IP VARCHAR2(50) null + +## REFINERY_COMPANY +ID NUMBER(22) notnull +CODE NUMBER(22) notnull +NAME NVARCHAR2(1500) notnull +CREATION_DATE DATE(7) notnull +CREATED_BY VARCHAR2(10) notnull +DISPLAY_NAME NVARCHAR2(300) notnull + +## REFINERY_DINARAK_API_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +STATUS_CODE VARCHAR2(20) notnull +SERVICE_NAME VARCHAR2(20) notnull +EWALLET_NUMBER VARCHAR2(50) notnull +AMOUNT NUMBER(22) notnull +NNPN VARCHAR2(20) notnull +REQUEST_DATA CLOB(4000) notnull +RESPONSE_DATA CLOB(4000) null +REFINERY_TRIP_ID NUMBER(22) null + +## REFINERY_REMAINING_BALANCE +ID NUMBER(22) notnull PK +TN NUMBER(22) notnull +REMAINING_BALANCE NUMBER(10,3) notnull +BEFORE_REMAINING_BALANCE NUMBER(10,3) null +CREATED_BY VARCHAR2(50) null +CREATION_DATE DATE(7) notnull +UPDATED_BY VARCHAR2(50) null +LAST_UPDATE_DATE DATE(7) null + +## REFINERY_REMAINING_BALANCE_LOG +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) notnull +AMOUNT NUMBER(10,3) notnull +BALANCE_BEFORE NUMBER(10,3) notnull +CREATED_BY VARCHAR2(50) notnull +CREATION_DATE DATE(7) notnull +UPDATED_BY VARCHAR2(50) null +LAST_UPDATE_DATE DATE(7) null +TRIP_ID NUMBER(22) null +REF_VARIABLES_GROUP_ID NUMBER(22) null + +## REFINERY_TRIPS +ID NUMBER(22) notnull PK +PN VARCHAR2(20) notnull +DISPATCH_DATE DATE(7) null +ACTUAL_LOADING_DATE DATE(7) null +ACTUAL_LOADING_TIME VARCHAR2(10) null +LOADING_CENTER VARCHAR2(100) null +CLIENT_NO VARCHAR2(20) null +TN VARCHAR2(50) null +TRN VARCHAR2(50) null +NNPN VARCHAR2(50) null +MATERIAL_NO VARCHAR2(50) null +MENAGATE_NO VARCHAR2(50) null +EMPTY_WEIGHT NUMBER(12,3) null +GROSS_WEIGHT NUMBER(12,3) null +NET_LOADING_WEIGHT NUMBER(12,3) null +STANDARD_UNITS_WEIGHT NUMBER(12,3) null +LITERS_WEIGHT NUMBER(12,3) null +DENSITY NUMBER(10,3) null +TEMPERATURE NUMBER(7,3) null +FLAG NUMBER(22) null +DISCHARGE_AUTHORIZTION_NO VARCHAR2(50) null +DISCHARGE_AUTHORIZTION_YEAR NUMBER(22) null +DISCHARGE_ENTRY_DATE DATE(7) null +DISCHARGE_ENTRY_TIME VARCHAR2(10) null +DISCHARGE_EXIT_DATE DATE(7) null +DISCHARGE_EXIT_TIME VARCHAR2(10) null +ACTUAL_GROSS_WEIGHT NUMBER(12,3) null +ACTUAL_EMPTY_WEIGHT NUMBER(12,3) null +NET_DISCHARGE_WEIGHT NUMBER(12,3) null +WATER_AMOUNT NUMBER(12,3) null +SEDIMENT_AMOUNT NUMBER(8,3) null +TRIP_STATUS VARCHAR2(20) null +USER_ID VARCHAR2(100) null +TRIP_LAST_UPDATE_DATE VARCHAR2(20) null +DAY_TIME NUMBER(22) null +PROGRAM_ID VARCHAR2(100) null +WORK_STN_ID VARCHAR2(20) null +EXCHANGE_CLAIM_NO VARCHAR2(20) null +PAID_AMOUNT_WATER VARCHAR2(300) null +STATUS_CODE VARCHAR2(50) null +CREATION_DATE DATE(7) notnull +LAST_UPDATE_DATE DATE(7) null +CREATED_BY VARCHAR2(50) null +FIRST_ADVANCE_PAYMENT NUMBER(22) null +SECOND_ADVANCE_PAYMENT NUMBER(22) null +DIESEL_LITER_PRICE NUMBER(22) null +TON_WAGE NUMBER(7,3) null +TON_PRICE NUMBER(7,3) null +DRIVER_TIP NUMBER(7,3) null +PERMIT_DISPATCH NUMBER(22) null +WAYBILL_FEE NUMBER(7,3) null +COMMISSION NUMBER(7,3) null +UPDATED_BY VARCHAR2(50) null +CALCULATED_QUANTITY_TON NUMBER(10,3) null +QUANTITY_WAGE NUMBER(10,3) null +TOLERANCE_QUANTITY NUMBER(10,3) null +PENALTY_QUANTITY NUMBER(10,3) null +PENALTY_AMOUNT NUMBER(10,3) null +NET_WAGE NUMBER(10,3) null +REMARKS VARCHAR2(500) null +WAGE_CLAIM_ID NUMBER(22) null +LOADING_NO NUMBER(22) null +RECEIVED_BY VARCHAR2(50) null +RECEIVED_DATE DATE(7) null +PAYMENTED_BY VARCHAR2(50) null +PAYMENTED_DATE DATE(7) null +DINARAK_REFERENCE_ID NUMBER(22) null +DIESEL_CHARGE NUMBER(22) null +TRANSFERED NUMBER(22) null +REFINERY_WALLET_ID NUMBER(22) null +REVERSE_PAYMENT NUMBER(22) null +PAYMENT_OPTIONS VARCHAR2(50) null +VOUCHER_SERIAL_NUMBER NUMBER(22) null +TRIP_NET_WAGE NUMBER(10,3) null +REMAINING_BALANCE NUMBER(10,3) null + +## REFINERY_TRIPS_LOG +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null +STATUS_CODE VARCHAR2(50) null +TRIP_STATUS VARCHAR2(50) null +USER_ID VARCHAR2(50) null +USER_IP VARCHAR2(50) null + +## REFINERY_VARIABLES +ID NUMBER(22) notnull PK +KEY_NAME VARCHAR2(50) notnull +KEY_VALUE VARCHAR2(50) notnull +CREATION_DATE DATE(7) notnull +CREATED_BY VARCHAR2(50) notnull +UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(50) null +START_DATE DATE(7) null +END_DATE DATE(7) null +GROUP_ID NUMBER(22) null + +## REFINERY_WAGE_CLAIM +ID NUMBER(22) notnull PK +WAGE_CLAIM_NO NUMBER(22) null +WAGE_CLAIM_DATE DATE(7) null +COMMISSION_CLAIM_NO NUMBER(22) null +STATUS_CODE VARCHAR2(20) null +CREATED_BY VARCHAR2(50) null +COMMISSION_CLAIM_ID NUMBER(22) null +UPDATED_BY VARCHAR2(50) null +LAST_UPDATE_DATE DATE(7) null +TRANSFERED NUMBER(22) null + +## REFINERY_WAGE_CLAIM_LOG +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null +USER_ID VARCHAR2(50) null +USER_IP VARCHAR2(50) null + +## REFINERY_WALLET +ID NUMBER(22) notnull PK +TN NUMBER(22) null +COMPANY_CODE NUMBER(22) null +EPAYMENT NUMBER(22) notnull +OWNER_NNPN NUMBER(22) null +WALLET_NUMBER NVARCHAR2(45) null +OWNER_NAME NVARCHAR2(450) null +CREATION_DATE DATE(7) notnull +DRIVER_NAME NVARCHAR2(450) null +DRIVER_NNPN NUMBER(22) null +IBAN VARCHAR2(50) null +BANK_ACCOUNT VARCHAR2(50) null +BANK_NAME NVARCHAR2(300) null +CREATED_BY VARCHAR2(10) notnull +UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(10) null +STATUS_CODE VARCHAR2(10) notnull +BANK_BRANCH VARCHAR2(50) null +OWNER_NAME_ENGLISH VARCHAR2(150) null + +## REFINERY_WALLET_LOG +ID NUMBER(22) notnull PK +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null +STATUS_CODE VARCHAR2(50) null +TRIP_STATUS VARCHAR2(50) null +USER_ID VARCHAR2(50) null +USER_IP VARCHAR2(50) null + +## REPORT_LOG +ID NUMBER(22) notnull PK +TN NVARCHAR2(450) null +TRN NVARCHAR2(450) null +NNPN NVARCHAR2(450) null +CRN NVARCHAR2(450) null +PERMIT_NO NVARCHAR2(450) null +LOCATIONID NUMBER(22) null +STATUS VARCHAR2(20) null +DATEFROM DATE(7) null +DATETO DATE(7) null +REPORTNAME NVARCHAR2(450) null +USERID VARCHAR2(20) null +CREATIONDATE DATE(7) null + +## ROUTEGPS +ID NUMBER(22) notnull PK +POINTORDER NUMBER(22) null +ORGID NUMBER(22) null +DESTID NUMBER(22) null +LON NUMBER(22) null +LAT NUMBER(22) null +PERC NUMBER(22) null + +## ROUTEGPS_BCKP +ID NUMBER(22) null +POINTORDER NUMBER(22) null +ORGID NUMBER(22) null +DESTID NUMBER(22) null +LON NUMBER(22) null +LAT NUMBER(22) null +PERC NUMBER(22) null + +## ROUTESTOFIX +ROUTEID NUMBER(22) null + +## ROUTESTOFIX2 +ROUTEID NUMBER(22) null + +## ROUTING +ID NUMBER(22) notnull PK +ROUTENAME NVARCHAR2(600) null +ORGADDRESSID NUMBER(22) null +DESTADDRESSID NUMBER(22) null +DISPORDER NUMBER(22) null +DOMAIN VARCHAR2(6) notnull PK +SHIPMENTMODE VARCHAR2(10) null +CREATEDBY NVARCHAR2(150) null +CREATEDATE DATE(7) null +UPDATEDBY NVARCHAR2(150) null +LASTUPDATEDATE DATE(7) null +STATUS NUMBER(22) null +DEFAULTLANE VARCHAR2(50) null +EXPRESS_LANE NUMBER(22) null +OVERNIGHT NUMBER(22) null +RELATED_CTL NUMBER(22) null +RELATED_EMCON NUMBER(22) null +RELATED_TADMOUR NUMBER(22) null + +## ROUTINGETA +ORGID NUMBER(22) null +DESTID NUMBER(22) null +SHIPMENTMODE NVARCHAR2(30) null +FMSHIPMENTMODE NVARCHAR2(30) null +CNT NUMBER(22) null +ETA NUMBER(22) null + +## ROUTINGLEGS +ID NUMBER(22) notnull PK +LOCATIONID NUMBER(22) null +SORTORDER NUMBER(22) null +ROUTEID NUMBER(22) null +DOMAIN VARCHAR2(8) null + +## ROUTINGLEGS_BACKUP +ID NUMBER(22) notnull +LOCATIONID NUMBER(22) null +SORTORDER NUMBER(22) null +ROUTEID NUMBER(22) null +DOMAIN VARCHAR2(8) null + +## SAD_GEN_TRANS +TRANS_NO NUMBER(22) notnull +KEY_DEC VARCHAR2(50) null +TRANS_YEAR NUMBER(22) notnull +ENTRY_DATE DATE(7) null +SAD_ITM_TOTAL VARCHAR2(50) null +SAD_PACK_TOTAL VARCHAR2(50) null +SAD_MANIF_NBER VARCHAR2(50) null +WEIGHT VARCHAR2(50) null +CLOSE_DATE VARCHAR2(50) null +CENTER_TO VARCHAR2(50) null +DES_COUNTRY VARCHAR2(50) null +KEY_YEAR VARCHAR2(50) null +KEY_CUO VARCHAR2(50) null +KEY_NBER VARCHAR2(50) null +SAD_REG_SERIAL VARCHAR2(50) null +SAD_REG_NBER VARCHAR2(50) null +SAD_REG_DATE VARCHAR2(50) null +SAD_REG_YEAR VARCHAR2(50) null +CREATEDBY VARCHAR2(50) null +SAD_LOC_GOODS VARCHAR2(50) null + +## SAD_GEN_VIEW +PERM_NO NUMBER(22) notnull +KEY_DEC VARCHAR2(50) null +PERM_YEAR NUMBER(22) notnull +ENTRY_DATE DATE(7) null +SAD_ITM_TOTAL VARCHAR2(50) null +SAD_PACK_TOTAL VARCHAR2(50) null +SAD_MANIF_NBER VARCHAR2(50) null +WEIGHT VARCHAR2(50) null +CLOSE_DATE VARCHAR2(50) null +CENTER_TO VARCHAR2(50) null +DES_COUNTRY VARCHAR2(50) null +KEY_YEAR VARCHAR2(50) null +KEY_CUO VARCHAR2(50) null +KEY_NBER VARCHAR2(50) null +SAD_REG_SERIAL VARCHAR2(50) null +SAD_REG_NBER VARCHAR2(50) null +SAD_REG_DATE VARCHAR2(50) null +SAD_REG_YEAR VARCHAR2(50) null +CREATEDBY VARCHAR2(50) null + +## SAD_ITM_TRANS +TRANS_NO NUMBER(22) null +TRANS_YEAR NVARCHAR2(150) null +SADITM_GOODS_DESC1 NVARCHAR2(3000) null +SADITM_GOODS_DESC2 NVARCHAR2(3000) null +SADITM_GOODS_DESC3 NVARCHAR2(3000) null +WEIGHT NVARCHAR2(150) null + +## SAD_ITM_VIEW +PERM_NO NUMBER(22) null +PERM_YEAR NVARCHAR2(150) null +SADITM_GOODS_DESC1 NVARCHAR2(3000) null +SADITM_GOODS_DESC2 NVARCHAR2(3000) null +SADITM_GOODS_DESC3 NVARCHAR2(3000) null +WEIGHT NVARCHAR2(150) null + +## SCHEDULE +ID NUMBER(22) notnull PK +PERMITID NUMBER(22) null +CRID NUMBER(22) null +WAYBILLID NUMBER(22) null +ACTIONCODE VARCHAR2(10) notnull +SCHEDULEDATE DATE(7) notnull +STATUS NUMBER(22) notnull +ACTIONDONEDATE DATE(7) null +ACTIONDONEBY VARCHAR2(50) null +REMARKS NVARCHAR2(600) null +CREATETIMESTAMP DATE(7) notnull +CREATEUSERID VARCHAR2(20) notnull +LASTUPDATETIMESTAMP DATE(7) null +LASTUPDATEUSERID VARCHAR2(20) null + +## SHIPMENTMODE +CODE NVARCHAR2(30) notnull PK +CAPTION NVARCHAR2(300) null +DOMAIN VARCHAR2(5) notnull PK + +## SHIPPINGLINES +CODE VARCHAR2(50) null +COMPID NUMBER(22) null +COMPANYNUMBER VARCHAR2(50) null + +## SOJ_AXIALLOADS +ID NUMBER(22) notnull +AXIALCODE NUMBER(22) null +TOTALLOADTON NUMBER(22) null + +## SRQ_ORDERS +ID NUMBER(22) notnull PK +TYPE VARCHAR2(200) null +HEIGHT VARCHAR2(5) null +LENGTH VARCHAR2(5) null +LOCATIONID NUMBER(22) null +DESTINATIONID NUMBER(22) null +ORDERDATE DATE(7) null +SHIFT NUMBER(22) null +QUANTITY NUMBER(22) null +SHIPPINGLINE VARCHAR2(100) null +CREATEUSERID VARCHAR2(100) null +CREATETIMESTAMP DATE(7) null +LASTUPDATEUSERID VARCHAR2(100) null +LASTUPDATETIMESTAMP DATE(7) null +STATUS NVARCHAR2(30) null + +## STATUS +CODE VARCHAR2(10) null +DESCRIPTION NVARCHAR2(150) null +REF VARCHAR2(10) null +ISACTIVE NUMBER(22) null +DOMAIN VARCHAR2(5) null + +## STAT_HRS +HR24 NUMBER(22) notnull + +## SYSTEMPRINTERS +ID NUMBER(22) notnull PK +BOOTHID NUMBER(22) null +PRINTERID VARCHAR2(100) null +PRINTERCAPTION VARCHAR2(100) null +DOCUMENTTYPE VARCHAR2(50) null +STATUS VARCHAR2(10) null +CREATEDBY NVARCHAR2(150) null +CREATEDATE DATE(7) null +UPDATEDBY NVARCHAR2(150) null +LASTUPDATEDATE DATE(7) null + +## SYS_EXPORT_SCHEMA_01 +PROCESS_ORDER NUMBER(22) null +DUPLICATE NUMBER(22) null +DUMP_FILEID NUMBER(22) null +DUMP_POSITION NUMBER(22) null +DUMP_LENGTH NUMBER(22) null +DUMP_ORIG_LENGTH NUMBER(22) null +DUMP_ALLOCATION NUMBER(22) null +COMPLETED_ROWS NUMBER(22) null +ERROR_COUNT NUMBER(22) null +ELAPSED_TIME NUMBER(22) null +OBJECT_TYPE_PATH VARCHAR2(200) null +OBJECT_PATH_SEQNO NUMBER(22) null +OBJECT_TYPE VARCHAR2(30) null +IN_PROGRESS CHAR(1) null +OBJECT_NAME VARCHAR2(500) null +OBJECT_LONG_NAME VARCHAR2(4000) null +OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_NAME VARCHAR2(4000) null +PARTITION_NAME VARCHAR2(30) null +SUBPARTITION_NAME VARCHAR2(30) null +DATAOBJ_NUM NUMBER(22) null +FLAGS NUMBER(22) null +PROPERTY NUMBER(22) null +TRIGFLAG NUMBER(22) null +CREATION_LEVEL NUMBER(22) null +COMPLETION_TIME DATE(7) null +OBJECT_TABLESPACE VARCHAR2(30) null +SIZE_ESTIMATE NUMBER(22) null +OBJECT_ROW NUMBER(22) null +PROCESSING_STATE CHAR(1) null +PROCESSING_STATUS CHAR(1) null +BASE_PROCESS_ORDER NUMBER(22) null +BASE_OBJECT_TYPE VARCHAR2(30) null +BASE_OBJECT_NAME VARCHAR2(30) null +BASE_OBJECT_SCHEMA VARCHAR2(30) null +ANCESTOR_PROCESS_ORDER NUMBER(22) null +DOMAIN_PROCESS_ORDER NUMBER(22) null +PARALLELIZATION NUMBER(22) null +UNLOAD_METHOD NUMBER(22) null +LOAD_METHOD NUMBER(22) null +GRANULES NUMBER(22) null +SCN NUMBER(22) null +GRANTOR VARCHAR2(30) null +XML_CLOB CLOB(4000) null +PARENT_PROCESS_ORDER NUMBER(22) null +NAME VARCHAR2(30) null +VALUE_T VARCHAR2(4000) null +VALUE_N NUMBER(22) null +IS_DEFAULT NUMBER(22) null +FILE_TYPE NUMBER(22) null +USER_DIRECTORY VARCHAR2(4000) null +USER_FILE_NAME VARCHAR2(4000) null +FILE_NAME VARCHAR2(4000) null +EXTEND_SIZE NUMBER(22) null +FILE_MAX_SIZE NUMBER(22) null +PROCESS_NAME VARCHAR2(30) null +LAST_UPDATE DATE(7) null +WORK_ITEM VARCHAR2(30) null +OBJECT_NUMBER NUMBER(22) null +COMPLETED_BYTES NUMBER(22) null +TOTAL_BYTES NUMBER(22) null +METADATA_IO NUMBER(22) null +DATA_IO NUMBER(22) null +CUMULATIVE_TIME NUMBER(22) null +PACKET_NUMBER NUMBER(22) null +INSTANCE_ID NUMBER(22) null +OLD_VALUE VARCHAR2(4000) null +SEED NUMBER(22) null +LAST_FILE NUMBER(22) null +USER_NAME VARCHAR2(30) null +OPERATION VARCHAR2(30) null +JOB_MODE VARCHAR2(30) null +QUEUE_TABNUM NUMBER(22) null +CONTROL_QUEUE VARCHAR2(30) null +STATUS_QUEUE VARCHAR2(30) null +REMOTE_LINK VARCHAR2(4000) null +VERSION NUMBER(22) null +JOB_VERSION VARCHAR2(30) null +DB_VERSION VARCHAR2(30) null +TIMEZONE VARCHAR2(64) null +STATE VARCHAR2(30) null +PHASE NUMBER(22) null +GUID RAW(16) null +START_TIME DATE(7) null +BLOCK_SIZE NUMBER(22) null +METADATA_BUFFER_SIZE NUMBER(22) null +DATA_BUFFER_SIZE NUMBER(22) null +DEGREE NUMBER(22) null +PLATFORM VARCHAR2(101) null +ABORT_STEP NUMBER(22) null +INSTANCE VARCHAR2(60) null +CLUSTER_OK NUMBER(22) null +SERVICE_NAME VARCHAR2(100) null +OBJECT_INT_OID VARCHAR2(32) null + +## TAG +ID NUMBER(22) notnull PK +TN NUMBER(22) null +TAGID VARCHAR2(50) notnull +STATUSCODE VARCHAR2(10) notnull +CREATEDBY VARCHAR2(100) notnull +CREATIONTIME DATE(7) notnull +TRUCKID NUMBER(22) notnull +DEACTIVATION_USER VARCHAR2(50) null +DEACTIVATION_TIME DATE(7) null +REMARKS VARCHAR2(100) null + +## TAG_QUEUE_LOG +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) null +STATUS_CODE VARCHAR2(20) null +TAG_ID NUMBER(22) null +TAG_STATUS VARCHAR2(20) null +QUEUE_DATA CLOB(4000) null + +## TAX_INVOICE_LOG +ID NUMBER(22) notnull PK +INVOICE_NUMBER VARCHAR2(50) null +STATUS_CODE VARCHAR2(10) null +COMPANY_DESCRIPTION VARCHAR2(50) null +CREATION_DATE DATE(7) null + +## TEMP +TN VARCHAR2(100) null +REASON VARCHAR2(100) null +ID NUMBER(22) null + +## TEMP2 +TN VARCHAR2(55) notnull + +## TEMPDATA +IDS VARCHAR2(30) null + +## TEMPP +ID NUMBER(22) null + +## TEMPPERMITS +ID NUMBER(22) null + +## TEMPTN +TN NUMBER(22) null + +## TEMP_BACKLIST +NNPN VARCHAR2(100) null +NOTE NVARCHAR2(765) null + +## TEMP_BACKLIST_2 +NNPN VARCHAR2(100) null +NOTE NVARCHAR2(765) null + +## TEMP_BL +TN VARCHAR2(50) null +PN VARCHAR2(50) null +NOTES NVARCHAR2(750) null +ID NUMBER(22) null +PERMITDATE DATE(7) null + +## TEMP_BL_DANGER +TN NVARCHAR2(1500) null +LASTPERMITID NUMBER(22) null + +## TEMP_BL_ID +ID NUMBER(22) null + +## TEMP_DRIVER +NNPN NUMBER(22) null + +## TEMP_FUEL_ORDER +TN NUMBER(22) null +TRN NUMBER(22) null +NNPN NUMBER(22) null +CARGO VARCHAR2(10) null +ID NUMBER(22) null + +## TEMP_NTP_COMPANIES_TRUCKS +TN VARCHAR2(500) null +TRN VARCHAR2(500) null +USAGE_TYPE NVARCHAR2(300) null +COMPANY_ID NUMBER(22) null +TN_ID NUMBER(22) null + +## TEMP_NTP_TRAILERS +ID NUMBER(22) notnull +TN NVARCHAR2(1500) null +TCSCAC NUMBER(22) null +STATUSCODE VARCHAR2(20) null +CREATETIMESTAMP DATE(7) null +LASTUPDATETIMESTAMP DATE(7) null +AXIALS VARCHAR2(20) null +REG_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +KINDID NUMBER(22) null +DOMAIN VARCHAR2(20) null +CHASESNUMBER VARCHAR2(40) null +CREATEUSERID VARCHAR2(20) null +OWNERNAME VARCHAR2(100) null +OWNERNNPN VARCHAR2(40) null +REVOKEDDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null +ACCEPTEDDATE DATE(7) null +ACCEPTEDBY VARCHAR2(20) null +PHONENUMBER NUMBER(22) null +TN_ID NUMBER(22) null + +## TEMP_NTP_TRUCKS +ID NUMBER(22) notnull +TN VARCHAR2(500) null +TCSCAC NUMBER(22) null +STATUSCODE VARCHAR2(20) null +CREATETIMESTAMP DATE(7) null +LASTUPDATETIMESTAMP DATE(7) null +AXIALS VARCHAR2(20) null +REG_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +KINDID NUMBER(22) null +DOMAIN VARCHAR2(20) null +CHASESNUMBER VARCHAR2(40) null +CREATEUSERID VARCHAR2(20) null +OWNERNAME VARCHAR2(100) null +OWNERNNPN VARCHAR2(40) null +COLOR VARCHAR2(20) null +MODEL VARCHAR2(20) null +MANIFACTUREYEAR NUMBER(22) null +REVOKEDDATE DATE(7) null +REVOKEDBY VARCHAR2(20) null +ACCEPTEDDATE DATE(7) null +ACCEPTEDBY VARCHAR2(20) null +PHONENUMBER NUMBER(22) null +HEADTYPE VARCHAR2(20) null + +## TEMP_NTP_TRUCKS_PERSONAL +TN VARCHAR2(500) null +TRN VARCHAR2(500) null +ID NUMBER(22) null +TN_STATUS_CODE VARCHAR2(20) null +TRN_STATUS_CODE VARCHAR2(20) null +TN_ID NUMBER(22) null + +## TEMP_ORDERS +ORDER_NUMBER VARCHAR2(25) notnull + +## TEMP_OWNERS_NNPN +TN VARCHAR2(500) null +OWNERNAME VARCHAR2(200) null +NNPN VARCHAR2(20) null + +## TEMP_OWNERS_TRAILERS_NNPN +TN NVARCHAR2(1500) null +OWNERNAME VARCHAR2(200) null +NNPN VARCHAR2(20) null + +## TEMP_SULF +TN VARCHAR2(100) null + +## TEMP_TCS_ACTIVE_PERMITS +S1ID NUMBER(22) null +STATUS1 VARCHAR2(8) null +S2ID NUMBER(22) null +STATUS2 VARCHAR2(8) null +PN VARCHAR2(50) null + +## TEMP_TRAILERS +TRN VARCHAR2(20) null + +## TEMP_TRUCKS_HEADTYPES +TN NVARCHAR2(1500) null +TN_ID NUMBER(22) null +TRAILER_CATEGORY VARCHAR2(20) null +NEWCT VARCHAR2(7) null + +## TEMP_TRUCKS_MOBILE +TN NVARCHAR2(1500) null +NNPN NVARCHAR2(1500) null +MOBILE VARCHAR2(15) null + +## TEMP_TWINNING +TN NVARCHAR2(300) null + +## TEM_LOCATION +ID NUMBER(22) null +NAFITH NVARCHAR2(600) null +MADARIJ NVARCHAR2(600) null + +## TENDERS +ID NUMBER(22) notnull PK +NAME VARCHAR2(50) null +SORTORDER NUMBER(22) null +ISACTIVE VARCHAR2(1) null + +## TEST +TRN1 VARCHAR2(20) notnull PK +MINORCODE NUMBER(22) notnull + +## TNTRN_OUT_OF_TRIPS_COUNT +ID NUMBER(22) notnull PK +TN NVARCHAR2(60) null +TRN NVARCHAR2(60) null +STATUS_CODE VARCHAR2(20) null +CREATION_DATE DATE(7) notnull +CREATED_BY NVARCHAR2(30) null +UPDATE_DATE DATE(7) null +UPDATED_BY NVARCHAR2(30) null + +## TN_TEMP +TN NVARCHAR2(300) null +SCAC NUMBER(22) null + +## TRAILERS_INFO +ID NUMBER(22) notnull PK +TRN NVARCHAR2(45) notnull +STATUS_CODE VARCHAR2(20) notnull +CREATED_BY VARCHAR2(50) null +CREATION_DATE DATE(7) notnull +LICENSE_NO VARCHAR2(20) null +LICENSE_REGISTRATION_NO VARCHAR2(20) null +LICENSE_EXPIRY_DATE DATE(7) null +MANIFACTURER VARCHAR2(20) null +MANIFACTURE_YEAR NUMBER(22) null +TRAILER_TYPE VARCHAR2(150) null +TRAILER_CATEGORY VARCHAR2(20) null +NATIONALITY NVARCHAR2(30) null +COLOR VARCHAR2(20) null +MODEL VARCHAR2(20) null +VIN_NUMBER VARCHAR2(50) null +ENGINE_NUMBER VARCHAR2(50) null +LOADING_WEIGHT NUMBER(22) null +GROSS_WEIGHT NUMBER(22) null +OWNER_NAME VARCHAR2(500) null +OWNER_NNPN VARCHAR2(40) null +OWNER_PHONE_NUMBER NUMBER(22) null +OWNER_ADDRESS NVARCHAR2(750) null +LAST_UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(50) null +NOTES NVARCHAR2(750) null +REVOKE_REASON VARCHAR2(100) null +GOVERNATE VARCHAR2(100) null +SECONDARY_COLOR VARCHAR2(30) null +TRN_CODE NVARCHAR2(45) null + +## TROUBLESHOOT_ACTIONS +ID NUMBER(22) notnull PK +NAME VARCHAR2(100) null + +## TROUBLESHOOT_RESPONSE +ID NUMBER(22) notnull PK +BLACKLISTID NUMBER(22) notnull +USERID VARCHAR2(20) notnull +RESPONSE VARCHAR2(2500) null +RESPONSEDATE DATE(7) notnull +FINAL NUMBER(22) notnull +ACTIONID NUMBER(22) null + +## TRUCKKINDS +ID NUMBER(22) notnull PK +AXIALCODE NUMBER(22) null +TRUCKKINDCODE VARCHAR2(5) null +DESCREPTION VARCHAR2(100) null +SORTORDER NUMBER(22) null + +## TRUCKS +ID NUMBER(22) notnull PK +TN VARCHAR2(50) null +CREATIONTIME DATE(7) notnull +TCSCAC NUMBER(22) null +AXIALS VARCHAR2(20) null +REG_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +KINDID NUMBER(22) null +DOMAIN VARCHAR2(20) null +CHASESNUMBER VARCHAR2(40) null +CREATEUSERID VARCHAR2(20) null +OWNERNAME VARCHAR2(100) null +OWNERNNPN VARCHAR2(40) null +COLOR VARCHAR2(20) null +MODEL VARCHAR2(20) null +MANIFACTUREYEAR NUMBER(22) null +HEADTYPE VARCHAR2(20) null +TRUCK_NAT VARCHAR2(20) null + +## TRUCKS_INFO +ID NUMBER(22) notnull PK +TN NVARCHAR2(45) notnull +STATUS_CODE VARCHAR2(20) notnull +CREATED_BY VARCHAR2(50) null +CREATION_DATE DATE(7) notnull +LICENSE_NO VARCHAR2(20) null +LICENSE_REGISTRATION_NO VARCHAR2(20) null +LICENSE_EXPIRY_DATE DATE(7) null +MANIFACTURER VARCHAR2(20) null +MANIFACTURE_YEAR NUMBER(22) null +TRUCK_TYPE VARCHAR2(150) null +TRUCK_CATEGORY VARCHAR2(150) null +NATIONALITY NVARCHAR2(30) null +COLOR VARCHAR2(20) null +MODEL VARCHAR2(60) null +VIN_NUMBER VARCHAR2(50) null +ENGINE_NUMBER VARCHAR2(50) null +LOADING_WEIGHT NUMBER(22) null +GROSS_WEIGHT NUMBER(22) null +OWNER_NAME VARCHAR2(500) null +OWNER_NNPN VARCHAR2(40) null +OWNER_PHONE_NUMBER NUMBER(22) null +OWNER_ADDRESS NVARCHAR2(750) null +LAST_UPDATE_DATE DATE(7) null +UPDATED_BY VARCHAR2(50) null +NOTES NVARCHAR2(750) null +REVOKE_REASON VARCHAR2(100) null +GOVERNATE VARCHAR2(100) null +SECONDARY_COLOR VARCHAR2(30) null +TN_CODE NVARCHAR2(45) null + +## TRUCKS_TEMP +TN VARCHAR2(500) null +TRN VARCHAR2(500) null +TYPE VARCHAR2(500) null +SCAC NUMBER(22) null +TN_ID NUMBER(22) null + +## TRUCKS_TEMP_2 +TN VARCHAR2(500) null +TRN VARCHAR2(500) null +TYPE VARCHAR2(500) null +SCAC NUMBER(22) null +TN_ID NUMBER(22) null + +## TRUCKS_TEMP_OLD +TN VARCHAR2(500) null +TRN VARCHAR2(500) null +TYPE VARCHAR2(500) null +SCAC NUMBER(22) null + +## TRUCKTYPE +ID NUMBER(22) notnull PK +NAME NVARCHAR2(60) null + +## TRUCK_DISTRIBUTION_LOG +ID NUMBER(22) notnull PK +PERMITID NUMBER(22) null +ORDERID NUMBER(22) null +ORDERDATE DATE(7) null +CREATIONDATE DATE(7) null +UPDATEDATE DATE(7) null +TN VARCHAR2(20) null +STATUSCODE VARCHAR2(20) null +NOTES VARCHAR2(500) null +BLACKLISTID NUMBER(22) null +CARGOTYPE NUMBER(22) null +CREATEDBY VARCHAR2(20) null +ISBLOCKED NUMBER(22) null + +## UTT +ID NUMBER(22) notnull +USERID VARCHAR2(50) null +BOOTHID NUMBER(22) null +STATUS VARCHAR2(50) null +CREATIONDATE DATE(7) null +CREATEDBY VARCHAR2(50) null +UPDATEDATE DATE(7) null +UPDATEDBY VARCHAR2(50) null +DOMAIN VARCHAR2(50) null + +## VEHICLESTENDERS +ID NUMBER(22) notnull PK +VEHICLEID NUMBER(22) null +TENDERID NUMBER(22) null +STATUS NUMBER(22) null +CREATETIMESTAMP DATE(7) null +LASTUPDATETIMESTAMP DATE(7) null +PHONENUMBER VARCHAR2(10) null +TN NUMBER(22) null + +## VESSELS +ID NUMBER(22) notnull PK +NAME VARCHAR2(50) notnull +TOTALCAPACITY NUMBER(22) notnull +STATUS VARCHAR2(1) notnull +CREATEUSERID VARCHAR2(15) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null + +## VESSELS_HISTORY +ID NUMBER(22) notnull PK +VESSELID NUMBER(22) notnull +STATUS VARCHAR2(1) notnull +REASON NUMBER(22) null +NOTES VARCHAR2(500) null +CREATEUSERID VARCHAR2(15) notnull +CREATETIMESTAMP DATE(7) notnull + +## VESSEL_SCHEDULE +ID NUMBER(22) notnull PK +VESSELID NUMBER(22) notnull +SCHEDULEDATE DATE(7) notnull +CREATEUSERID VARCHAR2(15) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null + +## VESSEL_SCHEDULE_PERMITS +ID NUMBER(22) notnull PK +VESSELSCHEDULEID NUMBER(22) notnull +PERMITID NUMBER(22) notnull +ISACTIVE NUMBER(22) notnull +CREATEUSERID VARCHAR2(15) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null + +## VESSEL_SECTIONS +ID NUMBER(22) notnull PK +VESSELID NUMBER(22) notnull +CAPACITY NUMBER(22) null +CAPTION VARCHAR2(100) null +CREATEUSERID VARCHAR2(15) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null + +## VESSEL_SECTIONS_CARGOTYPE +ID NUMBER(22) notnull PK +VESSELSECTIONID NUMBER(22) notnull +CARGOTYPID NUMBER(22) notnull +CREATEUSERID VARCHAR2(15) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(15) null +LASTUPDATETIMESTAMP DATE(7) null + +## VILLAGES +ID NUMBER(22) notnull PK +NAME VARCHAR2(50) null +CITYID NUMBER(22) null + +## VIOLATIONS +ID NUMBER(22) notnull PK +PERMITID NUMBER(22) null +VIOLATIONTYPEID NUMBER(22) null +LOCATIONID NUMBER(22) null +CREATEDBY VARCHAR2(50) null +CREATIONDATE DATE(7) null +REMARKS NVARCHAR2(900) null +VIOLATIONDATE DATE(7) null + +## VIOLATIONTYPES +ID NUMBER(22) notnull PK +FEES NUMBER(22) null +DESCRIPTION NVARCHAR2(900) null +CREATIONDATE DATE(7) null +LASTUPDATEDATE DATE(7) null +STATUS VARCHAR2(50) null + +## WARNINGS +ID NUMBER(22) notnull PK +CRID NUMBER(22) null +WBLID NUMBER(22) null +PERMITID NUMBER(22) null +ISACTIVE VARCHAR2(1) null +STARTDATE DATE(7) null +EXPIRYDATE DATE(7) null +WARNINGID NUMBER(22) null +CREATIONDATE DATE(7) null +CREATEBY VARCHAR2(20) null +UPDATEDDATE DATE(7) null +UPDATEDBY VARCHAR2(20) null +UPDATEDTYPE NVARCHAR2(150) null + +## WARNINGTYPES +ID NUMBER(22) notnull PK +DESCRIPTION NVARCHAR2(4000) null +SEVERITY VARCHAR2(1) null + +## WARNING_TEMP +CRID NUMBER(22) notnull PK +EXPIRYDATE DATE(7) null + +## WASHINGQUEUE +ID NUMBER(22) notnull PK +TN VARCHAR2(15) null +TRN VARCHAR2(15) null +DRVR_NNPN VARCHAR2(20) null +STATUSCODE VARCHAR2(20) null +CREATIONDATE DATE(7) null +DRVR NVARCHAR2(300) null +QUEUE_DATE DATE(7) null +CREATEDBY VARCHAR2(20) null +UPDATEDBY VARCHAR2(20) null +UPDATEDATE DATE(7) null +RELEASEDATE DATE(7) null +RELEASEBY VARCHAR2(20) null +FREEZEDATE DATE(7) null +FREEZEBY VARCHAR2(20) null +PERMITID NUMBER(22) null + +## WAYBILL +ID NUMBER(22) notnull PK +CRID NUMBER(22) null +TCID NUMBER(22) null +SENTTO VARCHAR2(250) null +SENTTOADDRESS VARCHAR2(1000) null +DELIVERYDATE DATE(7) null +DELIVERYPLACE NUMBER(22) null +TRANSFEESJD NUMBER(22) null +TRANSTIME DATE(7) null +DELIVERYCONDITIONS NVARCHAR2(4000) null +TRANSPATH NVARCHAR2(4000) null +OTHEREXPENSE NVARCHAR2(4000) null +DELIVERYMAXTIME NUMBER(22) null +OTHERTASKS NVARCHAR2(1500) null +CREATEDBY NVARCHAR2(36) null +CREATIONDATE DATE(7) null +UPDATEDBY NVARCHAR2(300) null +LASTUPDATEDATE DATE(7) null +STATUS VARCHAR2(8) null +WAYBILLNUM NUMBER(22) null +PERMITID NUMBER(22) null +CANCELREASON NVARCHAR2(4000) null +SENTTOPHONE VARCHAR2(20) null +TRANSFEESFILS NUMBER(22) null +LOADINGMAXTIME NUMBER(22) null +DANGERNOTES NVARCHAR2(4000) null +FEESNOTES NVARCHAR2(4000) null +FROMWEIGHT NUMBER(22) null +TOWEIGHT NUMBER(22) null +TRUCKTYPE NUMBER(22) null +CARGOSIZE NUMBER(22) null +CARGOTYPE NUMBER(22) null +UPDATEDTYPE NVARCHAR2(150) null +DELIVERYLOC NUMBER(22) null +NETWIEGHT NUMBER(22) null +TRANSFEES NUMBER(22) notnull +EMPTYFEES NUMBER(22) notnull +PERMITFEES NUMBER(22) notnull +PORTFEES NUMBER(22) notnull +WEIGHFEES NUMBER(22) notnull +ASSIGNTO VARCHAR2(50) null +DOMAIN VARCHAR2(10) null + +## WAYBILLCHANGES +ID NUMBER(22) notnull PK +WAYBILL_ID NUMBER(22) notnull +CHANGETYPE NUMBER(22) null +NAME VARCHAR2(20) null +VALUE VARCHAR2(200) null +STATUS NUMBER(22) null +CHANGELEVEL NUMBER(22) null +DONEBY NVARCHAR2(300) null +CREATETIMESTAMP DATE(7) null +UPDATEDBY NVARCHAR2(300) null +LASTUPDATEDATE DATE(7) null + +## WAYBILLFEES +ID VARCHAR2(50) notnull +WBL_FEES NUMBER(22) null +TCS_SINGLEMOVE_FEES NUMBER(22) null +TCS_DOUBLEMOVE_FEES NUMBER(22) null +TCS_DLP_FEES NUMBER(22) null +NAFITH_COMMISION NUMBER(22) null +SOJ_COMMISION NUMBER(22) null +CREATIONDATE DATE(7) null +EXPIRYDATE DATE(7) null +CREATEDBY VARCHAR2(50) null +VEHICLE_DEMURRAGE NUMBER(22) null +CARGO_DEMURRAGE NUMBER(22) null + +## WAYBILL_FILES +ID NUMBER(22) notnull PK +WBID NUMBER(22) null +ORIGINALNAME NVARCHAR2(300) null +FILENAME NVARCHAR2(300) null +TYPE VARCHAR2(10) null + +## WAYBILL_INSURANCE +ID NUMBER(22) notnull PK +NAME VARCHAR2(50) null +VALUE VARCHAR2(50) null +SORTORDER NUMBER(22) null + +## WEIGHBRIDGE_RAW_DATA +LOCATIONID NUMBER(22) notnull +CARGO_KEY NUMBER(22) notnull +CARGO_STATE NUMBER(22) null +CARGO_TIME_IN DATE(7) null +CARGO_WEIGHT_IN NUMBER(5,0) null +CARGO_TIME_OUT DATE(7) null +CARGO_WEIGHT_OUT NUMBER(5,0) null +CARGO_WEIGHT_NET NUMBER(5,0) null +CARGO_TYPE VARCHAR2(10) null +CARGO_TYPE_TXT NVARCHAR2(300) null +CARGO_DRIVER_NAME NVARCHAR2(300) null +CARGO_TRUCK_NO NUMBER(22) null +CARGO_SOURCE NVARCHAR2(300) null +PERMITID NUMBER(22) null + +## WEIGHBRIDGE_RAW_DATA_BCKP +LOCATIONID NUMBER(22) notnull +CARGO_KEY NUMBER(22) notnull +CARGO_STATE NUMBER(22) null +CARGO_TIME_IN DATE(7) null +CARGO_WEIGHT_IN NUMBER(5,0) null +CARGO_TIME_OUT DATE(7) null +CARGO_WEIGHT_OUT NUMBER(5,0) null +CARGO_WEIGHT_NET NUMBER(5,0) null +CARGO_TYPE VARCHAR2(10) null +CARGO_TYPE_TXT NVARCHAR2(300) null +CARGO_DRIVER_NAME NVARCHAR2(300) null +CARGO_TRUCK_NO NUMBER(22) null +CARGO_SOURCE NVARCHAR2(300) null +PERMITID NUMBER(22) null + +## YARD4_GPS +ID NUMBER(22) null +GPS VARCHAR2(100) null + +## YARD_TIME_LIMIT +ID NUMBER(22) notnull PK +YARDNO NUMBER(22) notnull +TIMELIMIT NUMBER(22) notnull +CREATE_DATE DATE(7) notnull +CREATED_BY VARCHAR2(20) notnull + +## SEQUENCES +GC_SEQ, IVR_LOGS_SEQ, LOGINAUDITSEQ, LOG_CARGORELEASESSEQ, LTRC_COMPANY_ACTIVITY_TEMP_SEQ, ORDERSSEQ, REFINERY_WAGE_CLAIMSEQ, SEQ_310_GC, SEQ_327_GC, SEQ_47_GC, SEQ_65_GC, SEQ_89_GC, SEQ_ACT, SEQ_ACTIVATIONLOG, SEQ_ACT_CONTAINER_EXPORT, SEQ_ACT_CUSTOM_EXPORT, SEQ_ACT_PREGATE_FILES, SEQ_ACT_PREGATE_JOBS, SEQ_ACT_PREGATE_LOG, SEQ_ARAB_BRIDGE_QUEUE_LOG, SEQ_ARAB_BRIDGE_TRUCKS, SEQ_BLACKLIST, SEQ_BLACKLIST_DANGER, SEQ_BLACKLIST_QUEUE_LOG, SEQ_BLOCKEDLOCATIONS, SEQ_CARGORELEASES, SEQ_CARGORELEASESAUDIT, SEQ_CARGORELEASESDELEGATION, SEQ_CARGORELEASESDETAILS, SEQ_CARGORELEASESLOG, SEQ_CARGORELEASESPERMITS, SEQ_CARGORELEASESPERMITS_AB, SEQ_CARGORELEASES_AB, SEQ_CHECK_INTERNAL_CONTAINERS, SEQ_CID_HISTORY, SEQ_COMPANY_USER_ACTIVITY, SEQ_COMPANY_USER_ACTIVITY_TEMP, SEQ_CONTAINERVALIDITY, SEQ_CRNO, SEQ_CTL_ORDERS, SEQ_CTL_ORDERS_DETAILS, SEQ_CUSTOMS_EXPORT, SEQ_DEMURAGEVOUCHERS, SEQ_DESTINATION_QUOTA, SEQ_DINARK_API_LOG_ID, SEQ_DRIVERS, SEQ_DRIVERS_INFO, SEQ_EVENTS, SEQ_EVENTS_QUEUE_LOG, SEQ_EXT_INTEGRATION_QUEUE_LOG, SEQ_FLEET_DISTRIBUTION, SEQ_FLEET_ORDER, SEQ_FLEET_ORDER_DETAIL, SEQ_FLEET_QUEUE, SEQ_FLEET_QUEUE_LOG, SEQ_FUELBILLING, SEQ_FUEL_BILLING, SEQ_FUEL_FILES, SEQ_FUEL_WAGE, SEQ_GC_BLACKLIST, SEQ_GC_FILES, SEQ_GC_QUEUE, SEQ_GC_TRAILERS, SEQ_GC_TRUCKS, SEQ_GN_TCS_INTEGRATION, SEQ_GRAINSBLACKLIST, SEQ_GRAINS_BILLING, SEQ_GRAINS_FILES, SEQ_GRAINS_FINE, SEQ_GRAINS_PERMITS_WEIGHTS, SEQ_GRAINS_TRACKINGNO_CO, SEQ_GRAINS_TRACKINGNO_OWN, SEQ_GRAINS_TRUCKS_VALIDATION, SEQ_GRAINS_WAGE, SEQ_GRAINS_WEIGHBRIDG_CONTROL, SEQ_INVALID_ACCESS_LOG, SEQ_INVOICE, SEQ_INVOICE_DETAILS, SEQ_INVOICE_INFO, SEQ_INVOICE_SUMMARY, SEQ_JOPETROL_INTEGRATION_2, SEQ_LOCATIONS, SEQ_LOCATIONS_LOG, SEQ_LOG_ACT_CONTAINER_EXPORT, SEQ_LOG_CTL_ORDERS, SEQ_LOG_CUSTOMS_EXPORT, SEQ_LOG_FLEETDISTRIBUTION, SEQ_LOG_FLEETORDER, SEQ_LOG_FLEETQUEUE, SEQ_LOG_PERMITREQUEST, SEQ_LOG_PERMITS, SEQ_LOG_PERMITSRECEIPTS, SEQ_LOG_REFINERYTRIP, SEQ_LOG_REFINERY_WAGE_CLAIM, SEQ_LOG_REFINERY_WALLET, SEQ_LOG_TROUBLESHOOT, SEQ_LOG_WASHINGQUEUE, SEQ_MANUALKIOSKSLOG, SEQ_MANUAL_DESTINATIONS, SEQ_MOBILE_ATTACHEMNT, SEQ_MOT_ENTITYSPECS, SEQ_MOT_ENTITYSPECS_TMP, SEQ_MOT_EXCEPTIONS, SEQ_MOT_TN_ABROAD_TRIPS, SEQ_MOT_TRAILERS, SEQ_MOT_TRAILERS_FILES, SEQ_MOT_TRAILERS_TMP, SEQ_MOT_TRUCKS, SEQ_MOT_TRUCKS_FILES, SEQ_MOT_TRUCKS_TMP, SEQ_NEW_PORT_INTEGRATION_LOG, SEQ_NTP_COMPANY_DISTINATION, SEQ_NTP_DRIVERS, SEQ_NTP_ENTITYSPECS, SEQ_NTP_FUELTENDERORDER, SEQ_NTP_GRAINSTENDERORDER, SEQ_NTP_TRAILERS, SEQ_NTP_TRUCKS, SEQ_ORDERS, SEQ_OWNERS, SEQ_PERMITLANESATTRIBUTES, SEQ_PERMITLANES_LOG, SEQ_PERMITNUMBER, SEQ_PERMITROUTES, SEQ_PERMITS, SEQ_PERMITSRELATION, SEQ_PERMITSTOPS, SEQ_PERMITS_INVOICES, SEQ_PERMITS_INVOICES_SUMMARY, SEQ_PERMITS_RECEIPTS, SEQ_PERMITS_TO_YARD4, SEQ_PERMIT_EXCEL_LOG, SEQ_PERMIT_QUEUE_LOG, SEQ_PERMIT_REQUEST, SEQ_PERMIT_REQUEST_NUMBER, SEQ_PMIS, SEQ_QUEUE_LOG_ERROR, SEQ_QUEUE_WS_FAILED_LOG, SEQ_RECEIPT, SEQ_REFINARY_DINARK_API_LOG_ID, SEQ_REFINERY_CARDS, SEQ_REFINERY_CARDS_LOG, SEQ_REFINERY_COMMISSION_CLAIM, SEQ_REFINERY_REMAINING_BALANCE, SEQ_REFINERY_TRIPS, SEQ_REFINERY_TRIPS_LOG, SEQ_REFINERY_VARIABLES, SEQ_REFINERY_VARIABLES_GID, SEQ_REFINERY_WAGE_CLAIM, SEQ_REFINERY_WAGE_CLAIM_LOG, SEQ_REFINERY_WALLET, SEQ_REF_REMAINING_BALANCE_LOG, SEQ_REPORT_LOG, SEQ_ROUTING, SEQ_ROUTINGLEGS, SEQ_SCHEDULE, SEQ_SHARES_GC, SEQ_SRQ_ORDERS, SEQ_SYSTEMPRINTERS, SEQ_TAG, SEQ_TAG_QUEUE_LOG, SEQ_TAX_INVOICE_LOG, SEQ_TRAILERS_INFO, SEQ_TRUCKS, SEQ_TRUCKS_COMPANIES_MAPPING, SEQ_TRUCKS_INFO, SEQ_TRUCK_DISTRIBUTION_LOG, SEQ_UNIQUETRACK, SEQ_UTT, SEQ_VEHICLESTENDERS, SEQ_VESSELS_HISTORY, SEQ_VESSEL_SCHEDULE, SEQ_VESSEL_SCHEDULE_PERMITS, SEQ_VIOLATIONS, SEQ_WARNINGS, SEQ_WASHINGQUEUE, SEQ_WAYBILL, SEQ_WAYBILLCHANGES, SEQ_WAYBILL_FILES, TRC_COMPANY_ACTIVITY_SEQ, TROUBLESHOOTSEQ diff --git a/docs/schema/NTP.md b/docs/schema/NTP.md new file mode 100644 index 0000000..4c1e9fd --- /dev/null +++ b/docs/schema/NTP.md @@ -0,0 +1,1911 @@ +# Schema NTP (Oracle 11.2.0.4, qajodb) - columns: NAME TYPE(len/prec,scale) NULLABLE; PK marked + +## ACTIONS +ID NUMBER(3,0) notnull PK +NAME NVARCHAR2(240) null + +## ACTION_ACCESS_PERMISSION +ID NUMBER(22) notnull PK +SAM_ID NUMBER(22) notnull +ACTION_ALLOWED_VALUE NVARCHAR2(150) notnull +RECORD_STATUS NVARCHAR2(45) notnull + +## AI_VEHICLE +TYPE VARCHAR2(1) null +HR24 NUMBER(22) null + +## APPLICATION_ACTIONS +ID NUMBER(22) notnull PK +NAME NVARCHAR2(300) notnull + +## APPLICATION_STATUS +ID NUMBER(22) notnull PK +STATUS NVARCHAR2(300) notnull +LANGID NUMBER(22) notnull +APPERANCESTAT NVARCHAR2(300) null + +## APPLICATION_TYPES +ID NUMBER(22) notnull PK +NAME NVARCHAR2(300) notnull +PARENTSERVICE NUMBER(22) null +PATH VARCHAR2(100) null +DEFAULTFEES NUMBER(22) null + +## ATTACHMENTS +ID NUMBER(22) notnull PK +ENTITYID NUMBER(22) null +ENTITYNAME VARCHAR2(50) null +FILENAME VARCHAR2(500) null +FILETYPE VARCHAR2(100) null + +## BANKS +ID NUMBER(22) notnull PK +NAME NVARCHAR2(150) null + +## BILLING +ID NUMBER(22) notnull PK +APPREFID NUMBER(22) notnull +FEES NUMBER(22) notnull +BILLINGDATE DATE(7) notnull +SRVCID NUMBER(22) notnull + +## BLOCKED_USERS_SERVICES +ID NUMBER(22) notnull PK +USERLOGIN VARCHAR2(100) null +CREATEDATE DATE(7) notnull +BLOCK_END_DATE DATE(7) null +SERVICENAME VARCHAR2(100) null +STATUS VARCHAR2(30) null +BLOCKTYPE VARCHAR2(100) null + +## CARGOTYPE +ID NUMBER(22) notnull PK +CODE VARCHAR2(10) notnull +NAME NVARCHAR2(150) notnull + +## CHARGENAMEPRICE +ID NUMBER(22) notnull PK +NAME NVARCHAR2(75) null +PRICE NUMBER(22) null + +## CITIES +ID NUMBER(22) notnull PK +NAME VARCHAR2(20) null +SORTORDER NUMBER(22) null + +## CLAIMSAPP_DETAILS +ID NUMBER(22) notnull PK +CLAIMSAPPID NUMBER(22) notnull +PERMITNO NUMBER(22) null +DRIVERNAME NVARCHAR2(900) null +YARDNO NUMBER(22) null +CANCELREASON NUMBER(22) null +CARGOTYPE NUMBER(22) null +ENTRANCEREASONS NUMBER(22) null +PERMITSQNTY NUMBER(22) null +CLEARNAME NUMBER(22) null +PERMITSTYPE NUMBER(22) null +WORKEDFLAG NUMBER(22) null +FACITYDATE NVARCHAR2(30) null +FACITYHUR NVARCHAR2(15) null +FACITYDURATION NUMBER(22) null +FACITYREASONS NUMBER(22) null +WEIGHT NUMBER(22) null +PACTVQNTY NUMBER(22) null +RELEASENO1 NVARCHAR2(75) null +RELEASENO2 NVARCHAR2(75) null +TRUCKNO NVARCHAR2(60) null +TRAILERNO NVARCHAR2(60) null +TRUCKNATIONALITY NUMBER(22) null +CARNUMBER NVARCHAR2(60) null +DESTCOMPANY NUMBER(22) null +DEDUCTVALUE NUMBER(22) null +TT VARCHAR2(100) null +EXCEPTIONREASON NVARCHAR2(60) null +CID VARCHAR2(20) null +EMP_CANCEL_REASON NUMBER(22) null + +## CLAIMSAPP_FILES +ID NUMBER(22) notnull PK +CLAIMSAPPID NUMBER(22) notnull +ORIGINALNAME NVARCHAR2(600) notnull +FILENAME VARCHAR2(200) notnull + +## CLAIMSAPP_MASTER +ID NUMBER(22) notnull PK +APPDATE DATE(7) notnull +CLAIMTYPE NUMBER(22) notnull +NOTE NCLOB(4000) notnull +DONEBY VARCHAR2(10) notnull +WFID NUMBER(22) notnull +CARGOTYPE NUMBER(22) null + +## CLAIMSAPP_REASONS +ID NUMBER(22) notnull PK +CAPTION NVARCHAR2(900) notnull +CLAIMSTYPE NUMBER(22) notnull + +## CLAIMSAPP_RESPONSE +ID NUMBER(22) notnull PK +CLAIMSAPPID NUMBER(22) notnull +SUPERVISORID VARCHAR2(10) notnull +SUPERVISORCOMMENT NCLOB(4000) notnull +LEVELNO NUMBER(22) notnull +RESPONSEDATE DATE(7) notnull +DECISIONDIR NUMBER(22) null +SHIFT NUMBER(22) null +NUMPERMISSION NVARCHAR2(1500) null + +## CLAIMSRESP_FILES +ID NUMBER(22) notnull PK +RESPAPPID NUMBER(22) null +ORIGINALNAME NVARCHAR2(300) null +FILENAME VARCHAR2(100) null + +## CLEARING_AGENTS +ID NVARCHAR2(75) null +NAME NVARCHAR2(1500) null + +## COMPANIES +ID NUMBER(22) notnull PK +NAME NVARCHAR2(300) notnull +STAKEHOLDERID NUMBER(22) notnull +STATUS NUMBER(22) notnull +DESCRIPTION NVARCHAR2(300) null +EMAIL NVARCHAR2(150) null +FAX NVARCHAR2(150) null +TELEPHONE NVARCHAR2(150) null +MOBILE NVARCHAR2(150) null +CONTACTPERSON NVARCHAR2(300) null +ADDRESS NVARCHAR2(600) null +BILLINGADDRESS NVARCHAR2(600) null +EXCEPTION48HRS NUMBER(22) null +EXCEPTIONTRIPCOUNT NUMBER(22) null +WBLAUDIT NUMBER(22) null +ACCOUNT_NUMBER NUMBER(22) null +SCAC NUMBER(22) null +HAS_EXCEL_SERVICE NUMBER(22) notnull +CREATIONDATE DATE(7) null +BILLING_NUMBER VARCHAR2(20) null +CREATEDBY VARCHAR2(50) null +UPDATEDBY VARCHAR2(50) null +LASTUPDATEDATE DATE(7) null +REVOKE_REASON VARCHAR2(50) null +NOTES VARCHAR2(250) null + +## COMPANYNOTES +ID NUMBER(22) notnull PK +DONEBY VARCHAR2(10) null +NOTESUBJECT VARCHAR2(300) null +NOTEDATA NCLOB(4000) null +WFID NUMBER(22) null +APPDATE DATE(7) null +COMMITMENT NUMBER(22) null + +## COMPANYNOTES_FILES +ID NUMBER(22) notnull PK +COMPNOTEID NUMBER(22) null +ORIGINALNAME NVARCHAR2(300) null +FILENAME VARCHAR2(100) null + +## COMPANYNOTES_RESPONSE +ID NUMBER(22) notnull PK +COMPNOTEID NUMBER(22) null +SUPERVISORID VARCHAR2(10) null +SUPERVISORCOMMENT NCLOB(4000) null +LEVELNO NUMBER(22) null +RESPONSEDATE DATE(7) null +DECISIONDIR NUMBER(22) null +SHIFT NUMBER(22) null + +## COMPANYNOTES_RESP_FILES +ID NUMBER(22) notnull PK +RESPAPPID NUMBER(22) null +ORIGINALNAME NVARCHAR2(300) null +FILENAME VARCHAR2(100) null + +## DESTINATIONADDRESSID +ID NUMBER(22) notnull PK +CAPTION NVARCHAR2(300) null + +## FEE_TYPE +ID NUMBER(22) notnull PK +NAME VARCHAR2(50) null + +## FEE_VALUE +ID NUMBER(22) notnull PK +VALUE NUMBER(22) null +SERVICE_FEE_ID NUMBER(22) null +GROUP_ID NUMBER(22) null +STAKEHOLDER_ID NUMBER(22) null + +## FIELD_SEARCH +ID NUMBER(22) notnull PK +OBJECTNAME VARCHAR2(50) notnull +INPUTCSSID NVARCHAR2(150) notnull +FORMCSSID NVARCHAR2(150) notnull +SEARCH_TYPE NVARCHAR2(45) notnull +RECORD_STATUS NVARCHAR2(30) notnull +LOOKUP_FUNCTION NVARCHAR2(150) null +DEFAULT_VALUE NVARCHAR2(150) null +INPUTCSSCLASSES VARCHAR2(150) null +VALIDATION_CODE NVARCHAR2(150) null +MAX_LENGTH NUMBER(22) null +ORDERING NUMBER(22) null + +## FIRMS +CODE NVARCHAR2(60) notnull PK +CAPTION NVARCHAR2(300) null +DISPORDER NUMBER(22) null + +## GOVERNORATE +ID NUMBER(22) notnull PK +NAME NVARCHAR2(60) null + +## GROUPS +ID NUMBER(22) notnull PK +NAME VARCHAR2(50) notnull +DESCRIPTION VARCHAR2(100) null +STAKEHOLDERID NUMBER(22) null +STATUS NUMBER(22) null + +## GROUP_ACTIONS +ID NUMBER(19,0) notnull PK +GROUPID NUMBER(10,0) notnull +ACTIONID NUMBER(10,0) notnull + +## GROUP_SERVICE +ID NUMBER(19,0) notnull PK +GROUPID NUMBER(10,0) notnull +SERVICEID NUMBER(10,0) notnull + +## GROUP_USERS +ID NUMBER(22) notnull PK +GROUPID NUMBER(22) notnull +USERID NUMBER(22) notnull + +## HPNOTES +ID NUMBER(22) notnull PK +NOTEDATE DATE(7) notnull +VIEW_ROLE NVARCHAR2(30) null +VIEW_COMPID NUMBER(22) null +NOTETXT NVARCHAR2(900) notnull +URL VARCHAR2(100) null +APPID NUMBER(22) null + +## INBONDTYPECODE +CODE NVARCHAR2(30) notnull PK +CAPTION NVARCHAR2(300) null + +## KIOSKS_PRINTED_FILES +ID NUMBER(22) notnull PK +PARENT_FOLDER VARCHAR2(5) null +YARDID NUMBER(22) null +FILE_NAME VARCHAR2(100) null +CREATIONDATE DATE(7) null +ISJOB NUMBER(22) null +STATUS VARCHAR2(15) null + +## LOCATIONS +ID NUMBER(22) notnull PK +NAME NVARCHAR2(900) null +TYPE VARCHAR2(2) null + +## LOGINAUDIT +ID NUMBER(22) notnull PK +USERNAME VARCHAR2(50) null +ROLECODE VARCHAR2(50) null +DOMAIN VARCHAR2(50) null +LOGINTIME DATE(7) null +GROUPID VARCHAR2(500) null +SESSIONVARS CLOB(4000) null +CGI CLOB(4000) null + +## LOGS +ID NUMBER(22) notnull PK +ACTIONDATE DATE(7) notnull +IPADDRESS VARCHAR2(15) null +LOGTYPE NUMBER(22) notnull +DONEBY VARCHAR2(50) null +DONEBYROLE VARCHAR2(20) null +DONEBYNAME NVARCHAR2(300) null +BROWSER NVARCHAR2(900) null +REFERENCEID NUMBER(22) null +APPTYPE NUMBER(22) null + +## LOGS_TYPE +ID NUMBER(22) notnull PK +DESCRIPTION NVARCHAR2(210) notnull + +## LOG_TROUBLESHOOT +ID NUMBER(22) null +ENTITIY_ID NUMBER(22) null +METHOD_NAME VARCHAR2(100) null +LOG_DATE DATE(7) null +USER_ID NUMBER(22) null +USER_IP VARCHAR2(18) null +OLD_DATA CLOB(4000) null +NEW_DATA CLOB(4000) null + +## LT_ACTION +CODE NVARCHAR2(150) notnull PK +NAME VARCHAR2(300) notnull + +## LT_CAPTION +CODE VARCHAR2(100) notnull +AR NVARCHAR2(900) null +EN NVARCHAR2(900) null +MOBILE NUMBER(22) null + +## LT_CAPTION_BACKUP +CODE VARCHAR2(50) notnull +AR NVARCHAR2(900) null +EN NVARCHAR2(900) null +MOBILE NUMBER(22) null + +## LT_OBJECT +CODE VARCHAR2(50) notnull PK +CAPTIONCODE NVARCHAR2(900) notnull +PERMISSIONTYPE VARCHAR2(25) null +ENABLE_LOGGING NUMBER(22) null +TABLENAME VARCHAR2(60) null +DATASOURCE VARCHAR2(30) null + +## LT_PUBLIC +CODE VARCHAR2(100) notnull +NAME VARCHAR2(100) null +LT_TYPE VARCHAR2(100) notnull +ORDERING NUMBER(22) null + +## LT_PUBLIC_TYPE +LT_TYPE VARCHAR2(100) notnull PK + +## LT_TENDER +ID NUMBER(22) notnull PK +CODE NVARCHAR2(150) notnull +NAME NVARCHAR2(765) null + +## LT_VALIDATION +CODE NVARCHAR2(150) notnull PK +REGEX NVARCHAR2(210) null +PUBLIC_ERROR_CODE NVARCHAR2(300) notnull +HINT NVARCHAR2(300) null + +## MAIN_YARD_ORDERS +ID NUMBER(22) notnull PK +QUANTITY NUMBER(22) null +CRN VARCHAR2(50) null +STATUSCODE VARCHAR2(50) null +REMARKS NVARCHAR2(1500) null +CREATEDBY NVARCHAR2(150) null +CREATIONTIMESTAMP DATE(7) null +WFID NUMBER(22) null +SERVICE_TYPE VARCHAR2(50) null +CAN NUMBER(22) null +SHIFT VARCHAR2(10) null +CARGODESCRIPTION NVARCHAR2(150) null + +## MAIN_YARD_ORDERS_FILES +ID NUMBER(22) notnull PK +ORDERID NUMBER(22) null +ORIGINALNAME NVARCHAR2(150) null +FILENAME NVARCHAR2(150) null +RESPONSEID NUMBER(22) null + +## MAIN_YARD_ORDERS_RESPONSE +ID NUMBER(22) notnull PK +MAINORDERID NUMBER(22) null +SUPERVISORID VARCHAR2(50) null +SUPERVISORCOMMENT NCLOB(4000) null +LEVELNO NUMBER(22) null +RESPONSEDATE DATE(7) null +DECISIONDIR NUMBER(22) null + +## MANUALKIOSKINFO +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) null +STATUS_CODE VARCHAR2(50) null +MACADDRESS VARCHAR2(200) null +ENCRYPTIONKEY VARCHAR2(200) null +CONFIG VARCHAR2(2000) null +TYPE VARCHAR2(20) null + +## MLOG$_NTPUSERS +M_ROW$$ VARCHAR2(255) null +SNAPTIME$$ DATE(7) null +DMLTYPE$$ VARCHAR2(1) null +OLD_NEW$$ VARCHAR2(1) null +CHANGE_VECTOR$$ RAW(255) null +XID$$ NUMBER(22) null + +## MOBILENOTIFICATIONSLOG +ID NUMBER(22) notnull PK +USERID VARCHAR2(50) null +DEVICEID VARCHAR2(500) null +STATUS VARCHAR2(50) null +CREATIONDATE DATE(7) notnull +SENDERID VARCHAR2(50) null +MSG_REQUEST NVARCHAR2(4000) null +MSG_RESPONSE NVARCHAR2(4000) null +OS VARCHAR2(100) null +MSG_TEMPLATE_ID NUMBER(22) null +SOURCE_FROM NVARCHAR2(150) null + +## MOBILE_ERRORS +ID NUMBER(22) notnull +ERROR CLOB(4000) notnull +ERRORDATE DATE(7) notnull +IPADDRESS VARCHAR2(15) notnull +USERID VARCHAR2(50) null +BROWSER VARCHAR2(200) null +METHODNAME VARCHAR2(100) null +PARAMS VARCHAR2(500) null + +## MOBILE_FORGETPASSWORD_LOG +ID NUMBER(22) notnull PK +USERID NUMBER(22) notnull +NEW_PASSWORD VARCHAR2(50) notnull +STATUSCODE VARCHAR2(10) null +TYPE VARCHAR2(30) null + +## MOBILE_SESSIONS +ID NUMBER(22) notnull PK +USERID VARCHAR2(20) null +SESSIONSTART DATE(7) null +SESSIONEND DATE(7) null +SESSIONVARIABLES CLOB(4000) null + +## MOBILE_USER_INQUIRY +ID NUMBER(22) notnull PK +USERID VARCHAR2(50) notnull +CREATIONDATE DATE(7) notnull +MESSAGE NVARCHAR2(4000) notnull +STATUSCODE VARCHAR2(50) notnull +REPLY VARCHAR2(2000) null +REPLYBY VARCHAR2(20) null +REPLYDATE DATE(7) null + +## MOBILE_USER_TOKEN +ID NUMBER(22) notnull PK +CREATIONDATE DATE(7) null +STATUSCODE VARCHAR2(50) null +USERID VARCHAR2(100) null +OS VARCHAR2(20) null +TOKEN VARCHAR2(1000) null +SESSION_OBJECT VARCHAR2(1000) null + +## MOTREGTYPE +ID NUMBER(22) notnull PK +NAME NVARCHAR2(300) null + +## MOTTRUCKTYPE +ID NUMBER(22) notnull PK +CODE VARCHAR2(100) null +NAME NVARCHAR2(300) null + +## MOT_ENTITYSPECS +ID NUMBER(22) notnull PK +TNID NUMBER(22) null +TRNID NUMBER(22) null +SPECID NUMBER(22) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +TEMPUPDATEDATE DATE(7) null + +## MOT_TRAILERS +ID NUMBER(22) notnull PK +TRN VARCHAR2(20) notnull +TCSCAC VARCHAR2(5) notnull +OWNERSHIPCODE VARCHAR2(10) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +AXIS_NUM NUMBER(22) null +LICENSE_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +EMPTYWGHT NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(10) null +OWNERID NUMBER(22) null +AXIALID NUMBER(22) null + +## MOT_TRUCKS +ID NUMBER(22) notnull PK +TN NUMBER(22) notnull +TCSCAC NUMBER(22) notnull +OWNERSHIPCODE NUMBER(22) notnull +STATUS NUMBER(22) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATETIMESTAMP DATE(7) notnull +AXIS_NUM NUMBER(22) null +LICENSE_DATE DATE(7) null +LICENSE_NUM NUMBER(22) null +OWNERID NUMBER(22) null +LASTUPDATEUSERID VARCHAR2(20) null +AXIALID NUMBER(22) null +EMPTYWGHT NUMBER(22) null + +## NATIONALITY +CODE NVARCHAR2(30) null +ID NUMBER(22) notnull PK +NAME NVARCHAR2(300) null +LANGID NUMBER(22) null + +## NOTIFICATIONMESSAGETEMPLATE +ID NUMBER(22) notnull PK +TYPE NVARCHAR2(900) notnull +TITLE NVARCHAR2(900) notnull +MESSAGE NVARCHAR2(1050) notnull +ROLES NVARCHAR2(900) notnull +PRIORITY NUMBER(22) null + +## NTPNEWS +ID NUMBER(22) notnull PK +SUBJECT NVARCHAR2(300) notnull +NEWSBODY NCLOB(4000) notnull +NEWSDATE DATE(7) notnull +PUBLISHED NUMBER(22) null + +## NTPUSERS +ID NUMBER(22) notnull PK +FIRSTNAME NVARCHAR2(450) notnull +LASTNAME NVARCHAR2(450) notnull +EMAIL VARCHAR2(50) null +MOBILE VARCHAR2(15) null +LOGIN VARCHAR2(15) null +STATUS NUMBER(22) null +COMPANYID NUMBER(22) null +EMPNO VARCHAR2(15) null +ROLECODE VARCHAR2(20) null +PASSWORD VARCHAR2(50) null +SSOKEY VARCHAR2(50) null +SSOEXPIRY DATE(7) null +DOMAINNAME VARCHAR2(10) null +LOCATIONID NUMBER(22) null +LASTUPDATEDATE DATE(7) null +UPDATEDBY VARCHAR2(50) null +CONTACTSALUTATIONCODE VARCHAR2(50) null +EMPLOYMENTDATE DATE(7) null +TENDER VARCHAR2(50) null +CREATEDBY VARCHAR2(50) null +CREATIONDATE DATE(7) notnull +YARDIDS VARCHAR2(50) null +RESET_PASSWORD NUMBER(22) null +REVOKE_RESONS VARCHAR2(50) null +NOTES VARCHAR2(250) null +LAST_RESET_PASSWORD DATE(7) null + +## NTPUSERS_BCKP +ID NUMBER(22) notnull +FIRSTNAME NVARCHAR2(450) notnull +LASTNAME NVARCHAR2(450) notnull +EMAIL VARCHAR2(50) null +MOBILE VARCHAR2(15) null +LOGIN VARCHAR2(10) null +STATUS NUMBER(22) null +COMPANYID NUMBER(22) null +EMPNO VARCHAR2(15) null +ROLECODE VARCHAR2(8) null +PASSWORD VARCHAR2(50) null +SSOKEY VARCHAR2(50) null +SSOEXPIRY DATE(7) null +DOMAINNAME VARCHAR2(10) null +LOCATIONID NUMBER(22) null +LASTUPDATEDATE DATE(7) null +UPDATEDBY VARCHAR2(50) null +CONTACTSALUTATIONCODE VARCHAR2(50) null +EMPLOYMENTDATE DATE(7) null + +## OBJECT_ACCESS_PERMISSION +ID NUMBER(22) notnull PK +OBJECT VARCHAR2(25) null +KEY VARCHAR2(25) null +VALUE2 CLOB(4000) null +VALUE VARCHAR2(4000) null + +## ORIGINADDRESSID +ID NUMBER(22) notnull PK +CAPTION NVARCHAR2(300) null + +## OUTBOXMAIL +ID NUMBER(22) notnull PK +DONEBY NVARCHAR2(30) null +SENDTO NVARCHAR2(60) null +SMSDATA NCLOB(4000) null +APPDATE DATE(7) null +SHOULDREAD NUMBER(22) null +EXTERNALBOOK NUMBER(22) null +ALLEMPLOYEES NUMBER(22) null +SMSSUBJECT NVARCHAR2(150) null +DRIVERID NVARCHAR2(60) null +ROLECODE NVARCHAR2(60) null + +## OUTBOXMAIL_FILES +ID NUMBER(22) notnull PK +MAILID NUMBER(22) null +ORIGNAME NVARCHAR2(300) null +FILENAME NVARCHAR2(300) null + +## OUTBOXMAIL_READ +ID NUMBER(22) notnull PK +READBY NVARCHAR2(60) null +MAILID NUMBER(22) null +RAEDDATE DATE(7) null + +## OWNERSHIP_MATRIX +ROLE VARCHAR2(50) null +KEY VARCHAR2(50) null +OBJECT VARCHAR2(50) null +OBJECTKEY VARCHAR2(50) null +TYPE VARCHAR2(50) null + +## PERC_RANGE +MIN_VALUE NUMBER(22) null +MAX_VALUE NUMBER(22) null +CAPTION NVARCHAR2(300) null + +## PERMITSTATUS +CODE VARCHAR2(10) null +CATG VARCHAR2(10) null + +## PERMITSTYPE +ID NUMBER(22) notnull PK +NAME NVARCHAR2(900) null + +## PERMIT_STATUS +ID NUMBER(22) null +CODE NVARCHAR2(30) null +DESC_EN NVARCHAR2(150) null +DESC_AR NVARCHAR2(150) null + +## PETROLEUMBAN +ID NUMBER(22) notnull PK +BANTYPE NUMBER(22) null +VALUE NVARCHAR2(45) null +BANID NUMBER(22) null +DETAILS NVARCHAR2(3000) null +CREATEDATE DATE(7) null +CREATEBY VARCHAR2(10) null +STATUS NUMBER(22) null +CANCELDATE DATE(7) null +CANCELBY VARCHAR2(10) null + +## PETROLEUMBANLIST +ID NUMBER(22) notnull PK +NAME NVARCHAR2(150) null + +## PETROLEUMCHARGES +ID NUMBER(22) notnull PK +ORDERID NUMBER(22) null +FEEID NUMBER(22) null +AMOUNT NUMBER(22) null +CREATIONDATE DATE(7) null +USERID NVARCHAR2(36) null +VOUCHERNO NUMBER(22) null + +## PETROLEUMCLAIMS +ID NUMBER(22) notnull PK +INTERVALID NUMBER(22) notnull +LOSSKG NUMBER(22) notnull +SEAWATERKG NUMBER(22) notnull +TOTALPAYMENT NUMBER(22) notnull +COMPANYCODE NUMBER(22) notnull +DISCHARGEWEIGHT NUMBER(22) notnull +DEPOSITPERCENT NUMBER(22) notnull +DEPOSIT NUMBER(22) null + +## PETROLEUMCOMPANIES +ID NUMBER(22) notnull PK +COMPANYNAME NVARCHAR2(450) null +TRUCKSCOUNT NUMBER(22) null +DATEOFCOUNT DATE(7) null +ACTIVEFLAG NUMBER(22) null +COMPANYCODE NUMBER(22) null +REFINARYNAME NVARCHAR2(3000) null +BILLINGNAME NVARCHAR2(450) null +CONTACTNAME NVARCHAR2(300) null + +## PETROLEUMERRORMSG +CODE VARCHAR2(50) null +DESCRIPTION NVARCHAR2(150) null +LANGID NUMBER(22) null + +## PETROLEUMEVENTS +ID NUMBER(22) notnull PK +EVENTDATE DATE(7) null +LOCATIONID NUMBER(22) null +EVENTTYPE VARCHAR2(8) null +PREVSTATUS VARCHAR2(5) null +CURRESTATUS VARCHAR2(5) null +DONEBY NVARCHAR2(36) null +PETROLEUMORDERID NUMBER(22) null + +## PETROLEUMFEERETURN +ID NUMBER(22) notnull PK +INTERVALID NUMBER(22) null +COMPANYCODE NUMBER(22) null +VALUE NUMBER(22) null +TYPE NUMBER(22) null +NOTES NVARCHAR2(1500) null +WEIGHT NUMBER(22) null +CREATIONDATE DATE(7) null +CREATEDBY VARCHAR2(50) null +RELATEDINTERVAL NUMBER(22) null + +## PETROLEUMFEES +ID NUMBER(22) notnull PK +TYPENAME NVARCHAR2(300) null +FEE NUMBER(22) null +TAFQIT NVARCHAR2(300) null +CODE VARCHAR2(10) null + +## PETROLEUMINTERVALS +ID NUMBER(22) notnull PK +YEAR NUMBER(22) null +MONTH NUMBER(22) null +INTERVAL VARCHAR2(100) null +LOCKED NUMBER(22) null +LOCKEDBY VARCHAR2(15) null +LOCKEDDATE DATE(7) null +SUBINTERVAL NUMBER(22) null +CLAIMNO NUMBER(22) null +TENDERID NUMBER(22) null +WATERINTERVAL NUMBER(22) null + +## PETROLEUMORDER +ID NUMBER(22) notnull PK +SHIPMENTMODE NVARCHAR2(15) null +INBONDTYPECODE NVARCHAR2(15) null +FIRMS NVARCHAR2(60) null +ORIGINADDRESSID NUMBER(22) null +DESTINATIONADDRESSID NUMBER(22) null +TN NVARCHAR2(150) null +TRNAT NVARCHAR2(30) null +TRN NVARCHAR2(150) null +TT NVARCHAR2(150) null +ASRN NUMBER(22) null +CAN NUMBER(22) null +DRVR NVARCHAR2(450) null +CAT NUMBER(22) null +DLN NUMBER(22) null +DLED DATE(7) null +NAT NVARCHAR2(30) null +NNPN NUMBER(22) null +DONEBY NVARCHAR2(36) null +PN NUMBER(22) null +COMPANYCODE NUMBER(22) null +CREATIONDATE DATE(7) notnull +ROUTINGTEMPLATEID NUMBER(22) null +TRACKINGNO NUMBER(22) null +SHIPMENTSTATUSCODE VARCHAR2(5) null +REASON NCLOB(4000) null +LASTUPDATEDATE DATE(7) null +UPDATEDBY NVARCHAR2(36) null +WAITDONEBY VARCHAR2(12) null +WAITDATE DATE(7) null +CANCELREASON NVARCHAR2(3000) null +SUBSHIPMENTMODE VARCHAR2(10) null +FORMNO NUMBER(22) null +CANCELLEDPN NUMBER(22) null +OWNER_NNPN NUMBER(22) null +OWNER_NAME VARCHAR2(350) null + +## PETROLEUMPRICES +ID NUMBER(22) notnull PK +START_DATE DATE(7) null +END_DATE DATE(7) null +PRICE NUMBER(22) null +CREATIONDATE DATE(7) null +USERID VARCHAR2(12) null +ROADMNGPRICE NUMBER(22) null +TENDERMNGPRICE NUMBER(22) null +PERMITPRICE NUMBER(22) null +DRIVERTIP NUMBER(22) null + +## PETROLEUMQUOTA +ID NUMBER(22) notnull PK +QUOTADATE DATE(7) null +QUOTAVALUE NUMBER(22) null +DONEBY NVARCHAR2(36) null +ASRN NVARCHAR2(36) null + +## PETROLEUMREFINERY +ID NUMBER(22) notnull PK +SERIAL NUMBER(22) null +LOADDENSITY NUMBER(22) null +LOADWEIGHT NUMBER(22) null +DISCHDENSITY NUMBER(22) null +DISCHWEIGHT NUMBER(22) null +NETWEIGHT NUMBER(22) null +TN NUMBER(22) null +TRN NUMBER(22) null +POLICYNO NUMBER(22) null +COMPANYCODE NUMBER(22) null +DRVR NVARCHAR2(450) null +LOSS NUMBER(22) null +YEAR NUMBER(22) null +REQUESTSTATUS NUMBER(22) null +REQUESTBY VARCHAR2(15) null +REQUESTDATE DATE(7) null +LOSSTOLERANCE NUMBER(22) null +PENALTYFACTOR NUMBER(22) null +PENALTY NUMBER(22) null +TRNSWAGE NUMBER(22) null +REFINARYSHEET NUMBER(22) null +INTERVALID NUMBER(22) null +PENALTYSHEET NUMBER(22) null +UPLOADERROR VARCHAR2(1000) null +SEAWATER NUMBER(22) null +SEAWATERSHEET NUMBER(22) null +FORMNO NUMBER(22) null +RCOMPANYCODE NUMBER(22) null +PAYINTERVAL NUMBER(22) null +DISCHDATE DATE(7) null +LOADDATE DATE(7) null + +## PETROLEUMROUTING +ID NUMBER(22) notnull PK +ROUTINGTEMPLATENAME NVARCHAR2(180) null +ADDRESSID NUMBER(22) null +DISPORDER NUMBER(22) null +DESTINATIONADDRESSID NUMBER(22) null +SHIPMENTMODE VARCHAR2(10) null + +## PETROLEUMTENDER +ID NUMBER(22) notnull PK +FROMDATE DATE(7) notnull +TODATE DATE(7) notnull + +## PETROLEUMTRACKING +ID NUMBER(22) notnull PK +PETROLEUMORDERID NUMBER(22) null +LOCATIONID NUMBER(22) null +TRACKINGNO NUMBER(22) null +CREATIONDATE DATE(7) null + +## PETROLEUMVIOLIST +ID NUMBER(22) notnull PK +NAME NVARCHAR2(150) null + +## PET_TRUCKTYPE +CODE NVARCHAR2(150) notnull PK +CAPTION NVARCHAR2(300) null + +## PORTLETS +ID NUMBER(22) notnull PK +CAPTIONID NUMBER(22) null +TYPE NUMBER(22) null +TABLENAME VARCHAR2(50) null +DISPLAYCOLUMN VARCHAR2(50) null +VALUECOLUMN VARCHAR2(50) null +GROUPBYCOLUMN VARCHAR2(50) null +FILTERCOLUMN VARCHAR2(250) null +VIEWTOTAL NUMBER(22) null +ORDERCOLUMN VARCHAR2(50) null +CACHE NUMBER(22) null +DEFAULTFILTER VARCHAR2(250) null + +## PORTLET_CAPTIONS +ID NUMBER(22) notnull PK +LANGUAGE VARCHAR2(3) notnull +STRING VARCHAR2(50) notnull +CAPTION NVARCHAR2(150) notnull + +## PORTLET_DW1 +SHIPMENTID NUMBER(22) null +PN VARCHAR2(20) null +TN NVARCHAR2(150) null +TRN NVARCHAR2(150) null +TRNAT VARCHAR2(10) null +DRVR NVARCHAR2(1500) null +COMPCODE VARCHAR2(10) null +SHIPMENTMODE VARCHAR2(10) null +LASTUPDATETIMESTAMP DATE(7) null +SHIPMENTCHARGETYPECODE VARCHAR2(10) null +SHIPMENTSTATUSCODE VARCHAR2(10) null +INVOICINGDATE DATE(7) null +PERMITCREATIONDATE DATE(7) null +CHARGENAME VARCHAR2(10) null +TT VARCHAR2(25) null +SHIPMENTCHARGEID NUMBER(22) null +LASTSTOP DATE(7) null +ETA DATE(7) null +CURRENTLOCATION NUMBER(22) null +USERID VARCHAR2(10) null +CAN NUMBER(22) null +CAN2 NUMBER(22) null +RVKDREASON NVARCHAR2(1500) null + +## PORTLET_DW1_TEMP +SHIPMENTID NUMBER(22) null +PN VARCHAR2(20) null +TN NVARCHAR2(150) null +TRN NVARCHAR2(150) null +TRNAT VARCHAR2(10) null +DRVR NVARCHAR2(1500) null +COMPCODE VARCHAR2(10) null +SHIPMENTMODE VARCHAR2(10) null +LASTUPDATETIMESTAMP DATE(7) null +SHIPMENTCHARGETYPECODE VARCHAR2(10) null +SHIPMENTSTATUSCODE VARCHAR2(10) null +INVOICINGDATE DATE(7) null +PERMITCREATIONDATE DATE(7) null +CHARGENAME VARCHAR2(10) null +TT VARCHAR2(25) null +SHIPMENTCHARGEID NUMBER(22) null +LASTSTOP DATE(7) null +ETA DATE(7) null +CURRENTLOCATION NUMBER(22) null +USERID VARCHAR2(10) null +CAN NUMBER(22) null +CAN2 NUMBER(22) null +RVKDREASON NVARCHAR2(1500) null + +## PORTLET_DW2 +SHIPMENTID NUMBER(22) null +VIOLATIONSERIAL NVARCHAR2(300) null +VIOLATIONDATETIME DATE(7) null +VIOLATIONREASON NUMBER(22) null +VIOLATIONADDRESSID NUMBER(22) null +REMARKS NVARCHAR2(2700) null + +## PORTLET_DW2_TEMP +SHIPMENTID NUMBER(22) null +VIOLATIONSERIAL NVARCHAR2(300) null +VIOLATIONDATETIME DATE(7) null +VIOLATIONREASON NUMBER(22) null +VIOLATIONADDRESSID NUMBER(22) null +REMARKS NVARCHAR2(2700) null + +## PORTLET_DW3 +SHIPMENTID NUMBER(22) null +SHIPMENTCHARGEID NUMBER(22) null +SHIPMENTCHARGETYPECODE VARCHAR2(50) null +CHARGENAME VARCHAR2(50) null +INVOICINGDATE DATE(7) null + +## PORTLET_DW3_TEMP +SHIPMENTID NUMBER(22) null +SHIPMENTCHARGEID NUMBER(22) null +SHIPMENTCHARGETYPECODE VARCHAR2(50) null +CHARGENAME VARCHAR2(50) null +INVOICINGDATE DATE(7) null + +## PORTLET_FINANCE +ID NUMBER(22) notnull +COMPCODE VARCHAR2(10) notnull +DEBIT NUMBER(22) notnull +CREDIT NUMBER(22) notnull +LASTUPDATE DATE(7) null + +## PORTLET_SEARCH +ID NUMBER(22) notnull PK +PORTLETID NUMBER(22) notnull +FIELD VARCHAR2(20) notnull +FORMAT VARCHAR2(10) notnull +FIELD_CAPTION NVARCHAR2(600) null +FILTERCRITERIA VARCHAR2(200) null +ORDERCOLUMN VARCHAR2(50) null +COMBO_QUERY VARCHAR2(350) null +SEARCH_ALL NUMBER(22) null +SEARCH_ALL1 VARCHAR2(50) null + +## REFINARYSHEETS +ID NUMBER(22) notnull PK +UPLOADDATE DATE(7) null +ORIGINALNAME NVARCHAR2(300) null +FILENAME NVARCHAR2(300) null +TYPE NUMBER(22) null +FAILEDNO VARCHAR2(1000) null +DONEBY VARCHAR2(12) null + +## ROLES +CODE VARCHAR2(20) notnull PK +NAME NVARCHAR2(300) notnull +DIRECTMANAGER VARCHAR2(5) null +EMPLOYEES VARCHAR2(20) null +MANAGERS VARCHAR2(20) null +LEVELNUMBER NUMBER(22) null +ROLETYPE NVARCHAR2(150) null +TENDER VARCHAR2(20) null + +## SERVICES +ID NUMBER(22) notnull PK +NAME NVARCHAR2(300) null +NAME_AR NVARCHAR2(600) null + +## SERVICE_FEE +ID NUMBER(22) notnull PK +SERVICEID NUMBER(22) null +FEE_TYPE_ID NUMBER(22) null +NAME_EN NVARCHAR2(150) null +NAME_AR NVARCHAR2(150) null +DEFAULT_VAL NUMBER(22) null +MIN NUMBER(22) null +MAX NUMBER(22) null +DESCRIPTION NVARCHAR2(600) null + +## SERVICE_PARAMS +ID NUMBER(22) notnull PK +SERVICE_ID NUMBER(22) null +NAME NVARCHAR2(150) null +DESCRIPTION NVARCHAR2(600) null +VALUE NUMBER(22) null + +## SHIPING_LINES +ID NUMBER(22) notnull PK +INITIALS VARCHAR2(4) null +CODE VARCHAR2(4) null +NAME VARCHAR2(100) null + +## SHIPMENTMODE +CODE NVARCHAR2(30) notnull PK +CAPTION NVARCHAR2(300) null + +## STAKEHOLDER +ID NUMBER(22) notnull PK +NAME VARCHAR2(50) notnull +DESCRIPTION VARCHAR2(100) null +STATUS NUMBER(22) notnull + +## STATUS +CODE VARCHAR2(50) notnull PK +NAME NVARCHAR2(900) null +SORTORDER NUMBER(22) null + +## STATUS_ACTION_MATRIX +ID NUMBER(22) notnull PK +STATUSCODE VARCHAR2(50) null +OBJECTCODE VARCHAR2(50) notnull +ACTIONCODE NVARCHAR2(150) notnull +NEXTSTATUSCODE VARCHAR2(50) null +ROLECODE VARCHAR2(50) notnull +ISDEFAULT NUMBER(22) notnull +CAPTIONCODE VARCHAR2(50) null +RECORDSTATUS VARCHAR2(50) null +READONLYFIELDS VARCHAR2(400) null +ACTIONICON VARCHAR2(50) null +HTMLID VARCHAR2(50) null +HTMLCLASSES VARCHAR2(50) null +PLACE VARCHAR2(50) null +ORDERING VARCHAR2(50) null +FUNCTIONAME VARCHAR2(50) null + +## STATUS_ACTION_MATRIX_EXTEND +ID NUMBER(22) notnull PK +SAM_ID NUMBER(22) null +ENTITY_COLUMN_NAME NVARCHAR2(150) null +SESSION_KEY NVARCHAR2(150) null +VALUE VARCHAR2(30) null +RECORD_STATUS VARCHAR2(20) null +VALUE_TO_EXCLUDE NVARCHAR2(150) null +TYPE_TO_EXCLUDE NVARCHAR2(150) null +ENTITY_TYPE_TO_EXCLUDE NVARCHAR2(150) null + +## SUBSHIPMENTMODE +CODE NVARCHAR2(30) notnull PK +CAPTION NVARCHAR2(300) null +DISPORDER NUMBER(22) null +SHIPMENTMODE NVARCHAR2(30) null + +## SURVEY_ANSWERS_SETUP +ID NUMBER(22) notnull PK +SURVEY_ID NUMBER(22) notnull +QUESTION_ID NUMBER(22) notnull +VALUE NVARCHAR2(750) null + +## SURVEY_GROUP_SETUP +ID NUMBER(22) notnull PK +SURVEY_ID NUMBER(22) notnull +NAME VARCHAR2(255) null + +## SURVEY_QUESTIONS_SETUP +ID NUMBER(22) notnull PK +SURVEY_ID NUMBER(22) notnull +QUESTION NVARCHAR2(4000) notnull +NOTES NVARCHAR2(765) null +ANSWER_TYPE VARCHAR2(20) null +GROUP_ID NUMBER(22) null + +## SURVEY_SETUP +ID NUMBER(22) notnull PK +CREATION_DATE DATE(7) notnull +STATUS_CODE VARCHAR2(20) notnull +ROLE_CODES VARCHAR2(255) notnull +NAME VARCHAR2(255) notnull +NOTES VARCHAR2(255) null + +## SURVEY_USER_RESPONSE +ID NUMBER(22) notnull PK +USER_ID VARCHAR2(50) null +SURVEY_ID NUMBER(22) null +QUESTION_ID NUMBER(22) null +ANSWER_ID NUMBER(22) null +VALUE VARCHAR2(150) null +BULK_ANSWER_ID VARCHAR2(100) null +ISPROCESSED NUMBER(22) null + +## SYSTEM_ERRORS +ID NUMBER(22) notnull PK +ERROR CLOB(4000) notnull +ERRORDATE DATE(7) notnull +IPADDRESS VARCHAR2(15) notnull +USERID VARCHAR2(50) null +BROWSER VARCHAR2(200) null + +## SYSTEM_USER_LOG +ID NUMBER(22) notnull +ERROR VARCHAR2(4000) null +ERRORDATE DATE(7) notnull +IPADDRESS VARCHAR2(15) notnull +URI VARCHAR2(4000) null +USERID VARCHAR2(50) null +SESSIONID VARCHAR2(500) null +FORM VARCHAR2(4000) null + +## SYSTEM_VARIABLES +ID NUMBER(22) notnull PK +NAME NVARCHAR2(600) null +VALUE CLOB(4000) null + +## SYS_EXPORT_SCHEMA_01 +PROCESS_ORDER NUMBER(22) null +DUPLICATE NUMBER(22) null +DUMP_FILEID NUMBER(22) null +DUMP_POSITION NUMBER(22) null +DUMP_LENGTH NUMBER(22) null +DUMP_ALLOCATION NUMBER(22) null +COMPLETED_ROWS NUMBER(22) null +ERROR_COUNT NUMBER(22) null +ELAPSED_TIME NUMBER(22) null +OBJECT_TYPE_PATH VARCHAR2(200) null +OBJECT_PATH_SEQNO NUMBER(22) null +OBJECT_TYPE VARCHAR2(30) null +IN_PROGRESS CHAR(1) null +OBJECT_NAME VARCHAR2(500) null +OBJECT_LONG_NAME VARCHAR2(4000) null +OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_SCHEMA VARCHAR2(30) null +PARTITION_NAME VARCHAR2(30) null +SUBPARTITION_NAME VARCHAR2(30) null +FLAGS NUMBER(22) null +PROPERTY NUMBER(22) null +COMPLETION_TIME DATE(7) null +OBJECT_TABLESPACE VARCHAR2(30) null +SIZE_ESTIMATE NUMBER(22) null +OBJECT_ROW NUMBER(22) null +PROCESSING_STATE CHAR(1) null +PROCESSING_STATUS CHAR(1) null +BASE_PROCESS_ORDER NUMBER(22) null +BASE_OBJECT_TYPE VARCHAR2(30) null +BASE_OBJECT_NAME VARCHAR2(30) null +BASE_OBJECT_SCHEMA VARCHAR2(30) null +ANCESTOR_PROCESS_ORDER NUMBER(22) null +DOMAIN_PROCESS_ORDER NUMBER(22) null +PARALLELIZATION NUMBER(22) null +UNLOAD_METHOD NUMBER(22) null +GRANULES NUMBER(22) null +SCN NUMBER(22) null +GRANTOR VARCHAR2(30) null +XML_CLOB CLOB(4000) null +NAME VARCHAR2(30) null +VALUE_T VARCHAR2(4000) null +VALUE_N NUMBER(22) null +IS_DEFAULT NUMBER(22) null +FILE_TYPE NUMBER(22) null +USER_DIRECTORY VARCHAR2(4000) null +USER_FILE_NAME VARCHAR2(4000) null +FILE_NAME VARCHAR2(4000) null +EXTEND_SIZE NUMBER(22) null +FILE_MAX_SIZE NUMBER(22) null +PROCESS_NAME VARCHAR2(30) null +LAST_UPDATE DATE(7) null +WORK_ITEM VARCHAR2(30) null +OBJECT_NUMBER NUMBER(22) null +COMPLETED_BYTES NUMBER(22) null +TOTAL_BYTES NUMBER(22) null +METADATA_IO NUMBER(22) null +DATA_IO NUMBER(22) null +CUMULATIVE_TIME NUMBER(22) null +PACKET_NUMBER NUMBER(22) null +OLD_VALUE VARCHAR2(4000) null +SEED NUMBER(22) null +LAST_FILE NUMBER(22) null +USER_NAME VARCHAR2(30) null +OPERATION VARCHAR2(30) null +JOB_MODE VARCHAR2(30) null +CONTROL_QUEUE VARCHAR2(30) null +STATUS_QUEUE VARCHAR2(30) null +REMOTE_LINK VARCHAR2(4000) null +VERSION NUMBER(22) null +DB_VERSION VARCHAR2(30) null +TIMEZONE VARCHAR2(64) null +STATE VARCHAR2(30) null +PHASE NUMBER(22) null +GUID RAW(16) null +START_TIME DATE(7) null +BLOCK_SIZE NUMBER(22) null +METADATA_BUFFER_SIZE NUMBER(22) null +DATA_BUFFER_SIZE NUMBER(22) null +DEGREE NUMBER(22) null +PLATFORM VARCHAR2(101) null +ABORT_STEP NUMBER(22) null +INSTANCE VARCHAR2(60) null + +## SYS_EXPORT_SCHEMA_02 +PROCESS_ORDER NUMBER(22) null +DUPLICATE NUMBER(22) null +DUMP_FILEID NUMBER(22) null +DUMP_POSITION NUMBER(22) null +DUMP_LENGTH NUMBER(22) null +DUMP_ORIG_LENGTH NUMBER(22) null +DUMP_ALLOCATION NUMBER(22) null +COMPLETED_ROWS NUMBER(22) null +ERROR_COUNT NUMBER(22) null +ELAPSED_TIME NUMBER(22) null +OBJECT_TYPE_PATH VARCHAR2(200) null +OBJECT_PATH_SEQNO NUMBER(22) null +OBJECT_TYPE VARCHAR2(30) null +IN_PROGRESS CHAR(1) null +OBJECT_NAME VARCHAR2(500) null +OBJECT_LONG_NAME VARCHAR2(4000) null +OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_NAME VARCHAR2(4000) null +PARTITION_NAME VARCHAR2(30) null +SUBPARTITION_NAME VARCHAR2(30) null +DATAOBJ_NUM NUMBER(22) null +FLAGS NUMBER(22) null +PROPERTY NUMBER(22) null +TRIGFLAG NUMBER(22) null +CREATION_LEVEL NUMBER(22) null +COMPLETION_TIME DATE(7) null +OBJECT_TABLESPACE VARCHAR2(30) null +SIZE_ESTIMATE NUMBER(22) null +OBJECT_ROW NUMBER(22) null +PROCESSING_STATE CHAR(1) null +PROCESSING_STATUS CHAR(1) null +BASE_PROCESS_ORDER NUMBER(22) null +BASE_OBJECT_TYPE VARCHAR2(30) null +BASE_OBJECT_NAME VARCHAR2(30) null +BASE_OBJECT_SCHEMA VARCHAR2(30) null +ANCESTOR_PROCESS_ORDER NUMBER(22) null +DOMAIN_PROCESS_ORDER NUMBER(22) null +PARALLELIZATION NUMBER(22) null +UNLOAD_METHOD NUMBER(22) null +LOAD_METHOD NUMBER(22) null +GRANULES NUMBER(22) null +SCN NUMBER(22) null +GRANTOR VARCHAR2(30) null +XML_CLOB CLOB(4000) null +PARENT_PROCESS_ORDER NUMBER(22) null +NAME VARCHAR2(30) null +VALUE_T VARCHAR2(4000) null +VALUE_N NUMBER(22) null +IS_DEFAULT NUMBER(22) null +FILE_TYPE NUMBER(22) null +USER_DIRECTORY VARCHAR2(4000) null +USER_FILE_NAME VARCHAR2(4000) null +FILE_NAME VARCHAR2(4000) null +EXTEND_SIZE NUMBER(22) null +FILE_MAX_SIZE NUMBER(22) null +PROCESS_NAME VARCHAR2(30) null +LAST_UPDATE DATE(7) null +WORK_ITEM VARCHAR2(30) null +OBJECT_NUMBER NUMBER(22) null +COMPLETED_BYTES NUMBER(22) null +TOTAL_BYTES NUMBER(22) null +METADATA_IO NUMBER(22) null +DATA_IO NUMBER(22) null +CUMULATIVE_TIME NUMBER(22) null +PACKET_NUMBER NUMBER(22) null +INSTANCE_ID NUMBER(22) null +OLD_VALUE VARCHAR2(4000) null +SEED NUMBER(22) null +LAST_FILE NUMBER(22) null +USER_NAME VARCHAR2(30) null +OPERATION VARCHAR2(30) null +JOB_MODE VARCHAR2(30) null +QUEUE_TABNUM NUMBER(22) null +CONTROL_QUEUE VARCHAR2(30) null +STATUS_QUEUE VARCHAR2(30) null +REMOTE_LINK VARCHAR2(4000) null +VERSION NUMBER(22) null +JOB_VERSION VARCHAR2(30) null +DB_VERSION VARCHAR2(30) null +TIMEZONE VARCHAR2(64) null +STATE VARCHAR2(30) null +PHASE NUMBER(22) null +GUID RAW(16) null +START_TIME DATE(7) null +BLOCK_SIZE NUMBER(22) null +METADATA_BUFFER_SIZE NUMBER(22) null +DATA_BUFFER_SIZE NUMBER(22) null +DEGREE NUMBER(22) null +PLATFORM VARCHAR2(101) null +ABORT_STEP NUMBER(22) null +INSTANCE VARCHAR2(60) null +CLUSTER_OK NUMBER(22) null +SERVICE_NAME VARCHAR2(100) null +OBJECT_INT_OID VARCHAR2(32) null + +## SYS_EXPORT_SCHEMA_03 +PROCESS_ORDER NUMBER(22) null +DUPLICATE NUMBER(22) null +DUMP_FILEID NUMBER(22) null +DUMP_POSITION NUMBER(22) null +DUMP_LENGTH NUMBER(22) null +DUMP_ORIG_LENGTH NUMBER(22) null +DUMP_ALLOCATION NUMBER(22) null +COMPLETED_ROWS NUMBER(22) null +ERROR_COUNT NUMBER(22) null +ELAPSED_TIME NUMBER(22) null +OBJECT_TYPE_PATH VARCHAR2(200) null +OBJECT_PATH_SEQNO NUMBER(22) null +OBJECT_TYPE VARCHAR2(30) null +IN_PROGRESS CHAR(1) null +OBJECT_NAME VARCHAR2(500) null +OBJECT_LONG_NAME VARCHAR2(4000) null +OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_NAME VARCHAR2(4000) null +PARTITION_NAME VARCHAR2(30) null +SUBPARTITION_NAME VARCHAR2(30) null +DATAOBJ_NUM NUMBER(22) null +FLAGS NUMBER(22) null +PROPERTY NUMBER(22) null +TRIGFLAG NUMBER(22) null +CREATION_LEVEL NUMBER(22) null +COMPLETION_TIME DATE(7) null +OBJECT_TABLESPACE VARCHAR2(30) null +SIZE_ESTIMATE NUMBER(22) null +OBJECT_ROW NUMBER(22) null +PROCESSING_STATE CHAR(1) null +PROCESSING_STATUS CHAR(1) null +BASE_PROCESS_ORDER NUMBER(22) null +BASE_OBJECT_TYPE VARCHAR2(30) null +BASE_OBJECT_NAME VARCHAR2(30) null +BASE_OBJECT_SCHEMA VARCHAR2(30) null +ANCESTOR_PROCESS_ORDER NUMBER(22) null +DOMAIN_PROCESS_ORDER NUMBER(22) null +PARALLELIZATION NUMBER(22) null +UNLOAD_METHOD NUMBER(22) null +LOAD_METHOD NUMBER(22) null +GRANULES NUMBER(22) null +SCN NUMBER(22) null +GRANTOR VARCHAR2(30) null +XML_CLOB CLOB(4000) null +PARENT_PROCESS_ORDER NUMBER(22) null +NAME VARCHAR2(30) null +VALUE_T VARCHAR2(4000) null +VALUE_N NUMBER(22) null +IS_DEFAULT NUMBER(22) null +FILE_TYPE NUMBER(22) null +USER_DIRECTORY VARCHAR2(4000) null +USER_FILE_NAME VARCHAR2(4000) null +FILE_NAME VARCHAR2(4000) null +EXTEND_SIZE NUMBER(22) null +FILE_MAX_SIZE NUMBER(22) null +PROCESS_NAME VARCHAR2(30) null +LAST_UPDATE DATE(7) null +WORK_ITEM VARCHAR2(30) null +OBJECT_NUMBER NUMBER(22) null +COMPLETED_BYTES NUMBER(22) null +TOTAL_BYTES NUMBER(22) null +METADATA_IO NUMBER(22) null +DATA_IO NUMBER(22) null +CUMULATIVE_TIME NUMBER(22) null +PACKET_NUMBER NUMBER(22) null +INSTANCE_ID NUMBER(22) null +OLD_VALUE VARCHAR2(4000) null +SEED NUMBER(22) null +LAST_FILE NUMBER(22) null +USER_NAME VARCHAR2(30) null +OPERATION VARCHAR2(30) null +JOB_MODE VARCHAR2(30) null +QUEUE_TABNUM NUMBER(22) null +CONTROL_QUEUE VARCHAR2(30) null +STATUS_QUEUE VARCHAR2(30) null +REMOTE_LINK VARCHAR2(4000) null +VERSION NUMBER(22) null +JOB_VERSION VARCHAR2(30) null +DB_VERSION VARCHAR2(30) null +TIMEZONE VARCHAR2(64) null +STATE VARCHAR2(30) null +PHASE NUMBER(22) null +GUID RAW(16) null +START_TIME DATE(7) null +BLOCK_SIZE NUMBER(22) null +METADATA_BUFFER_SIZE NUMBER(22) null +DATA_BUFFER_SIZE NUMBER(22) null +DEGREE NUMBER(22) null +PLATFORM VARCHAR2(101) null +ABORT_STEP NUMBER(22) null +INSTANCE VARCHAR2(60) null +CLUSTER_OK NUMBER(22) null +SERVICE_NAME VARCHAR2(100) null +OBJECT_INT_OID VARCHAR2(32) null + +## SYS_EXPORT_SCHEMA_04 +PROCESS_ORDER NUMBER(22) null +DUPLICATE NUMBER(22) null +DUMP_FILEID NUMBER(22) null +DUMP_POSITION NUMBER(22) null +DUMP_LENGTH NUMBER(22) null +DUMP_ORIG_LENGTH NUMBER(22) null +DUMP_ALLOCATION NUMBER(22) null +COMPLETED_ROWS NUMBER(22) null +ERROR_COUNT NUMBER(22) null +ELAPSED_TIME NUMBER(22) null +OBJECT_TYPE_PATH VARCHAR2(200) null +OBJECT_PATH_SEQNO NUMBER(22) null +OBJECT_TYPE VARCHAR2(30) null +IN_PROGRESS CHAR(1) null +OBJECT_NAME VARCHAR2(500) null +OBJECT_LONG_NAME VARCHAR2(4000) null +OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_NAME VARCHAR2(4000) null +PARTITION_NAME VARCHAR2(30) null +SUBPARTITION_NAME VARCHAR2(30) null +DATAOBJ_NUM NUMBER(22) null +FLAGS NUMBER(22) null +PROPERTY NUMBER(22) null +TRIGFLAG NUMBER(22) null +CREATION_LEVEL NUMBER(22) null +COMPLETION_TIME DATE(7) null +OBJECT_TABLESPACE VARCHAR2(30) null +SIZE_ESTIMATE NUMBER(22) null +OBJECT_ROW NUMBER(22) null +PROCESSING_STATE CHAR(1) null +PROCESSING_STATUS CHAR(1) null +BASE_PROCESS_ORDER NUMBER(22) null +BASE_OBJECT_TYPE VARCHAR2(30) null +BASE_OBJECT_NAME VARCHAR2(30) null +BASE_OBJECT_SCHEMA VARCHAR2(30) null +ANCESTOR_PROCESS_ORDER NUMBER(22) null +DOMAIN_PROCESS_ORDER NUMBER(22) null +PARALLELIZATION NUMBER(22) null +UNLOAD_METHOD NUMBER(22) null +LOAD_METHOD NUMBER(22) null +GRANULES NUMBER(22) null +SCN NUMBER(22) null +GRANTOR VARCHAR2(30) null +XML_CLOB CLOB(4000) null +PARENT_PROCESS_ORDER NUMBER(22) null +NAME VARCHAR2(30) null +VALUE_T VARCHAR2(4000) null +VALUE_N NUMBER(22) null +IS_DEFAULT NUMBER(22) null +FILE_TYPE NUMBER(22) null +USER_DIRECTORY VARCHAR2(4000) null +USER_FILE_NAME VARCHAR2(4000) null +FILE_NAME VARCHAR2(4000) null +EXTEND_SIZE NUMBER(22) null +FILE_MAX_SIZE NUMBER(22) null +PROCESS_NAME VARCHAR2(30) null +LAST_UPDATE DATE(7) null +WORK_ITEM VARCHAR2(30) null +OBJECT_NUMBER NUMBER(22) null +COMPLETED_BYTES NUMBER(22) null +TOTAL_BYTES NUMBER(22) null +METADATA_IO NUMBER(22) null +DATA_IO NUMBER(22) null +CUMULATIVE_TIME NUMBER(22) null +PACKET_NUMBER NUMBER(22) null +INSTANCE_ID NUMBER(22) null +OLD_VALUE VARCHAR2(4000) null +SEED NUMBER(22) null +LAST_FILE NUMBER(22) null +USER_NAME VARCHAR2(30) null +OPERATION VARCHAR2(30) null +JOB_MODE VARCHAR2(30) null +QUEUE_TABNUM NUMBER(22) null +CONTROL_QUEUE VARCHAR2(30) null +STATUS_QUEUE VARCHAR2(30) null +REMOTE_LINK VARCHAR2(4000) null +VERSION NUMBER(22) null +JOB_VERSION VARCHAR2(30) null +DB_VERSION VARCHAR2(30) null +TIMEZONE VARCHAR2(64) null +STATE VARCHAR2(30) null +PHASE NUMBER(22) null +GUID RAW(16) null +START_TIME DATE(7) null +BLOCK_SIZE NUMBER(22) null +METADATA_BUFFER_SIZE NUMBER(22) null +DATA_BUFFER_SIZE NUMBER(22) null +DEGREE NUMBER(22) null +PLATFORM VARCHAR2(101) null +ABORT_STEP NUMBER(22) null +INSTANCE VARCHAR2(60) null +CLUSTER_OK NUMBER(22) null +SERVICE_NAME VARCHAR2(100) null +OBJECT_INT_OID VARCHAR2(32) null + +## SYS_EXPORT_SCHEMA_05 +PROCESS_ORDER NUMBER(22) null +DUPLICATE NUMBER(22) null +DUMP_FILEID NUMBER(22) null +DUMP_POSITION NUMBER(22) null +DUMP_LENGTH NUMBER(22) null +DUMP_ORIG_LENGTH NUMBER(22) null +DUMP_ALLOCATION NUMBER(22) null +COMPLETED_ROWS NUMBER(22) null +ERROR_COUNT NUMBER(22) null +ELAPSED_TIME NUMBER(22) null +OBJECT_TYPE_PATH VARCHAR2(200) null +OBJECT_PATH_SEQNO NUMBER(22) null +OBJECT_TYPE VARCHAR2(30) null +IN_PROGRESS CHAR(1) null +OBJECT_NAME VARCHAR2(500) null +OBJECT_LONG_NAME VARCHAR2(4000) null +OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_SCHEMA VARCHAR2(30) null +ORIGINAL_OBJECT_NAME VARCHAR2(4000) null +PARTITION_NAME VARCHAR2(30) null +SUBPARTITION_NAME VARCHAR2(30) null +DATAOBJ_NUM NUMBER(22) null +FLAGS NUMBER(22) null +PROPERTY NUMBER(22) null +TRIGFLAG NUMBER(22) null +CREATION_LEVEL NUMBER(22) null +COMPLETION_TIME DATE(7) null +OBJECT_TABLESPACE VARCHAR2(30) null +SIZE_ESTIMATE NUMBER(22) null +OBJECT_ROW NUMBER(22) null +PROCESSING_STATE CHAR(1) null +PROCESSING_STATUS CHAR(1) null +BASE_PROCESS_ORDER NUMBER(22) null +BASE_OBJECT_TYPE VARCHAR2(30) null +BASE_OBJECT_NAME VARCHAR2(30) null +BASE_OBJECT_SCHEMA VARCHAR2(30) null +ANCESTOR_PROCESS_ORDER NUMBER(22) null +DOMAIN_PROCESS_ORDER NUMBER(22) null +PARALLELIZATION NUMBER(22) null +UNLOAD_METHOD NUMBER(22) null +LOAD_METHOD NUMBER(22) null +GRANULES NUMBER(22) null +SCN NUMBER(22) null +GRANTOR VARCHAR2(30) null +XML_CLOB CLOB(4000) null +PARENT_PROCESS_ORDER NUMBER(22) null +NAME VARCHAR2(30) null +VALUE_T VARCHAR2(4000) null +VALUE_N NUMBER(22) null +IS_DEFAULT NUMBER(22) null +FILE_TYPE NUMBER(22) null +USER_DIRECTORY VARCHAR2(4000) null +USER_FILE_NAME VARCHAR2(4000) null +FILE_NAME VARCHAR2(4000) null +EXTEND_SIZE NUMBER(22) null +FILE_MAX_SIZE NUMBER(22) null +PROCESS_NAME VARCHAR2(30) null +LAST_UPDATE DATE(7) null +WORK_ITEM VARCHAR2(30) null +OBJECT_NUMBER NUMBER(22) null +COMPLETED_BYTES NUMBER(22) null +TOTAL_BYTES NUMBER(22) null +METADATA_IO NUMBER(22) null +DATA_IO NUMBER(22) null +CUMULATIVE_TIME NUMBER(22) null +PACKET_NUMBER NUMBER(22) null +INSTANCE_ID NUMBER(22) null +OLD_VALUE VARCHAR2(4000) null +SEED NUMBER(22) null +LAST_FILE NUMBER(22) null +USER_NAME VARCHAR2(30) null +OPERATION VARCHAR2(30) null +JOB_MODE VARCHAR2(30) null +QUEUE_TABNUM NUMBER(22) null +CONTROL_QUEUE VARCHAR2(30) null +STATUS_QUEUE VARCHAR2(30) null +REMOTE_LINK VARCHAR2(4000) null +VERSION NUMBER(22) null +JOB_VERSION VARCHAR2(30) null +DB_VERSION VARCHAR2(30) null +TIMEZONE VARCHAR2(64) null +STATE VARCHAR2(30) null +PHASE NUMBER(22) null +GUID RAW(16) null +START_TIME DATE(7) null +BLOCK_SIZE NUMBER(22) null +METADATA_BUFFER_SIZE NUMBER(22) null +DATA_BUFFER_SIZE NUMBER(22) null +DEGREE NUMBER(22) null +PLATFORM VARCHAR2(101) null +ABORT_STEP NUMBER(22) null +INSTANCE VARCHAR2(60) null +CLUSTER_OK NUMBER(22) null +SERVICE_NAME VARCHAR2(100) null +OBJECT_INT_OID VARCHAR2(32) null + +## TABLE_CRMUSERS +USERID VARCHAR2(50) null +SYSTEMROLECODE VARCHAR2(50) null +CONTACTID NUMBER(22) null +CONTACTNAME NVARCHAR2(1500) null +ORGID NUMBER(22) null +ORGNAME NVARCHAR2(1500) null +EMPNO VARCHAR2(50) null +COMPANYCODE VARCHAR2(50) null +PASSPHRASEHASH VARCHAR2(200) null +STATUS VARCHAR2(50) null + +## TAGGING_SESSIONS +ID NUMBER(22) notnull PK +USERID VARCHAR2(20) null +SESSIONSTART DATE(7) null +SESSIONEND DATE(7) null +SESSIONVARIABLES CLOB(4000) null + +## TEMP_COMP +SCAC NVARCHAR2(300) null +BILLING_NUMBER VARCHAR2(20) null +COMPANY_NAME NVARCHAR2(900) null + +## TEMP_DATA +COL1 NVARCHAR2(150) null + +## TEMP_DATA2 +COL1 NVARCHAR2(150) null + +## TEMP_MOBILE +NNPN VARCHAR2(100) null +NOTE NVARCHAR2(765) null + +## TEMP_SAM +ID NUMBER(22) notnull +STATUSCODE VARCHAR2(50) null +OBJECTCODE VARCHAR2(50) notnull +ACTIONCODE NVARCHAR2(150) notnull +NEXTSTATUSCODE VARCHAR2(50) null +ROLECODE VARCHAR2(50) notnull +ISDEFAULT NUMBER(22) notnull +CAPTIONCODE VARCHAR2(50) null +RECORDSTATUS VARCHAR2(50) null +READONLYFIELDS VARCHAR2(250) null +ACTIONICON VARCHAR2(50) null +HTMLID VARCHAR2(50) null +HTMLCLASSES VARCHAR2(50) null +PLACE VARCHAR2(50) null +ORDERING VARCHAR2(50) null +FUNCTIONAME VARCHAR2(50) null + +## TICKETS +ID NUMBER(22) notnull PK +SUMMARY VARCHAR2(2000) notnull +DETAILS VARCHAR2(2000) notnull +SEVERITY NUMBER(22) notnull +SYSTEM NUMBER(22) notnull +ERRORMSG VARCHAR2(1000) null +NOTES VARCHAR2(1000) null +CREATEUSERID VARCHAR2(20) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(20) null +LASTUPDATETIMESTAMP DATE(7) null +WFID NUMBER(22) notnull + +## TICKETSRESP_FILES +ID NUMBER(22) notnull PK +RESPAPPID NUMBER(22) null +ORIGINALNAME NVARCHAR2(300) null +FILENAME VARCHAR2(100) null + +## TICKETS_CATEGORY +ID NUMBER(22) notnull PK +DESCRIPTION NVARCHAR2(300) notnull +PARENT NUMBER(22) notnull +SENTTO VARCHAR2(1000) null + +## TICKETS_FILES +ID NUMBER(22) notnull PK +TICKETID NUMBER(22) null +ORIGINALNAME NVARCHAR2(300) null +FILENAME VARCHAR2(100) null + +## TICKETS_RESPONSE +ID NUMBER(22) notnull PK +TICKETID NUMBER(22) notnull +USERID VARCHAR2(20) notnull +RESPONSE VARCHAR2(2500) notnull +LEVELNO NUMBER(22) notnull +RESPONSEDATE DATE(7) notnull + +## TICKETS_SOLUTION +ID NUMBER(22) notnull PK +TICKETID NUMBER(22) notnull +SAMMARY VARCHAR2(1000) notnull +SOLUTION VARCHAR2(1000) notnull +CREATEUSERID VARCHAR2(20) notnull +CREATETIMESTAMP DATE(7) notnull +LASTUPDATEUSERID VARCHAR2(20) null +LASTUPDATETIMESTAMP DATE(7) null +DESCRIPTION VARCHAR2(1000) notnull +CATEGORY NUMBER(22) null +TICKETNO NUMBER(22) null +VIEWS NUMBER(22) null +USEFUL NUMBER(22) null + +## TMP +CODE NUMBER(22) null +NAME NVARCHAR2(600) null +TRUCKS NUMBER(22) null + +## TRANSACTIONS +ID NUMBER(22) notnull PK +SRVCID NUMBER(22) notnull +APPREFID NUMBER(22) notnull +DONEBY VARCHAR2(10) notnull +TXDATE DATE(7) notnull +COMPANYID NUMBER(22) null + +## TRUCKTYPE +ID NUMBER(22) notnull PK +NAME NVARCHAR2(150) null + +## TRUCK_COUNTER +TRUCK_ID NUMBER(22) notnull +FILENAME NVARCHAR2(300) notnull +LOCATION NUMBER(22) notnull +TIMESTAMP DATE(7) notnull +TYPE VARCHAR2(5) notnull +CREATIONDATE DATE(7) notnull + +## T_CRM_COMPANY_CONTACT_INFO +COMPCODE VARCHAR2(10) null +ADDRESS NVARCHAR2(1500) null +PHONE NVARCHAR2(1500) null +MOB NVARCHAR2(1500) null +FAX NVARCHAR2(1500) null +EMAIL NVARCHAR2(1500) null + +## URL_SECURITY +URL VARCHAR2(500) null +ALLOWEDROLES VARCHAR2(500) null + +## USERDEVICEINFO +ID NUMBER(22) notnull PK +USERID NUMBER(22) null +UDID VARCHAR2(250) null +DEVICEID VARCHAR2(100) null +OS VARCHAR2(100) null +OSVERSION VARCHAR2(100) null +STATUSCODE VARCHAR2(20) null +TOKEN VARCHAR2(500) null +FCMTOKEN VARCHAR2(500) null +CREATIONDATE DATE(7) notnull +UPDATEDATE DATE(7) null +APPVERSION VARCHAR2(100) null + +## USER_ACTION_LOG +ID NUMBER(22) notnull PK +ACTION VARCHAR2(50) notnull +USER_ID VARCHAR2(50) notnull +CREATION_DATE DATE(7) notnull + +## USER_SMS_LOGS +ID NUMBER(22) notnull PK +USERLOGIN VARCHAR2(100) notnull +DATETIME DATE(7) notnull +STATUS VARCHAR2(100) notnull +MSG_REQUEST NVARCHAR2(1500) null +MSG_RESPONSE NVARCHAR2(4000) null +MOBILENO VARCHAR2(100) null +SERVICETYPE VARCHAR2(100) null +SMSPROVIDER VARCHAR2(100) null + +## VILLAGES +ID NUMBER(22) notnull PK +NAME VARCHAR2(50) null +CITYID NUMBER(22) null + +## VIOLATION_REASON +CODE NUMBER(22) null +REASON NVARCHAR2(3000) null +STATUS VARCHAR2(50) null +DOMAINNAME VARCHAR2(50) null + +## VOUCHERS +ID NUMBER(22) notnull PK +FEES NUMBER(22) notnull +WFID NUMBER(22) notnull +CREATEDBY NVARCHAR2(150) notnull +CREATIONTIMESTAMP DATE(7) notnull +CHECKNUMBER NUMBER(22) null +BANKID NUMBER(22) null + +## VOUCHERS_FILES +ID NUMBER(22) notnull PK +VOUCHERID NUMBER(22) null +ORIGINALNAME NVARCHAR2(150) null +FILENAME NVARCHAR2(150) null + +## VOUCHERS_RESPONSE +ID NUMBER(22) notnull PK +VOUCHERID NUMBER(22) null +SUPERVISORID VARCHAR2(50) null +SUPERVISORCOMMENT NCLOB(4000) null +LEVELNO NUMBER(22) null +RESPONSEDATE DATE(7) null +DECISIONDIR NUMBER(22) null + +## WEBSITE_CAPTIONS +ID NUMBER(22) notnull PK +CAPTION_INDEX NUMBER(22) notnull +CAPTION NVARCHAR2(900) notnull +LANG NVARCHAR2(9) notnull + +## WF +ID NUMBER(22) notnull PK +DONEBY VARCHAR2(10) null +STATUSID NUMBER(22) null +CREATIONDATE DATE(7) null +ASSIGNEDTO VARCHAR2(13) null +TYPEID NUMBER(22) null +LASTUPDATEDATE DATE(7) null +ASSIGNEDTOROLE VARCHAR2(5) null +TRACKNO NUMBER(22) null +PROCESSFLAG NUMBER(22) null +COMPANYID_OLD VARCHAR2(10) null +QUEUE NUMBER(22) null +COMPANYID VARCHAR2(10) null +LASTUPDATEUSERID VARCHAR2(10) null + +## WF_ACTIONS +ID NUMBER(22) notnull PK +SERVICEID NUMBER(22) notnull +FORMID NUMBER(22) notnull +ACTIONS CLOB(4000) notnull +FORMNAME NVARCHAR2(150) notnull + +## WF_LOG +ID NUMBER(22) notnull PK +WFID NUMBER(22) notnull +USERID VARCHAR2(50) notnull +STARTTIME DATE(7) notnull +ENDTIME DATE(7) null +STARTSTATUS NUMBER(22) notnull +ENDSTATUS NUMBER(22) null +CLOSED NUMBER(22) notnull +ROLE VARCHAR2(8) null + +## YARDS +ID NUMBER(22) notnull PK +NAME NVARCHAR2(150) notnull + +## YARDSNOTIFY +ID NUMBER(22) notnull PK +SENDERID NUMBER(22) null +SENDERCOMMENT NCLOB(4000) null +SHIFT NUMBER(22) null +YARDNO NUMBER(22) null +CLAIMTYPE NUMBER(22) null +CREATIONDATE DATE(7) null +WFID NUMBER(22) null +SENT NUMBER(22) notnull +COMPANYNAME NVARCHAR2(1500) null +NOTE NCLOB(4000) null + +## YARDSNOTIFY_DETAILS +ID NUMBER(22) notnull PK +MASTERNOTIFYID NUMBER(22) notnull +PERMITNO NUMBER(22) null +TRUCKNO NUMBER(22) null +DRIVERNAME NVARCHAR2(300) null +YARDNO NUMBER(22) null +CANCELREASON NVARCHAR2(900) null +RELEASENO1 NVARCHAR2(60) null +RELEASENO2 NVARCHAR2(60) null +TRAILERNO NVARCHAR2(60) null +TRUCKNATIONALITY NVARCHAR2(150) null +CARGOTYPE NVARCHAR2(60) null +ENTRANCEREASONS NVARCHAR2(60) null +FACITYDATE NVARCHAR2(30) null +FACITYHUR NVARCHAR2(15) null +FACITYDURATION NVARCHAR2(30) null +FACITYREASONS NVARCHAR2(300) null +CLEARNAME NVARCHAR2(75) null + +## SEQUENCES +BLOCKED_USERS_SERVICESSEQ, LOGINAUDITSEQ, MOBILENOTIFICATIONID, MOBILE_ERRORSID, MOBILE_SESSIONSID, MOBILE_USER_INQUIRY_SEQ, SEQ_ACTIONS, SEQ_APPLICATION_ACTIONS, SEQ_APPLICATION_STATUS, SEQ_APPLICATION_TYPES, SEQ_ATTACHMENTS, SEQ_BILLING, SEQ_CARGOTYPE, SEQ_CLAIMSAPP_DETAILS, SEQ_CLAIMSAPP_FILES, SEQ_CLAIMSAPP_MASTER, SEQ_CLAIMSAPP_REASONS, SEQ_CLAIMSAPP_RESPONSE, SEQ_COMPANIES, SEQ_COMPANYNOTES, SEQ_COMPANYNOTES_FILES, SEQ_COMPANYNOTES_RESPONSE, SEQ_COMPANYNOTES_RESP_FILES, SEQ_FEE_RELATION, SEQ_FEE_VALUE, SEQ_GROUPS, SEQ_GROUP_ACTIONS, SEQ_GROUP_SERVICE, SEQ_GROUP_USERS, SEQ_HPNOTES, SEQ_KIOSKS_PRINTED_FILES, SEQ_LOGS, SEQ_LOGS_TYPE, SEQ_LOG_PERMITREQUEST, SEQ_MAIN_YARD_ORDERS, SEQ_MAIN_YARD_ORDERS_FILES, SEQ_MAIN_YARD_ORDERS_RESPONSE, SEQ_MOBILE_FORGETPASSWORD_LOG, SEQ_MOBILE_USER_TOKEN, SEQ_NTPUSERS, SEQ_ORMTESTTB, SEQ_OUTBOXMAIL, SEQ_OUTBOXMAIL_FILES, SEQ_PERMITLANES_LOG, SEQ_PERMITSTYPE, SEQ_PETROLEUMBAN, SEQ_PETROLEUMCHARGES, SEQ_PETROLEUMCLAIMS, SEQ_PETROLEUMCOMPANIES, SEQ_PETROLEUMEVENTS, SEQ_PETROLEUMFEERETURN, SEQ_PETROLEUMINTERVALS, SEQ_PETROLEUMORDER, SEQ_PETROLEUMPRICES, SEQ_PETROLEUMQUOTA, SEQ_PETROLEUMREFINERY, SEQ_PETROLEUMSHWAER, SEQ_PETROLEUMTRACKING, SEQ_PETROLEUM_TRACKING, SEQ_REFINARYSHEETS, SEQ_REFINERY_VARIABLES, SEQ_REFINERY_VARIABLES_GID, SEQ_SERVICES, SEQ_SERVICE_FEES, SEQ_SERVICE_PARAMS, SEQ_SMS_LOGS, SEQ_STAKEHOLDER, SEQ_SURVEY_USER_ANSWERS, SEQ_SYSTEM_ERRORS, SEQ_SYSTEM_USER_LOG, SEQ_TICKETS, SEQ_TICKETSRESP_FILES, SEQ_TICKETS_FILES, SEQ_TICKETS_RESPONSE, SEQ_TICKETS_SOLUTION, SEQ_TRANSACTIONS, SEQ_TRUCKTYPE, SEQ_USER_LOG, SEQ_VOUCHERS, SEQ_VOUCHERS_FILES, SEQ_VOUCHERS_RESPONSE, SEQ_WARNINGS, SEQ_WF, SEQ_WF_ACTIONS, SEQ_WF_LOG, SEQ_YARDS, SEQ_YARDSNOTIFY, SEQ_YARDSNOTIFY_DETAILS, TAGGING_SESSIONSID, USERDEVICEINFOID diff --git a/src/NTP.Api/Auth/ActiveUserValidator.cs b/src/NTP.Api/Auth/ActiveUserValidator.cs new file mode 100644 index 0000000..57010fd --- /dev/null +++ b/src/NTP.Api/Auth/ActiveUserValidator.cs @@ -0,0 +1,37 @@ +using System.Security.Claims; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Options; +using NTP.Application.Abstractions; +using NTP.Application.Auth; + +namespace NTP.Api.Auth; + +/// +/// Port of Application.cfc onRequestStart: the user must still be active (NTPUSERS.STATUS = 1) with the same +/// ROLECODE, and role SU is only allowed for the configured super users. Result cached briefly (Jwt:ActiveCheckCacheSeconds). +/// +internal sealed class ActiveUserValidator( + IAuthService authService, IMemoryCache cache, IOptions jwt, IOptions auth) +{ + public async Task IsValidAsync(ClaimsPrincipal principal, CancellationToken ct) + { + var login = principal.FindFirst(AppClaims.UserId)?.Value; + var role = principal.FindFirst(AppClaims.Role)?.Value; + if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(role)) return false; + + if (role.Equals("SU", StringComparison.OrdinalIgnoreCase) && + !auth.Value.SuperUsers.Contains(login, StringComparer.OrdinalIgnoreCase)) + return false; + + var ttl = jwt.Value.ActiveCheckCacheSeconds; + if (ttl <= 0) + return await authService.IsUserStillActiveAsync(login, role, ct); + + var key = $"active:{login}:{role}"; + if (cache.TryGetValue(key, out bool cached)) return cached; + + var active = await authService.IsUserStillActiveAsync(login, role, ct); + cache.Set(key, active, TimeSpan.FromSeconds(ttl)); + return active; + } +} diff --git a/src/NTP.Api/Auth/AuthExtensions.cs b/src/NTP.Api/Auth/AuthExtensions.cs new file mode 100644 index 0000000..7cfb2b0 --- /dev/null +++ b/src/NTP.Api/Auth/AuthExtensions.cs @@ -0,0 +1,76 @@ +using System.Security.Cryptography; +using System.Text; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; +using Microsoft.IdentityModel.Tokens; +using NTP.Application.Abstractions; + +namespace NTP.Api.Auth; + +public static class AuthExtensions +{ + /// JWT bearer + ICurrentUser + fallback "authenticated user required" policy (use [AllowAnonymous] explicitly). + public static IServiceCollection AddNtpAuthentication(this IServiceCollection services, IConfiguration configuration, IHostEnvironment env) + { + var jwt = configuration.GetSection(JwtOptions.SectionName).Get() ?? new JwtOptions(); + + if (string.IsNullOrWhiteSpace(jwt.Key)) + { + if (!env.IsDevelopment()) + throw new InvalidOperationException( + "Jwt:Key is not configured. Set it via environment variable Jwt__Key, user-secrets or appsettings.Local.json (min 32 characters)."); + // Development only: random per-process key (tokens stop working after a restart). Set Jwt:Key to keep them. + jwt.Key = Convert.ToBase64String(RandomNumberGenerator.GetBytes(48)); + Console.WriteLine("WARNING: Jwt:Key not set - using a random development key (tokens are invalidated on restart)."); + } + if (jwt.Key.Length < JwtOptions.MinKeyLength) + throw new InvalidOperationException($"Jwt:Key must be at least {JwtOptions.MinKeyLength} characters."); + + services.Configure(o => + { + o.Key = jwt.Key; o.Issuer = jwt.Issuer; o.Audience = jwt.Audience; + o.ExpiryMinutes = jwt.ExpiryMinutes; o.ActiveCheckCacheSeconds = jwt.ActiveCheckCacheSeconds; + }); + services.Configure(configuration.GetSection(AuthOptions.SectionName)); + + services.AddMemoryCache(); + services.AddHttpContextAccessor(); + services.AddScoped(); + services.AddSingleton(); + services.AddScoped(); + + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(o => + { + o.MapInboundClaims = false; + o.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidIssuer = jwt.Issuer, + ValidateAudience = true, + ValidAudience = jwt.Audience, + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Key)), + ValidateLifetime = true, + ClockSkew = TimeSpan.FromSeconds(30), + NameClaimType = AppClaims.Name, + RoleClaimType = AppClaims.Role + }; + o.Events = new JwtBearerEvents + { + OnTokenValidated = async ctx => + { + var validator = ctx.HttpContext.RequestServices.GetRequiredService(); + if (ctx.Principal is null || + !await validator.IsValidAsync(ctx.Principal, ctx.HttpContext.RequestAborted)) + ctx.Fail("User is no longer active or the role changed."); + } + }; + }); + + services.AddAuthorizationBuilder() + .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()); + + return services; + } +} diff --git a/src/NTP.Api/Auth/BearerSecurityTransformer.cs b/src/NTP.Api/Auth/BearerSecurityTransformer.cs new file mode 100644 index 0000000..b2f1669 --- /dev/null +++ b/src/NTP.Api/Auth/BearerSecurityTransformer.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi; + +namespace NTP.Api.Auth; + +/// Adds the "Bearer" JWT scheme to the OpenAPI document so Swagger UI shows the Authorize button. +internal sealed class BearerSecurityTransformer : IOpenApiDocumentTransformer +{ + public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) + { + document.Components ??= new OpenApiComponents(); + document.Components.SecuritySchemes ??= new Dictionary(); + document.Components.SecuritySchemes["Bearer"] = new OpenApiSecurityScheme + { + Type = SecuritySchemeType.Http, + Scheme = "bearer", + BearerFormat = "JWT", + Description = "Paste the accessToken returned by POST /api/v1/auth/login." + }; + document.Security ??= []; + document.Security.Add(new OpenApiSecurityRequirement + { + [new OpenApiSecuritySchemeReference("Bearer", document)] = [] + }); + return Task.CompletedTask; + } +} diff --git a/src/NTP.Api/Auth/CurrentUser.cs b/src/NTP.Api/Auth/CurrentUser.cs new file mode 100644 index 0000000..8ed8641 --- /dev/null +++ b/src/NTP.Api/Auth/CurrentUser.cs @@ -0,0 +1,37 @@ +using System.Security.Claims; +using NTP.Application.Abstractions; + +namespace NTP.Api.Auth; + +/// ICurrentUser over the request's JWT claims (IHttpContextAccessor). +internal sealed class CurrentUser(IHttpContextAccessor accessor) : ICurrentUser +{ + private ClaimsPrincipal? Principal => accessor.HttpContext?.User; + + private string Str(string type) => Principal?.FindFirst(type)?.Value ?? string.Empty; + private long? Num(string type) => + long.TryParse(Principal?.FindFirst(type)?.Value, out var v) ? v : null; + + public bool IsAuthenticated => Principal?.Identity?.IsAuthenticated == true; + public long Id => Num(AppClaims.Id) ?? 0; + public string UserId => Str(AppClaims.UserId); + public string Name => Str(AppClaims.Name); + public string RoleCode => Str(AppClaims.Role); + public string RoleName => Str(AppClaims.RoleName); + public string Domain => Str(AppClaims.Domain); + public long? LocationId => Num(AppClaims.LocationId); + public string LocationName => Str(AppClaims.LocationName); + public long? StkId => Num(AppClaims.StkId); + public long? CompId => Num(AppClaims.CompId); + public long? CompanyId => Num(AppClaims.CompanyId); + public string CompanyName => Str(AppClaims.CompanyName); + public string CompanyCode => Str(AppClaims.CompanyCode); + public string EmpNo => Str(AppClaims.EmpNo); + public string Lang => Str(AppClaims.Lang) is { Length: > 0 } l ? l : "AR"; + public bool IsStaff => string.Equals(Str(AppClaims.IsStaff), "true", StringComparison.OrdinalIgnoreCase); + + public bool IsInRole(string roleCode) => + string.Equals(RoleCode, roleCode, StringComparison.OrdinalIgnoreCase); + + public bool IsInAnyRole(params string[] roleCodes) => roleCodes.Any(IsInRole); +} diff --git a/src/NTP.Api/Auth/JwtOptions.cs b/src/NTP.Api/Auth/JwtOptions.cs new file mode 100644 index 0000000..f3e4be5 --- /dev/null +++ b/src/NTP.Api/Auth/JwtOptions.cs @@ -0,0 +1,26 @@ +namespace NTP.Api.Auth; + +/// Config section "Jwt". Key comes from user-secrets / env (Jwt__Key) / appsettings.Local.json - never appsettings.json. +public sealed class JwtOptions +{ + public const string SectionName = "Jwt"; + + public string Key { get; set; } = string.Empty; + public string Issuer { get; set; } = "NTP"; + public string Audience { get; set; } = "NTP.Web"; + public int ExpiryMinutes { get; set; } = 480; + + /// Seconds to cache the per-request "user still active with same role" check (0 = query every request, like legacy). + public int ActiveCheckCacheSeconds { get; set; } = 10; + + public const int MinKeyLength = 32; +} + +/// Config section "Auth". +public sealed class AuthOptions +{ + public const string SectionName = "Auth"; + + /// Application.cfc: users with role SU not in this list are rejected on every request. + public string[] SuperUsers { get; set; } = []; +} diff --git a/src/NTP.Api/Auth/JwtTokenIssuer.cs b/src/NTP.Api/Auth/JwtTokenIssuer.cs new file mode 100644 index 0000000..1bc6325 --- /dev/null +++ b/src/NTP.Api/Auth/JwtTokenIssuer.cs @@ -0,0 +1,58 @@ +using System.Security.Claims; +using System.Text; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; +using NTP.Application.Abstractions; +using NTP.Application.Auth; + +namespace NTP.Api.Auth; + +internal sealed class JwtTokenIssuer(IOptions options) : ITokenIssuer +{ + private readonly JwtOptions _o = options.Value; + + public (string Token, DateTime ExpiresAtUtc) Issue(AuthenticatedUser user) + { + var expires = DateTime.UtcNow.AddMinutes(_o.ExpiryMinutes); + var descriptor = new SecurityTokenDescriptor + { + Issuer = _o.Issuer, + Audience = _o.Audience, + NotBefore = DateTime.UtcNow, + Expires = expires, + Subject = new ClaimsIdentity(CreateClaims(user)), + SigningCredentials = new SigningCredentials( + new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_o.Key)), SecurityAlgorithms.HmacSha256) + }; + return (new JsonWebTokenHandler().CreateToken(descriptor), expires); + } + + /// Claim set for a user (null/empty values are omitted). Exposed for tests. + public static IEnumerable CreateClaims(AuthenticatedUser u) + { + static Claim? C(string type, string? value) => string.IsNullOrEmpty(value) ? null : new Claim(type, value); + static Claim? N(string type, long? value) => value is null ? null : new Claim(type, value.Value.ToString()); + + var claims = new[] + { + C(AppClaims.UserId, u.UserId), + C(AppClaims.Id, u.Id.ToString()), + C(AppClaims.Name, u.Name), + C(AppClaims.Role, u.RoleCode), + C(AppClaims.RoleName, u.RoleName), + C(AppClaims.Domain, u.Domain), + N(AppClaims.LocationId, u.LocationId), + C(AppClaims.LocationName, u.LocationName), + N(AppClaims.StkId, u.StkId), + N(AppClaims.CompId, u.CompId), + N(AppClaims.CompanyId, u.CompanyId), + C(AppClaims.CompanyName, u.CompanyName), + C(AppClaims.CompanyCode, u.CompanyCode), + C(AppClaims.EmpNo, u.EmpNo), + C(AppClaims.Lang, u.Lang), + C(AppClaims.IsStaff, u.IsStaff ? "true" : "false"), + }; + return claims.Where(c => c is not null).Select(c => c!); + } +} diff --git a/src/NTP.Api/Authorization/RequirePermissionAttribute.cs b/src/NTP.Api/Authorization/RequirePermissionAttribute.cs new file mode 100644 index 0000000..f814125 --- /dev/null +++ b/src/NTP.Api/Authorization/RequirePermissionAttribute.cs @@ -0,0 +1,32 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using NTP.Application.Access; +using NTP.Application.Common; + +namespace NTP.Api.Authorization; + +/// +/// Gate an endpoint (or a whole controller) on a permission resource key from the database permission table +/// (see ). SU always passes; unauthenticated callers are rejected by the app-wide +/// fallback policy before this runs. A failure answers 403 with code FORBIDDEN_RESOURCE. +/// Several keys mean "any of them" (a shared endpoint serving more than one screen). +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] +public sealed class RequirePermissionAttribute : TypeFilterAttribute +{ + public RequirePermissionAttribute(params string[] resourceKeys) : base(typeof(RequirePermissionFilter)) + { + Arguments = [resourceKeys]; + } +} + +internal sealed class RequirePermissionFilter(string[] resourceKeys, IPermissionService permissions) : IAsyncAuthorizationFilter +{ + public async Task OnAuthorizationAsync(AuthorizationFilterContext context) + { + foreach (var key in resourceKeys) + if (await permissions.IsAllowedAsync(key, context.HttpContext.RequestAborted)) return; + + throw new ForbiddenException("FORBIDDEN_RESOURCE", "ليس لديك صلاحية للوصول إلى هذه الشاشة"); + } +} diff --git a/src/NTP.Api/Controllers/V1/AuthController.cs b/src/NTP.Api/Controllers/V1/AuthController.cs new file mode 100644 index 0000000..0266273 --- /dev/null +++ b/src/NTP.Api/Controllers/V1/AuthController.cs @@ -0,0 +1,59 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using NTP.Application.Abstractions; +using NTP.Application.Auth; + +namespace NTP.Api.Controllers.V1; + +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/auth")] +[Produces("application/json")] +public sealed class AuthController(IAuthService service, ICurrentUser currentUser) : ControllerBase +{ + /// Legacy signon.checkLogin. UserName is "DOMAIN.login" (e.g. ASEZA.50034). + [HttpPost("login")] + [AllowAnonymous] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + public Task Login(LoginRequest request, CancellationToken ct) => + service.LoginAsync(request, Client(), ct); + + /// The caller's claims (legacy session snapshot). + [HttpGet("me")] + [ProducesResponseType(StatusCodes.Status200OK)] + public CurrentUserDto Me() => new( + currentUser.Id, currentUser.UserId, currentUser.Name, currentUser.RoleCode, currentUser.RoleName, + currentUser.Domain, currentUser.LocationId, currentUser.LocationName, currentUser.StkId, currentUser.CompId, + currentUser.CompanyId, currentUser.CompanyName, currentUser.CompanyCode, currentUser.EmpNo, + currentUser.Lang, currentUser.IsStaff); + + /// Legacy signon.changePass. + [HttpPost("change-password")] + [ProducesResponseType(StatusCodes.Status200OK)] + public Task ChangePassword(ChangePasswordRequest request, CancellationToken ct) => + service.ChangePasswordAsync(request, ct); + + /// Switches AR/EN; returns a fresh token carrying the new language claim. + [HttpPost("language")] + [ProducesResponseType(StatusCodes.Status200OK)] + public Task Language(SetLanguageRequest request, CancellationToken ct) => + service.SetLanguageAsync(request, ct); + + /// Legacy signon.signOut: writes the sign-out audit row (the token itself is stateless; the client drops it). + [HttpPost("logout")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task Logout(CancellationToken ct) + { + await service.SignOutAsync(Client(), ct); + return NoContent(); + } + + private ClientInfo Client() + { + var ip = HttpContext.Connection.RemoteIpAddress; + if (ip is { IsIPv4MappedToIPv6: true }) ip = ip.MapToIPv4(); + return new ClientInfo(ip?.ToString(), Request.Headers.UserAgent.ToString()); + } +} diff --git a/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs b/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs new file mode 100644 index 0000000..d5ce3cc --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Grains/OrdersController.cs @@ -0,0 +1,213 @@ +using Asp.Versioning; +using NTP.Api.Authorization; +using NTP.Application.Access; +using Microsoft.AspNetCore.Mvc; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; + +namespace NTP.Api.Controllers.V1.Grains; + +/// Tender orders (legacy tenderOrderGrid.cfm / createNewTenderOrder.cfm / tenderOrder.cfc) and mobile publish. +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/orders")] +[Produces("application/json")] +public sealed class OrdersController( + ITenderOrderService orders, + IMobilePublishService mobile, + IOrderLookupService lookups) : ControllerBase +{ + [HttpGet] + [RequirePermission(PermissionKeys.OrdersList)] + public Task> Search( + [FromQuery] DateTime? orderDate, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + orders.SearchAsync(new TenderOrderQuery(orderDate), new PageRequest(page, pageSize), ct); + + [HttpPost] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersCreate)] + public Task Create(CreateTenderOrderRequest request, CancellationToken ct) => orders.CreateAsync(request, ct); + + [HttpDelete("{id:long}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersList)] + public Task Delete(long id, CancellationToken ct) => orders.DeleteAsync(id, ct); + + /// Show / hide the order on the mobile app (legacy publishMobile). + [HttpPut("{id:long}/mobile")] + [RequirePermission(PermissionKeys.OrdersList)] + public Task Publish(long id, MobilePublishRequest request, CancellationToken ct) => + mobile.SetVisibilityAsync(id, request.Show, ct); + + // ---- dropdown sources + [HttpGet("lookups/cargo-types")] + [RequirePermission(PermissionKeys.OrdersList, PermissionKeys.OrdersBilling)] + public Task> CargoTypes(CancellationToken ct) => lookups.CargoTypesAsync(ct); + + [HttpGet("lookups/loading-locations")] + [RequirePermission(PermissionKeys.OrdersList)] + public Task> LoadingLocations(CancellationToken ct) => lookups.LoadingLocationsAsync(ct); + + [HttpGet("lookups/destinations")] + [RequirePermission(PermissionKeys.OrdersList)] + public Task> Destinations(CancellationToken ct) => lookups.DestinationsAsync(ct); + + [HttpGet("lookups/billing-destinations")] + [RequirePermission(PermissionKeys.OrdersBilling)] + public Task> BillingDestinations(CancellationToken ct) => lookups.BillingDestinationsAsync(ct); + + [HttpGet("lookups/packed-destinations")] + [RequirePermission(PermissionKeys.OrdersCompanyDest)] + public Task> PackedDestinations(CancellationToken ct) => lookups.PackedDestinationsAsync(ct); + + [HttpGet("lookups/companies")] + [RequirePermission(PermissionKeys.OrdersBilling, PermissionKeys.OrdersCompanyDest, PermissionKeys.OrdersReportFinance)] + public Task> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct); +} + +/// Daily quota per destination (legacy quotaGrid.cfm, grains.cfc getQuotaList / editQuota). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/orders/quotas")] +[Produces("application/json")] +public sealed class OrderQuotasController(IQuotaService quotas) : ControllerBase +{ + [HttpGet] + [RequirePermission(PermissionKeys.OrdersQuotas)] + public Task> List( + [FromQuery] DateTime? date, [FromQuery] int page = 1, [FromQuery] int pageSize = 50, CancellationToken ct = default) => + quotas.GetListAsync(date ?? DateTime.Today, new PageRequest(page, pageSize), ct); + + [HttpPut] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersQuotas)] + public Task Set(SetQuotaRequest request, CancellationToken ct) => quotas.SetQuotaAsync(request, ct); +} + +/// Financial billing entry and list (legacy BillingScreen.cfm / BillingGrid.cfm, Invoice.cfc). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/orders/billing")] +[Produces("application/json")] +public sealed class OrderBillingController(IBillingService billing) : ControllerBase +{ + [HttpGet] + [RequirePermission(PermissionKeys.OrdersBilling)] + public Task> Search( + [FromQuery] string? tn, [FromQuery] long? pn, [FromQuery] long? scac, + [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + billing.SearchAsync(new BillingQuery(tn, pn, scac), new PageRequest(page, pageSize), ct); + + /// Prefill of the billing form from a CLOSEd permit (legacy getBillingInfo). + [HttpGet("permit/{pn:long}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersBilling)] + public Task Permit(long pn, [FromQuery] long? scac, CancellationToken ct) => billing.GetPermitAsync(pn, scac, ct); + + [HttpPost] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersBilling)] + public Task Add(AddBillingRequest request, CancellationToken ct) => billing.AddAsync(request, ct); +} + +/// Invoices list (legacy InvoiceGrid.cfm, Invoice.cfc getInvoiceGrid). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/orders/invoices")] +[Produces("application/json")] +public sealed class OrderInvoicesController(IInvoiceService invoices) : ControllerBase +{ + [HttpGet] + [RequirePermission(PermissionKeys.OrdersInvoices)] + public Task> Search( + [FromQuery] long? invoiceNumber, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + invoices.SearchAsync(invoiceNumber, new PageRequest(page, pageSize), ct); +} + +/// Loading weights entry (legacy addGrainsWeights.cfm). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/orders/weights")] +[Produces("application/json")] +public sealed class OrderWeightsController(IGrainsWeightService weights) : ControllerBase +{ + [HttpGet("{pn:long}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersWeights)] + public Task Get(long pn, CancellationToken ct) => weights.GetAsync(pn, ct); + + [HttpPost] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersWeights)] + public Task Save(SaveWeightsRequest request, CancellationToken ct) => weights.SaveAsync(request, ct); +} + +/// Which packed destinations a company may receive (legacy compdest.cfm over GRAINS_COMPANIES_LOCATION). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/orders/company-destinations")] +[Produces("application/json")] +public sealed class OrderCompanyDestinationsController(ICompanyDestinationService service) : ControllerBase +{ + [HttpGet("{scac:long}")] + [RequirePermission(PermissionKeys.OrdersCompanyDest)] + public Task Get(long scac, CancellationToken ct) => service.GetAsync(scac, ct); + + [HttpPut("{scac:long}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)] + [RequirePermission(PermissionKeys.OrdersCompanyDest)] + public Task Save(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct) => + service.SaveAsync(scac, request, ct); +} + +/// Reports (legacy tenderOrderReport_xls.cfm, FinancialBilling.cfm, FinancialRpts.cfm): JSON grids + CSV/XLSX export. +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/orders/reports")] +public sealed class OrderReportsController(IOrderReportService reports) : ControllerBase +{ + [HttpGet("tender-orders")] + [Produces("application/json")] + [RequirePermission(PermissionKeys.OrdersReportOrders)] + public Task TenderOrders([FromQuery] DateTime orderDate, CancellationToken ct) => + reports.GetTenderOrderReportAsync(orderDate, ct); + + /// format: csv (default) or xlsx. + [HttpGet("tender-orders/export")] + [RequirePermission(PermissionKeys.OrdersReportOrders)] + public async Task ExportTenderOrders([FromQuery] DateTime orderDate, [FromQuery] string format = "csv", CancellationToken ct = default) + { + var f = await reports.ExportTenderOrderReportAsync(orderDate, format, ct); + return File(f.Content, f.ContentType, f.FileName); + } + + [HttpGet("financial-billing")] + [Produces("application/json")] + [RequirePermission(PermissionKeys.OrdersReportFinance)] + public Task FinancialBilling( + [FromQuery] long scac, [FromQuery] long invoiceNumber, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + reports.GetFinancialBillingAsync(scac, invoiceNumber, new PageRequest(page, pageSize), ct); + + [HttpGet("financial-billing/export")] + [RequirePermission(PermissionKeys.OrdersReportFinance)] + public async Task ExportFinancialBilling( + [FromQuery] long scac, [FromQuery] long invoiceNumber, [FromQuery] string format = "csv", CancellationToken ct = default) + { + var f = await reports.ExportFinancialBillingAsync(scac, invoiceNumber, format, ct); + return File(f.Content, f.ContentType, f.FileName); + } + + /// Invoice numbers of a company for the report picker (legacy getInvoiceNo, which does not exist in the CFC). + [HttpGet("invoice-numbers")] + [Produces("application/json")] + [RequirePermission(PermissionKeys.OrdersReportFinance)] + public Task> InvoiceNumbers([FromQuery] long scac, CancellationToken ct) => reports.GetInvoiceNumbersAsync(scac, ct); +} diff --git a/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs b/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs new file mode 100644 index 0000000..de9fdff --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Grains/PermitsController.cs @@ -0,0 +1,445 @@ +using Asp.Versioning; +using NTP.Api.Authorization; +using NTP.Application.Access; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using NTP.Application.Common; +using NTP.Application.Grains.Permits; + +namespace NTP.Api.Controllers.V1.Grains; + +/// +/// Grain permits (legacy GNPermits.cfm / createGnOrder.cfm / viewPermitDetails.cfm / PhoneAccept.cfm / PhoneReject.cfm / deleteGnOrder.cfm / +/// RevokeGnPermit.cfm / arrivalTruck.cfm / addGrainsWeights.cfm / activeOrInactiveAbsenceFeature.cfm and grains.cfc). +/// Company users (stakeholder 62) only see and change their own permits (enforced in the service). +/// +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/permits")] +[Produces("application/json")] +public sealed class PermitsController(IPermitService permits) : ControllerBase +{ + // ---- lists + /// getGNPermits: empty until at least one filter is given (legacy behaviour). + [HttpGet] + [RequirePermission(PermissionKeys.PermitsList)] + public Task> Search( + [FromQuery] string? tn, [FromQuery] string? pn, [FromQuery] string? status, [FromQuery] long? destAddressId, + [FromQuery] string? tenderOrder, [FromQuery] string? shipmentMode, [FromQuery] string? creationDate, [FromQuery] long? companyCode, + [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + permits.SearchAsync(new PermitSearchQuery(tn, pn, status, destAddressId, tenderOrder, shipmentMode, creationDate, companyCode), + new PageRequest(page, pageSize), ct); + + /// getGNList (permitsGrid.cfm): gate / clearance list. + [HttpGet("gate")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)] + public Task> Gate( + [FromQuery] string? tn, [FromQuery] string? trn, [FromQuery] string? pn, + [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + permits.SearchGateListAsync(new GatePermitQuery(tn, trn, pn), new PageRequest(page, pageSize), ct); + + [HttpGet("{id:long}")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task Get(long id, CancellationToken ct) => permits.GetAsync(id, ct); + + [HttpGet("{id:long}/events")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task> Events(long id, CancellationToken ct) => permits.GetEventsAsync(id, ct); + + // ---- lookups used by the order form + [HttpGet("lookups/truck/{tn}")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task Truck(string tn, [FromQuery] bool validate = false, CancellationToken ct = default) => + permits.GetTruckInfoAsync(tn, validate, ct); + + [HttpGet("lookups/trailer/{trn}")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task Trailer(string trn, CancellationToken ct) => permits.GetTrailerInfoAsync(trn, ct); + + [HttpGet("lookups/driver/{nnpn}")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task Driver(string nnpn, CancellationToken ct) => permits.GetDriverInfoAsync(nnpn, ct); + + // ---- order lifecycle (companies and staff) + [HttpPost("{id:long}/submit")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task Submit(long id, SubmitOrderRequest request, CancellationToken ct) => permits.SubmitAsync(id, request, ct); + + [HttpPut("{id:long}")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task Update(long id, UpdateOrderRequest request, CancellationToken ct) => permits.UpdateAsync(id, request, ct); + + [HttpPost("{id:long}/accept")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task Accept(long id, CancellationToken ct) => permits.AcceptAsync(id, ct); + + [HttpPost("{id:long}/revoke")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task Revoke(long id, CancellationToken ct) => permits.RevokeAsync(id, ct); + + [HttpPost("{id:long}/revoke-accepted")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task RevokeAccepted(long id, CancellationToken ct) => permits.RevokeAcceptedAsync(id, ct); + + // ---- staff operations + [HttpPost("{id:long}/convert-to-resd")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task ConvertToResd(long id, CancellationToken ct) => permits.ConvertToResdAsync(id, ct); + + [HttpPost("{id:long}/cancel-order")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task CancelOrder(long id, ReasonRequest request, CancellationToken ct) => permits.CancelOrderAsync(id, request, ct); + + [HttpPost("{id:long}/revoke-permit")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task RevokePermit(long id, ReasonRequest request, CancellationToken ct) => permits.RevokePermitAsync(id, request, ct); + + [HttpPost("{id:long}/reactivate")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task Reactivate(long id, CancellationToken ct) => permits.ReactivateAsync(id, ct); + + /// GrainsFactory(Web).cancelGrainsPermit: RESD back to ACCPT. + [HttpPost("{id:long}/cancel-grains-permit")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task CancelGrainsPermit(long id, CancellationToken ct) => permits.CancelGrainsPermitAsync(id, ct); + + /// closePermit / arrivalTruck.cfm. + [HttpPost("close")] + [RequirePermission(PermissionKeys.PermitsClose)] + public Task Close(ClosePermitRequest request, CancellationToken ct) => permits.CloseManualAsync(request, ct); + + [HttpPost("{id:long}/phone-accept")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task PhoneAccept(long id, PhoneAcceptRequest request, CancellationToken ct) => permits.PhoneAcceptAsync(id, request, ct); + + [HttpPost("{id:long}/phone-reject")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task PhoneReject(long id, PhoneRejectRequest request, CancellationToken ct) => permits.PhoneRejectAsync(id, request, ct); + + // ---- stored loading weights (addGrainsWeights.cfm) + [HttpGet("weights/{pn}")] + [RequirePermission(PermissionKeys.OrdersWeights)] + public Task Weights(string pn, CancellationToken ct) => permits.LookupWeightsAsync(pn, ct); + + [HttpPut("weights")] + [RequirePermission(PermissionKeys.OrdersWeights)] + public Task SaveWeights(SaveWeightsRequest request, CancellationToken ct) => permits.SaveWeightsAsync(request, ct); + + // ---- absence feature switch (activeOrInactiveAbsenceFeature.cfm) + [HttpGet("absence-feature")] + [RequirePermission(PermissionKeys.PermitsAbsence, PermissionKeys.PermitsDistribution)] + public AbsenceFeatureDto AbsenceFeature() => permits.GetAbsenceFeature(); + + [HttpPost("absence-feature/toggle")] + [RequirePermission(PermissionKeys.PermitsAbsence)] + public Task ToggleAbsenceFeature(CancellationToken ct) => permits.ToggleAbsenceFeatureAsync(ct); +} + +/// Turns (legacy CreateQueue.cfm / queueGrid.cfm / createPermit.cfm / dblMovePN.cfm): OPEN permit records and the TCS permit. +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/permit-queue")] +[Produces("application/json")] +public sealed class PermitQueueController(IQueueService queue) : ControllerBase +{ + /// getGNQueueList (queueGrid.cfm). + [HttpGet] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task> List([FromQuery] string? tn, [FromQuery] string? pn, + [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) => + queue.ListAsync(new QueueSearchQuery(tn, pn), new PageRequest(page, pageSize), ct); + + /// AddToQueue (CreateQueue.cfm). + [HttpPost] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task Add(AddToQueueRequest request, CancellationToken ct) => queue.AddToQueueAsync(request, ct); + + [HttpGet("trailer-of/{tn}")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public async Task> TrailerOf(string tn, CancellationToken ct) => new { trailer = await queue.GetTrailerNumberAsync(tn, ct) }; + + /// checkTrucks. + [HttpPost("check-trucks")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task CheckTrucks([FromQuery] long tn, [FromQuery] long scac, CancellationToken ct) => queue.CheckTrucksAsync(tn, scac, ct); + + /// parseGrainsPermits job, on demand: create OPEN permits for the given companies. + [HttpPost("seed")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task Seed(SeedPermitsRequest request, CancellationToken ct) => queue.SeedPermitsAsync(request, ct); + + // ---- TCS permit form (createPermit.cfm) + [HttpGet("{id:long}/tcs-form")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task TcsForm(long id, CancellationToken ct) => queue.GetTcsFormDataAsync(id, ct); + + [HttpGet("tcs/routing-templates")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task> RoutingTemplates([FromQuery] long origin, [FromQuery] long destination, + [FromQuery] string shipmentMode, [FromQuery] string firms, CancellationToken ct) => + queue.GetRoutingTemplatesAsync(origin, destination, shipmentMode, firms, ct); + + [HttpGet("tcs/origins")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task> Origins([FromQuery] long routing, CancellationToken ct) => queue.GetOriginAddressesAsync(routing, ct); + + [HttpGet("tcs/ph-routes")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task> PhRoutes(CancellationToken ct) => queue.GetPhRoutesAsync(ct); + + [HttpGet("tcs/clearing-agent/{can:long}")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public async Task> ClearingAgent(long can, CancellationToken ct) => new { name = await queue.GetClearingAgentNameAsync(can, ct) }; + + [HttpGet("tcs/fop/{fop}")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task Fop(string fop, CancellationToken ct) => queue.GetFopDetailAsync(fop, ct); + + [HttpPost("{id:long}/tcs-permit")] + [RequirePermission(PermissionKeys.PermitsQueue)] + public Task CreateTcsPermit(long id, CreateTcsPermitRequest request, CancellationToken ct) => + queue.CreateTcsPermitAsync(id, request, ct); +} + +/// Destinations of permits and companies (legacy assginggdest.cfm / compdest.cfm / ManualInput.cfm / activateOrders.cfm). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/permit-destinations")] +[Produces("application/json")] +public sealed class PermitDestinationsController(IDestinationService destinations) : ControllerBase +{ + [HttpGet("lookups/locations")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)] + public Task> Locations(CancellationToken ct) => destinations.GetGrainsLocationsAsync(ct); + + /// Destination filter of the permit list (GNPermits.cfm): every GN exit location by name, active or not. + [HttpGet("lookups/filter-destinations")] + [RequirePermission(PermissionKeys.PermitsList)] + public Task> FilterDestinations(CancellationToken ct) => destinations.GetPermitFilterDestinationsAsync(ct); + + [HttpGet("lookups/exit-locations")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)] + public Task> ExitLocations(CancellationToken ct) => destinations.GetExitLocationsAsync(ct); + + [HttpGet("lookups/cargo-types")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)] + public Task> CargoTypes(CancellationToken ct) => destinations.GetCargoTypesAsync(ct); + + [HttpGet("lookups/location-groups")] + [RequirePermission(PermissionKeys.PermitsDestinations)] + public Task LocationGroups(CancellationToken ct) => destinations.GetLocationGroupsAsync(ct); + + [HttpGet("lookups/companies")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)] + public Task> Companies(CancellationToken ct) => destinations.GetCompaniesAsync(ct); + + [HttpGet("companies/{scac:long}")] + [RequirePermission(PermissionKeys.PermitsDestinations)] + public Task> CompanyDestinations(long scac, CancellationToken ct) => destinations.GetCompanyDestinationsAsync(scac, ct); + + [HttpPut("companies/{scac:long}")] + [RequirePermission(PermissionKeys.PermitsDestinations)] + public Task SaveCompanyDestinations(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct) => + destinations.SaveCompanyDestinationsAsync(scac, request, ct); + + /// savegrainsdest (assginggdest.cfm). + [HttpPost("assign-by-pn")] + [RequirePermission(PermissionKeys.PermitsDestinations)] + public Task AssignByPn(AssignByPnRequest request, CancellationToken ct) => destinations.AssignByPnAsync(request, ct); + + // ---- manual input (ManualInput.cfm) + [HttpGet("order-dates")] + [RequirePermission(PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsDestinations)] + public Task> OrderDates(CancellationToken ct) => destinations.GetOrderDatesAsync(ct); + + [HttpGet("allowed-destinations")] + [RequirePermission(PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsDestinations)] + public Task> AllowedDestinations([FromQuery] string pn, [FromQuery] string orderDate, CancellationToken ct) => + destinations.GetAllowedDestinationsAsync(pn, orderDate, ct); + + [HttpGet("{permitId:long}/allowed-cargo")] + [RequirePermission(PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsDestinations)] + public Task> AllowedCargo(long permitId, CancellationToken ct) => destinations.GetAllowedCargoAsync(permitId, ct); + + [HttpGet("orders-for-permit")] + [RequirePermission(PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsDestinations)] + public Task> OrdersForPermit([FromQuery] string pn, [FromQuery] string orderDate, CancellationToken ct) => + destinations.GetOrdersForPermitAsync(pn, orderDate, ct); + + [HttpPost("manual-input")] + [RequirePermission(PermissionKeys.PermitsManualEntry)] + public Task ManualInput(ManualInputRequest request, CancellationToken ct) => destinations.ManualInputAsync(request, ct); + + /// searchDestination (WeightBridge.cfm): the truck's destination, assigning one when needed. + [HttpGet("search/{tn}")] + [RequirePermission(PermissionKeys.PermitsWeighbridge)] + public Task Search(string tn, CancellationToken ct) => destinations.SearchDestinationAsync(tn, ct); + + // ---- activation of today's orders (activateOrders.cfm) + [HttpGet("activation")] + [RequirePermission(PermissionKeys.PermitsActivation)] + public Task> Activation(CancellationToken ct) => destinations.GetActivationAsync(ct); + + [HttpPost("activation")] + [RequirePermission(PermissionKeys.PermitsActivation)] + public Task Activate(ActivateOrdersRequest request, CancellationToken ct) => destinations.ActivateOrdersAsync(request, ct); + + /// activateGrainsDestination job, on demand. + [HttpPost("jobs/activate-company-destinations")] + [Authorize(Roles = "SU")] + public async Task> ActivatePending(CancellationToken ct) => new { activated = await destinations.ActivatePendingCompanyDestinationsAsync(ct) }; +} + +/// Distribution of OPEN permits (legacy distributedOrder.cfm / distributionDetails.cfm / distributeSingelTruck.cfm / processOpenPermit.cfm ...). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/permit-distribution")] +[Produces("application/json")] +public sealed class PermitDistributionController(IDistributionService distribution) : ControllerBase +{ + [HttpPost("distribute")] + [RequirePermission(PermissionKeys.PermitsDistribution)] + public Task Distribute(DistributeRequest request, CancellationToken ct) => distribution.DistributeAsync(request, ct); + + [HttpPost("release")] + [RequirePermission(PermissionKeys.PermitsDistribution)] + public Task Release(ReleasePermitRequest request, CancellationToken ct) => distribution.ReleaseAsync(request, ct); + + [HttpPost("process-open")] + [RequirePermission(PermissionKeys.PermitsTruckOrder)] + public Task ProcessOpen(OpenPermitRequest request, CancellationToken ct) => distribution.ProcessOpenPermitAsync(request, ct); + + [HttpPost("process-open-with-destination")] + [RequirePermission(PermissionKeys.PermitsTruckOrder)] + public Task ProcessOpenWithDestination(OpenPermitWithDestinationRequest request, CancellationToken ct) => + distribution.ProcessOpenPermitWithDestinationAsync(request, ct); + + [HttpPost("process-company-open")] + [RequirePermission(PermissionKeys.PermitsTruckOrder)] + public Task ProcessCompanyOpen(CompanyOpenPermitsRequest request, CancellationToken ct) => + distribution.ProcessCompanyOpenPermitsAsync(request, ct); + + [HttpPost("single-truck")] + [RequirePermission(PermissionKeys.PermitsTruckOrder)] + public Task SingleTruck([FromQuery] string tn, CancellationToken ct) => distribution.DistributeSingleTruckAsync(tn, ct); + + [HttpGet("summary")] + [RequirePermission(PermissionKeys.PermitsDistribution)] + public Task> Summary(CancellationToken ct) => distribution.GetSummaryAsync(ct); + + [HttpGet("pivot")] + [RequirePermission(PermissionKeys.PermitsDistribution)] + public Task> Pivot(CancellationToken ct) => distribution.GetPivotAsync(ct); + + [HttpGet("search-truck")] + [RequirePermission(PermissionKeys.PermitsTruckStatus)] + public Task SearchTruck([FromQuery] string tn, CancellationToken ct) => distribution.SearchTruckAsync(tn, ct); + + [HttpGet("blacklisted")] + [RequirePermission(PermissionKeys.PermitsTruckStatus, PermissionKeys.PermitsDistribution)] + public Task> Blacklisted([FromQuery] string tn, CancellationToken ct) => distribution.GetBlacklistedAsync(tn, ct); + + [HttpPost("check-trips")] + [RequirePermission(PermissionKeys.PermitsDistribution)] + public Task CheckTrips(CheckTripsRequest request, CancellationToken ct) => distribution.CheckTripsAsync(request, ct); + + /// RevokeAllREQST.cfm: send every REQST / PLND permit of an order id below the given limit back to OPEN. + [HttpPost("revoke-all-requested")] + [Authorize(Roles = "SU")] + public Task RevokeAllRequested([FromQuery] long scrnBelow, CancellationToken ct) => distribution.RevokeAllRequestedAsync(scrnBelow, ct); + + /// checkForGabanEvents job, on demand. + [HttpPost("jobs/revert-unloaded")] + [Authorize(Roles = "SU")] + public async Task> RevertUnloaded(CancellationToken ct) => new { reverted = await distribution.RevertUnloadedPermitsAsync("SYSTEM", ct) }; + + // ---- auto call (GrainsFactoryWeb.autoCallService2 / callAPI) + [HttpPost("auto-call/send")] + [RequirePermission(PermissionKeys.PermitsDistribution)] + public Task SendAutoCall(AutoCallRequest request, CancellationToken ct) => distribution.SendAutoCallFileAsync(request, ct); + + [HttpPost("auto-call/ivr")] + [RequirePermission(PermissionKeys.PermitsDistribution)] + public Task TriggerIvr(CancellationToken ct) => distribution.TriggerIvrAsync(ct); +} + +/// autoCallResponse.cfc: the dialer's callback. Authenticated with the X-Api-Key header (Grains:Permits:AutoCall:ApiKey), not a JWT. +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/permit-autocall")] +[Produces("application/json")] +public sealed class PermitAutoCallController(IDistributionService distribution) : ControllerBase +{ + [HttpPost("callback")] + [AllowAnonymous] + public async Task Callback(AutoCallResponse body, [FromHeader(Name = "X-Api-Key")] string? apiKey, CancellationToken ct) + { + if (!distribution.IsValidDialerApiKey(apiKey)) return Unauthorized(); + var r = await distribution.HandleDialerCallbackAsync(body, ct); + return Ok(new { code = r.Code, msg = r.Message }); + } +} + +/// Weighbridges and print pages (legacy WeightBridge.cfm / EN_WeightBridge.cfm / EX_WeightBridge.cfm / loadingWeightBridge.cfm / printIn / printOut / acceptPrint). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/permit-weighbridge")] +[Produces("application/json")] +public sealed class PermitWeighbridgeController(IWeighbridgeService weighbridge) : ControllerBase +{ + [HttpPost("enter")] + [RequirePermission(PermissionKeys.PermitsWeighbridge)] + public Task Enter(WeighbridgeReadingRequest request, CancellationToken ct) => weighbridge.EnterAsync(request, ct); + + [HttpPost("exit")] + [RequirePermission(PermissionKeys.PermitsWeighbridge)] + public Task Exit(WeighbridgeReadingRequest request, CancellationToken ct) => weighbridge.ExitAsync(request, ct); + + [HttpPost("manual")] + [RequirePermission(PermissionKeys.PermitsWeighbridge)] + public Task Manual(ManualWeighbridgeRequest request, CancellationToken ct) => weighbridge.ManualAsync(request, ct); + + [HttpPost("loading-weights")] + [RequirePermission(PermissionKeys.PermitsWeighbridge)] + public Task Loading(WeighbridgeWeightsRequest request, CancellationToken ct) => weighbridge.LoadingWeightsAsync(request, ct); + + [HttpPost("discharge-weights")] + [RequirePermission(PermissionKeys.PermitsWeighbridge)] + public Task Discharge(WeighbridgeWeightsRequest request, CancellationToken ct) => weighbridge.DischargeWeightsAsync(request, ct); + + /// getTruckInfoFromTN. + [HttpGet("truck/{tn}")] + [RequirePermission(PermissionKeys.PermitsWeighbridge, PermissionKeys.PermitsClose)] + public Task Truck(string tn, [FromQuery] string status, CancellationToken ct) => weighbridge.GetTruckPermitAsync(tn, status, ct); + + [HttpGet("truck/{tn}/weight")] + [RequirePermission(PermissionKeys.PermitsWeighbridge, PermissionKeys.PermitsClose)] + public Task TruckWeight(string tn, CancellationToken ct) => weighbridge.GetTruckWaybridgeEventAsync(tn, ct); + + /// getlocTruckNum (locTruckNumGrid.cfm). + [HttpGet("location-truck-counts")] + [RequirePermission(PermissionKeys.PermitsWeighbridge)] + public Task> LocationCounts(CancellationToken ct) => weighbridge.GetLocationTruckCountsAsync(ct); + + // ---- print data + [HttpGet("{permitId:long}/print/accept")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)] + public Task AcceptPrint(long permitId, CancellationToken ct) => weighbridge.GetAcceptPrintAsync(permitId, ct); + + [HttpGet("{permitId:long}/print/in")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)] + public Task PrintIn(long permitId, CancellationToken ct) => weighbridge.GetPrintInAsync(permitId, ct); + + [HttpGet("{permitId:long}/print/out")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)] + public Task PrintOut(long permitId, CancellationToken ct) => weighbridge.GetPrintOutAsync(permitId, ct); + + [HttpGet("{permitId:long}/print/details")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)] + public Task Details(long permitId, CancellationToken ct) => weighbridge.GetPermitDetailsAsync(permitId, ct); + + // ---- jobs on demand + [HttpPost("jobs/sync")] + [Authorize(Roles = "SU")] + public async Task> Sync([FromQuery] bool aqaba, CancellationToken ct) => new { processed = await weighbridge.SyncAsync(aqaba, ct) }; +} diff --git a/src/NTP.Api/Controllers/V1/Grains/RegistryController.cs b/src/NTP.Api/Controllers/V1/Grains/RegistryController.cs new file mode 100644 index 0000000..96c30dd --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Grains/RegistryController.cs @@ -0,0 +1,303 @@ +using Asp.Versioning; +using NTP.Api.Authorization; +using NTP.Application.Access; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using NTP.Application.Common; +using NTP.Application.Grains.Registry; + +namespace NTP.Api.Controllers.V1.Grains; + +/// +/// Grains registry slice: trucks, trailers, drivers, blacklist (+ weighbridge exceptions, location counts, permit-screen lookups). +/// Port of services\Grains\cfc\register.cfc and the registry parts of grains.cfc. Thin controller: authorization of the individual actions +/// (legacy isActAuthorized ids, company scoping) is done in the services. +/// +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/registry")] +[Produces("application/json")] +public sealed class RegistryController( + ITruckRegistryService trucks, + ITrailerRegistryService trailers, + IDriverRegistryService drivers, + IBlacklistService blacklist, + IRegistryOpsService ops, + IRegistryLookupService lookups, + IRegistryAttachmentService attachments, + IRegistryQueuePermitService queuePermits) : ControllerBase +{ + // ------------------------------------------------------------------------------------------ permissions + lookups + + /// What the caller may do on the registry screens (legacy isActAuthorized buttons). + [HttpGet("permissions")] + public Task Permissions(CancellationToken ct) => lookups.PermissionsAsync(ct); + + /// NTP_TENDERS_COMPANIES (ACTIVE): the company select of the truck/trailer forms and filters. + [HttpGet("lookups/companies")] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers, PermissionKeys.RegistryBlacklist)] + public Task> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct); + + /// TRUCKKINDS by code (S, T for trucks; HTR, TR for trailers): the axial loads select. + [HttpGet("lookups/truck-kinds")] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)] + public Task> TruckKinds([FromQuery] string kinds, CancellationToken ct) => + lookups.TruckKindsAsync((kinds ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), ct); + + /// Destination locations grouped as on the truck form (packed / bulk / bulk-gallab). + [HttpGet("lookups/destinations")] + [RequirePermission(PermissionKeys.RegistryTrucks)] + public Task Destinations(CancellationToken ct) => lookups.DestinationsAsync(ct); + + [HttpGet("lookups/driver-nationalities")] + [RequirePermission(PermissionKeys.RegistryDrivers)] + public Task> DriverNationalities(CancellationToken ct) => lookups.DriverNationalitiesAsync(ct); + + [HttpGet("lookups/weighbridge-locations")] + [RequirePermission(PermissionKeys.RegistryWeighbridge)] + public Task> WeighbridgeLocations(CancellationToken ct) => lookups.WeighbridgeLocationsAsync(ct); + + // ------------------------------------------------------------------------------------------ trucks (truckGrid.cfm, registerGrainsTruck.cfm) + + /// getTruckGrid. searchType TN (trucks, default) or TRN (searches the trailers table, rows carry tnId). + [HttpGet("trucks")] + [RequirePermission(PermissionKeys.RegistryTrucks)] + public Task> SearchTrucks( + [FromQuery] string? searchType, [FromQuery] string? tn, [FromQuery] string? chasesNumber, [FromQuery] string? statusCode, + [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); + + /// getTruckInfo (+ connected trailer, destinations, attachments). + [HttpGet("trucks/{id:long}")] + [RequirePermission(PermissionKeys.RegistryTrucks)] + public Task GetTruck(long id, CancellationToken ct) => trucks.GetAsync(id, ct); + + /// getAllTrnOnthisTn: trailers connected to the truck. + [HttpGet("trucks/{id:long}/trailers")] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)] + public Task> TrailersOfTruck(long id, CancellationToken ct) => trucks.TrailersAsync(id, null, ct); + + /// saveTrucksDetails. + [HttpPost("trucks")] + [RequirePermission(PermissionKeys.RegistryTrucksCreate)] + public Task CreateTruck(SaveTruckRequest request, CancellationToken ct) => trucks.CreateAsync(request, ct); + + /// editTrucksDetails. + [HttpPut("trucks/{id:long}")] + [RequirePermission(PermissionKeys.RegistryTrucksEdit)] + public Task UpdateTruck(long id, SaveTruckRequest request, CancellationToken ct) => trucks.UpdateAsync(id, request, ct); + + /// acceptTruck (-> ACCPT). + [HttpPost("trucks/{id:long}/accept")] + [RequirePermission(PermissionKeys.RegistryTrucks)] + public Task AcceptTruck(long id, CancellationToken ct) => trucks.AcceptAsync(id, ct); + + /// revokeTruck (-> RVKD, cascades to trailers, destinations and open permits). + [HttpPost("trucks/{id:long}/revoke")] + [RequirePermission(PermissionKeys.RegistryTrucks)] + public Task RevokeTruck(long id, CancellationToken ct) => trucks.RevokeAsync(id, ct); + + // ------------------------------------------------------------------------------------------ trailers (trailerGrid.cfm, registerGrainsTrailer.cfm) + + [HttpGet("trailers")] + [RequirePermission(PermissionKeys.RegistryTrailers)] + public Task> SearchTrailers( + [FromQuery] string? tn, [FromQuery] string? chasesNumber, [FromQuery] string? statusCode, [FromQuery] long? tcscac, + [FromQuery] int page = 1, [FromQuery] int pageSize = 15, CancellationToken ct = default) => + trailers.SearchAsync(new TrailerListQuery(tn, chasesNumber, statusCode, tcscac), new PageRequest(page, pageSize), ct); + + [HttpGet("trailers/{id:long}")] + [RequirePermission(PermissionKeys.RegistryTrailers)] + public Task GetTrailer(long id, CancellationToken ct) => trailers.GetAsync(id, ct); + + /// saveTrailerDetails. + [HttpPost("trailers")] + [RequirePermission(PermissionKeys.RegistryTrailersCreate)] + public Task CreateTrailer(SaveTrailerRequest request, CancellationToken ct) => trailers.CreateAsync(request, ct); + + /// editTrailerDetails. + [HttpPut("trailers/{id:long}")] + [RequirePermission(PermissionKeys.RegistryTrailersEdit)] + public Task UpdateTrailer(long id, SaveTrailerRequest request, CancellationToken ct) => trailers.UpdateAsync(id, request, ct); + + [HttpPost("trailers/{id:long}/accept")] + [RequirePermission(PermissionKeys.RegistryTrailers)] + public Task AcceptTrailer(long id, CancellationToken ct) => trailers.AcceptAsync(id, ct); + + [HttpPost("trailers/{id:long}/revoke")] + [RequirePermission(PermissionKeys.RegistryTrailers)] + public Task RevokeTrailer(long id, CancellationToken ct) => trailers.RevokeAsync(id, ct); + + // ------------------------------------------------------------------------------------------ drivers (driverGrid.cfm, regesterDriver.cfm) + + [HttpGet("drivers")] + [RequirePermission(PermissionKeys.RegistryDrivers)] + public Task> SearchDrivers( + [FromQuery] string? nnpn, [FromQuery] string? name, [FromQuery] string? statusCode, + [FromQuery] int page = 1, [FromQuery] int pageSize = 15, CancellationToken ct = default) => + drivers.SearchAsync(new DriverListQuery(nnpn, name, statusCode), new PageRequest(page, pageSize), ct); + + [HttpGet("drivers/{id:long}")] + [RequirePermission(PermissionKeys.RegistryDrivers)] + public Task GetDriver(long id, CancellationToken ct) => drivers.GetAsync(id, ct); + + /// saveDriverDetails. + [HttpPost("drivers")] + [RequirePermission(PermissionKeys.RegistryDriversCreate)] + public Task CreateDriver(SaveDriverRequest request, CancellationToken ct) => drivers.CreateAsync(request, ct); + + [HttpPost("drivers/{id:long}/accept")] + [RequirePermission(PermissionKeys.RegistryDrivers)] + public Task AcceptDriver(long id, CancellationToken ct) => drivers.AcceptAsync(id, ct); + + [HttpPost("drivers/{id:long}/revoke")] + [RequirePermission(PermissionKeys.RegistryDrivers)] + public Task RevokeDriver(long id, CancellationToken ct) => drivers.RevokeAsync(id, ct); + + // ------------------------------------------------------------------------------------------ blacklist (blackListGrid.cfm, createBlacklist.cfm, confirmDeleteBL.cfm) + + /// getBlackListGrid. entityId = permit number. + [HttpGet("blacklist")] + [RequirePermission(PermissionKeys.RegistryBlacklist)] + public Task> SearchBlacklist( + [FromQuery] string? entityId, [FromQuery] string? category, [FromQuery] string? statusCode, + [FromQuery] int page = 1, [FromQuery] int pageSize = 15, CancellationToken ct = default) => + blacklist.SearchAsync(new BlacklistQuery(entityId, category, statusCode), new PageRequest(page, pageSize), ct); + + /// BL_addToBlacklist. + [HttpPost("blacklist")] + [RequirePermission(PermissionKeys.RegistryBlacklist)] + public Task AddToBlacklist(AddBlacklistRequest request, CancellationToken ct) => blacklist.AddAsync(request, ct); + + /// deleteFromBlackList (roles GNSU, GNCO, GTO). + [HttpPost("blacklist/{id:long}/cancel")] + [RequirePermission(PermissionKeys.RegistryBlacklist)] + public Task CancelBlacklist(long id, CancelBlacklistRequest request, CancellationToken ct) => blacklist.CancelAsync(id, request, ct); + + // ------------------------------------------------------------------------------------------ weighbridge exceptions, weights, counts, fleet + + /// saveWeighbridgesControlInfo (WeighbridgesControl.cfm). + [HttpPost("weighbridge-control")] + [RequirePermission(PermissionKeys.RegistryWeighbridge)] + public Task SaveWeighbridgeControl(SaveWeighbridgeControlRequest request, CancellationToken ct) => + ops.SaveWeighbridgeControlAsync(request, ct); + + /// saveGrainsWeights. + [HttpPost("permit-weights")] + [RequirePermission(PermissionKeys.OrdersWeights)] + public Task SaveGrainsWeights(SaveGrainsWeightsRequest request, CancellationToken ct) => ops.SaveGrainsWeightsAsync(request, ct); + + /// getlocTruckNum (locTruckNumGrid.cfm, refreshed every 5 minutes by the screen). + [HttpGet("location-truck-counts")] + [RequirePermission(PermissionKeys.RegistryLocationCounts)] + public Task> LocationTruckCounts(CancellationToken ct) => ops.LocationTruckCountsAsync(ct); + + /// checkTrucks: every company must use its whole fleet before reusing a truck. + [HttpPost("fleet-check")] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.PermitsQueue)] + public Task FleetCheck(FleetCheckRequest request, CancellationToken ct) => ops.CheckTrucksAsync(request, ct); + + /// validateNtpTrucks. + [HttpGet("validate-truck")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public async Task ValidateTruck([FromQuery] string tn, CancellationToken ct) => new { validTn = await ops.ValidateNtpTruckAsync(tn ?? string.Empty, ct) }; + + // ------------------------------------------------------------------------------------------ permit-screen lookups (grains.cfc) + + /// grains.cfc getDriverInfo: latest permit of the driver (active status). + [HttpGet("permit-lookups/driver")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public Task DriverFromPermits([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverFromPermitsAsync(nnpn ?? string.Empty, ct); + + /// grains.cfc getTruckInfo: latest finished permit of the truck. + [HttpGet("permit-lookups/truck")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public Task TruckFromPermits([FromQuery] string tn, CancellationToken ct) => lookups.TruckFromPermitsAsync(tn ?? string.Empty, ct); + + /// grains.cfc isTrailerInUse. + [HttpGet("permit-lookups/trailer-in-use")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public Task> TrailerInUse([FromQuery] string trn, [FromQuery] long? permitId, CancellationToken ct) => + lookups.TrailerInUseAsync(trn ?? string.Empty, permitId, ct); + + /// grains.cfc getTruckInfoFromTN. + [HttpGet("permit-lookups/permit-by-truck")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public Task PermitByTruck([FromQuery] string tn, [FromQuery] string status, CancellationToken ct) => + lookups.PermitByTruckAsync(tn ?? string.Empty, status ?? string.Empty, ct); + + /// grains.cfc getTrailerNumber: the trailer of a truck. + [HttpGet("permit-lookups/truck-trailer")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public Task TruckTrailer([FromQuery] string tn, CancellationToken ct) => lookups.TrailerNumberOfTruckAsync(tn ?? string.Empty, ct); + + /// grains.cfc getTNinfo (validate = ownership + MOT checks). + [HttpGet("permit-lookups/truck-info")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public Task TruckInfo([FromQuery] string tn, [FromQuery] bool validate = true, CancellationToken ct = default) => + lookups.TruckInfoAsync(tn ?? string.Empty, validate, ct); + + /// grains.cfc getTRNinfo. + [HttpGet("permit-lookups/trailer-info")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public Task TrailerInfo([FromQuery] string trn, CancellationToken ct) => lookups.TrailerInfoAsync(trn ?? string.Empty, ct); + + /// grains.cfc getDRVRinfo. + [HttpGet("permit-lookups/driver-info")] + [RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public Task DriverInfo([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverInfoAsync(nnpn ?? string.Empty, ct); + + // ------------------------------------------------------------------------------------------ MOT (register.cfc validate*) + + /// validateTNMOT: result '' (ok), 'not_registered' or 'wrongCT'. + [HttpGet("mot/truck")] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)] + public async Task MotTruck([FromQuery] string tn, [FromQuery] long scac, [FromQuery] string? truckType, CancellationToken ct) => + new { result = await lookups.ValidateTruckMotAsync(tn ?? string.Empty, scac, truckType, ct) }; + + /// validateTRNMOT: result '' (ok) or 'not_registered'. + [HttpGet("mot/trailer")] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)] + public async Task MotTrailer([FromQuery] string trn, [FromQuery] long scac, CancellationToken ct) => + new { result = await lookups.ValidateTrailerMotAsync(trn ?? string.Empty, scac, ct) }; + + /// validateOwnerTN: message '' (ok) or the legacy Arabic error. + [HttpGet("mot/owner")] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)] + public async Task MotOwner([FromQuery] string tn, [FromQuery] long scac, CancellationToken ct) => + new { message = await lookups.ValidateOwnerAsync(scac, tn ?? string.Empty, ct) }; + + // ------------------------------------------------------------------------------------------ attachments + + /// Temp upload: returns { id, name, size }; the id goes into attachmentIds of a save request. + [HttpPost("files/temp")] + [RequestSizeLimit(20_000_000)] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public async Task UploadTemp(IFormFile file, CancellationToken ct) + { + await using var stream = file.OpenReadStream(); + return await attachments.UploadTempAsync(stream, file.FileName, file.Length, ct); + } + + /// Downloads a stored attachment (kind: truck | trailer | driver). + [HttpGet("files/{kind}/{fileName}")] + [RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)] + public async Task Download(string kind, string fileName, CancellationToken ct) + { + var download = await attachments.OpenAsync(kind, fileName, ct); + Response.Headers.ContentDisposition = $"inline; filename*=UTF-8''{Uri.EscapeDataString(download.FileName)}"; + return File(download.Content, download.ContentType); + } + + // ------------------------------------------------------------------------------------------ scheduled jobs (call from the scheduler with a token) + + /// jobs\changeBlacklistStatus.cfm: OPEN entries past their expiry date become EXPIRED. + [HttpPost("jobs/expire-blacklist")] + [Authorize(Roles = "SU")] + public async Task ExpireBlacklist(CancellationToken ct) => new { expired = await blacklist.ExpireDueAsync(ct) }; + + /// jobs\RegisterGrainsQueueForNewTrucks.cfm: PCKD + BULK queue permits for 327 trucks that have none. + [HttpPost("jobs/register-queue-new-trucks")] + [Authorize(Roles = "SU")] + public async Task RegisterQueueForNewTrucks(CancellationToken ct) => new { trucks = await queuePermits.RegisterQueueForNewTrucksAsync(ct) }; +} diff --git a/src/NTP.Api/Controllers/V1/Grains/ReportsController.cs b/src/NTP.Api/Controllers/V1/Grains/ReportsController.cs new file mode 100644 index 0000000..bc96905 --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Grains/ReportsController.cs @@ -0,0 +1,163 @@ +using Asp.Versioning; +using NTP.Api.Authorization; +using NTP.Application.Access; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using NTP.Application.Common; +using NTP.Application.Grains.Reports; + +namespace NTP.Api.Controllers.V1.Grains; + +/// +/// Grains reports, dashboards, MOT reports and the file imports (legacy reports.cfc, Reports\*.cfm, *.cfr, ParseFile.cfc, ReadFiles\*). +/// Tabular reports share one shape: GET tables/{key} (paged JSON for the grid) and GET tables/{key}/export (xlsx). +/// +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/reports")] +[Produces("application/json")] +public sealed class ReportsController( + IReportsService reports, IPhoneApprovalImportService phoneImport, IWeighbridgeFileService files, + IPermissionService permissions) : ControllerBase +{ + private const string Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + private const long MaxUpload = 20 * 1024 * 1024; + + // ------------------------------------------------------------------ lookups for the filter forms + [HttpGet("lookups/companies")] + [RequirePermission(PermissionKeys.ReportsDashboard, PermissionKeys.ReportsFrequency, PermissionKeys.ReportsDistribution, PermissionKeys.ReportsDetails, PermissionKeys.ReportsNumOfTrips, PermissionKeys.ReportsQuota, PermissionKeys.TableKeyPrefix + "weighbridge-events", PermissionKeys.TableKeyPrefix + "waybridge-summary", PermissionKeys.TableKeyPrefix + "waybridge-details", PermissionKeys.TableKeyPrefix + "companies-turn", PermissionKeys.TableKeyPrefix + "owners-turn", PermissionKeys.TableKeyPrefix + "loading-weights", PermissionKeys.TableKeyPrefix + "closed-permits", PermissionKeys.TableKeyPrefix + "incapability")] + public Task> Companies(CancellationToken ct) => reports.CompaniesAsync(ct); + + [HttpGet("lookups/cargo-types")] + [RequirePermission(PermissionKeys.ReportsDashboard, PermissionKeys.ReportsFrequency, PermissionKeys.ReportsDistribution, PermissionKeys.ReportsDetails, PermissionKeys.ReportsNumOfTrips, PermissionKeys.ReportsQuota, PermissionKeys.TableKeyPrefix + "weighbridge-events", PermissionKeys.TableKeyPrefix + "waybridge-summary", PermissionKeys.TableKeyPrefix + "waybridge-details", PermissionKeys.TableKeyPrefix + "companies-turn", PermissionKeys.TableKeyPrefix + "owners-turn", PermissionKeys.TableKeyPrefix + "loading-weights", PermissionKeys.TableKeyPrefix + "closed-permits", PermissionKeys.TableKeyPrefix + "incapability")] + public Task> CargoTypes(CancellationToken ct) => reports.CargoTypesAsync(ct); + + [HttpGet("lookups/destinations")] + [RequirePermission(PermissionKeys.ReportsDashboard, PermissionKeys.ReportsFrequency, PermissionKeys.ReportsDistribution, PermissionKeys.ReportsDetails, PermissionKeys.ReportsNumOfTrips, PermissionKeys.ReportsQuota, PermissionKeys.TableKeyPrefix + "weighbridge-events", PermissionKeys.TableKeyPrefix + "waybridge-summary", PermissionKeys.TableKeyPrefix + "waybridge-details", PermissionKeys.TableKeyPrefix + "companies-turn", PermissionKeys.TableKeyPrefix + "owners-turn", PermissionKeys.TableKeyPrefix + "loading-weights", PermissionKeys.TableKeyPrefix + "closed-permits", PermissionKeys.TableKeyPrefix + "incapability")] + public Task> Destinations([FromQuery] string? shipmentMode, CancellationToken ct) => + reports.DestinationsAsync(shipmentMode, ct); + + // ------------------------------------------------------------------ trips reports (print/PDF pages) and dashboard + [HttpGet("trips/num-of-trips-and-trucks")] + [RequirePermission(PermissionKeys.ReportsNumOfTrips)] + public Task NumOfTripsAndTrucks([FromQuery] DateOnly from, [FromQuery] DateOnly to, CancellationToken ct) => + reports.NumOfTripsAndTrucksAsync(from, to, ct); + + [HttpGet("trips/quota")] + [RequirePermission(PermissionKeys.ReportsQuota)] + public Task Quota([FromQuery] DateOnly from, [FromQuery] DateOnly to, CancellationToken ct) => + reports.QuotaAsync(from, to, ct); + + [HttpGet("trips/frequency")] + [RequirePermission(PermissionKeys.ReportsFrequency)] + public Task Frequency([FromQuery] DateOnly from, [FromQuery] DateOnly to, [FromQuery] string? scac, + [FromQuery] string? cargoType, CancellationToken ct) => reports.FrequencyAsync(from, to, scac, cargoType, ct); + + /// TripsDistributionRpt (grouped 1-3, 4-6...) uses the same data as the frequency report (field groups). + [HttpGet("trips/distribution")] + [RequirePermission(PermissionKeys.ReportsDistribution)] + public Task Distribution([FromQuery] DateOnly from, [FromQuery] DateOnly to, CancellationToken ct) => + reports.FrequencyAsync(from, to, null, null, ct); + + [HttpGet("trips/details")] + [RequirePermission(PermissionKeys.ReportsDetails)] + public Task Details([FromQuery] DateOnly from, [FromQuery] DateOnly to, CancellationToken ct) => + reports.DetailsAsync(from, to, ct); + + /// grainsDashboards.cfm: charts input (trucks per number of trips) with optional company / cargo filter. + [HttpGet("dashboard")] + [RequirePermission(PermissionKeys.ReportsDashboard)] + public Task Dashboard([FromQuery] DateOnly from, [FromQuery] DateOnly to, [FromQuery] string? scac, + [FromQuery] string? cargoType, CancellationToken ct) => reports.FrequencyAsync(from, to, scac, cargoType, ct); + + // ------------------------------------------------------------------ MOT + [HttpGet("mot/multi-trips")] + [RequirePermission(PermissionKeys.ReportsMotMulti)] + public Task MotMultiTrips(CancellationToken ct) => reports.MotMultiTripsAsync(ct); + + // ------------------------------------------------------------------ table reports + [HttpGet("tables/{key}")] + public async Task Table(string key, [FromQuery] ReportFilter filter, [FromQuery] int page = 1, + [FromQuery] int pageSize = 50, CancellationToken ct = default) + { + await EnsureTableAllowedAsync(key, ct); + return await reports.PageAsync(key, filter, page, pageSize, ct); + } + + [HttpGet("tables/{key}/export")] + [Produces(Xlsx)] + public async Task Export(string key, [FromQuery] ReportFilter filter, CancellationToken ct) + { + await EnsureTableAllowedAsync(key, ct); + var (content, name) = await reports.ExportAsync(key, filter, ct); + return File(content, Xlsx, name); + } + + // ------------------------------------------------------------------ imports + + /// uploadAccptExlFile.cfm: IVR approvals file (CSV or XLSX) -> one accept / reject per row. + [HttpPost("imports/phone-approvals")] + [RequestSizeLimit(MaxUpload)] + [Authorize(Roles = "SU")] + public async Task ImportPhoneApprovals(IFormFile file, CancellationToken ct) + { + Check(file); + await using var s = file.OpenReadStream(); + return await phoneImport.ImportAsync(s, file.FileName, ct); + } + + [HttpPost("weighbridge-files/irbid")] + [Authorize(Roles = "SU")] + [RequestSizeLimit(MaxUpload)] + public async Task ImportIrbid(IFormFile file, CancellationToken ct) + { + Check(file); + await using var s = file.OpenReadStream(); + return await files.ImportIrbidAsync(s, file.FileName, ct); + } + + [HttpPost("weighbridge-files/original")] + [Authorize(Roles = "SU")] + [RequestSizeLimit(MaxUpload)] + public async Task ImportOriginal(IFormFile file, [FromQuery] bool replaceExisting = false, CancellationToken ct = default) + { + Check(file); + await using var s = file.OpenReadStream(); + return await files.ImportOriginalAsync(s, file.FileName, replaceExisting, ct); + } + + [HttpPost("weighbridge-files/rsifeh")] + [Authorize(Roles = "SU")] + [RequestSizeLimit(MaxUpload)] + public async Task ImportRsifeh(IFormFile file, CancellationToken ct) + { + Check(file); + await using var s = file.OpenReadStream(); + return await files.ImportRsifehAsync(s, file.FileName, ct); + } + + public sealed record ScanRequest(string Directory, string? ArchiveDirectory); + + /// One pass of the directory watcher (the background watcher itself is disabled by default). + [HttpPost("weighbridge-files/scan")] + [Authorize(Roles = "SU")] + public Task Scan(ScanRequest request, CancellationToken ct) => + files.ScanDirectoryAsync(request.Directory, request.ArchiveDirectory, ct); + + /// jobs/getWeighbridgeEvents.cfm (matching half): raw weighbridge rows -> permit events + CLOSE. + [HttpPost("weighbridge-files/raw-sync")] + [Authorize(Roles = "SU")] + public Task RawSync(CancellationToken ct) => files.SyncRawDataAsync(ct); + + /// The table key is dynamic, so the permission is checked here instead of with an attribute. + private async Task EnsureTableAllowedAsync(string key, CancellationToken ct) + { + if (!await permissions.IsAllowedAsync(PermissionKeys.ReportTable(key), ct)) + throw new ForbiddenException("FORBIDDEN_RESOURCE", "ليس لديك صلاحية للوصول إلى هذه الشاشة"); + } + + private static void Check(IFormFile? file) + { + if (file is null || file.Length == 0) throw new BusinessException("IMPORT_FILE_EMPTY", "الملف فارغ"); + } +} diff --git a/src/NTP.Api/Controllers/V1/Grains/WsController.cs b/src/NTP.Api/Controllers/V1/Grains/WsController.cs new file mode 100644 index 0000000..4c51b07 --- /dev/null +++ b/src/NTP.Api/Controllers/V1/Grains/WsController.cs @@ -0,0 +1,102 @@ +using System.Security.Cryptography; +using System.Text; +using Asp.Versioning; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Application.Grains.Reports; +using NTP.Infrastructure.Persistence.Repositories.Grains.Reports; + +namespace NTP.Api.Controllers.V1.Grains; + +/// +/// Authentication of the external web-service area: either a configured API key (header X-Api-Key, config +/// GrainsReports:Ws:ApiKeys) or a normal JWT bearer token. The app's fallback policy is bypassed with +/// [AllowAnonymous] on the controller, so THIS filter is the only gate: no valid key and no JWT => 401. +/// +public sealed class WsAuthFilter(IConfiguration configuration, ICurrentUser user) : IAsyncAuthorizationFilter +{ + public const string CallerKey = "grains.ws.caller"; + public const string HeaderName = "X-Api-Key"; + + public Task OnAuthorizationAsync(AuthorizationFilterContext context) + { + var http = context.HttpContext; + var presented = http.Request.Headers[HeaderName].FirstOrDefault(); + if (!string.IsNullOrEmpty(presented)) + { + var p = SHA256.HashData(Encoding.UTF8.GetBytes(presented)); + var ok = false; + foreach (var k in new GrainsReportsConfig(configuration).ApiKeys) + ok |= CryptographicOperations.FixedTimeEquals(p, SHA256.HashData(Encoding.UTF8.GetBytes(k))); // no early exit + if (ok) { http.Items[CallerKey] = WsService.TcsUser; return Task.CompletedTask; } + } + else if (user.IsAuthenticated) + { + http.Items[CallerKey] = string.IsNullOrEmpty(user.UserId) ? "system" : user.UserId; + return Task.CompletedTask; + } + http.Response.Headers.WWWAuthenticate = $"Bearer, {HeaderName}"; + var problem = new ProblemDetails + { + Status = StatusCodes.Status401Unauthorized, Title = "Unauthorized", Detail = "API key or bearer token required" + }; + problem.Extensions["code"] = "WS_UNAUTHORIZED"; + context.Result = new ObjectResult(problem) { StatusCode = StatusCodes.Status401Unauthorized }; + return Task.CompletedTask; + } +} + +/// External authenticated API used by weighbridge / TCS systems (legacy services\Grains\cfc\ws.cfc). +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/grains/ws")] +[Produces("application/json")] +[AllowAnonymous] +[TypeFilter(typeof(WsAuthFilter))] +public sealed class WsController(IWsService ws, IConfiguration configuration) : ControllerBase +{ + private string Caller => HttpContext.Items[WsAuthFilter.CallerKey] as string ?? "system"; + + [HttpGet("ping")] + public object Ping() => new { ok = true, caller = Caller }; + + /// getTrackNo(TN, TRNAT, CLOSEDATE) + [HttpPost("track-no")] + public Task GetTrackNo(GetTrackNoRequest request, CancellationToken ct) => ws.GetTrackNoAsync(request, Caller, ct); + + /// changeStatusToReqst(TN) + [HttpPost("status-to-requested")] + public Task ChangeStatusToReqst(ChangeStatusToReqstRequest request, CancellationToken ct) => + ws.ChangeStatusToReqstAsync(request, Caller, ct); + + /// saveShipmentInfo: commented out in the legacy ws.cfc, so disabled unless GrainsReports:Ws:EnableSaveShipmentInfo=true. + [HttpPost("shipment-info")] + public Task SaveShipmentInfo(SaveShipmentInfoRequest request, CancellationToken ct) + { + if (!new GrainsReportsConfig(configuration).SaveShipmentInfoEnabled) + throw new BusinessException("WS_OPERATION_DISABLED", "هذه العملية غير مفعلة"); + return ws.SaveShipmentInfoAsync(request, Caller, ct); + } + + /// addLoadingWeightEvent (pid is the plain permit id; the legacy encrypted id relied on the session key). + [HttpPost("loading-weight-event")] + public Task AddLoadingWeightEvent(LoadingWeightRequest request, CancellationToken ct) => + ws.AddLoadingWeightEventAsync(request, Caller, ct); + + [HttpPost("discharge-weight-event")] + public Task AddDischargeWeightEvent(LoadingWeightRequest request, CancellationToken ct) => + ws.AddDischargeWeightEventAsync(request, Caller, ct); + + /// createPermitRecord(TN, SCAC, NEXTSTATUS, TT, checkStatuses) + [HttpPost("permit-record")] + public Task CreatePermitRecord(CreatePermitRecordRequest request, CancellationToken ct) => + ws.CreatePermitRecordAsync(request, Caller, ct); + + /// addWeightBridgeEventWS (same as addWeightBridgeEvent + an audit row in GN_TCS_INTEGRATION). + [HttpPost("weighbridge-event")] + public Task AddWeightBridgeEvent(WeighbridgeEventRequest request, CancellationToken ct) => + ws.AddWeightBridgeEventWsAsync(request, Caller, HttpContext.Connection.RemoteIpAddress?.ToString(), ct); +} diff --git a/src/NTP.Api/Controllers/V1/LookupsController.cs b/src/NTP.Api/Controllers/V1/LookupsController.cs new file mode 100644 index 0000000..4dea806 --- /dev/null +++ b/src/NTP.Api/Controllers/V1/LookupsController.cs @@ -0,0 +1,38 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Mvc; +using NTP.Application.Lookups; + +namespace NTP.Api.Controllers.V1; + +/// Generic lookups only. Grains-specific lookups belong to the Grains slice controllers. Domain defaults to the caller's domain. +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/lookups")] +[Produces("application/json")] +public sealed class LookupsController(ILookupService service) : ControllerBase +{ + /// STATUS rows for a domain (e.g. GN). isActive=true -> ISACTIVE = 1. + [HttpGet("statuses")] + public Task> Statuses([FromQuery] string? domain, [FromQuery] bool? isActive, CancellationToken ct) => + service.StatusesAsync(domain, isActive, ct); + + /// LOCATIONS for a domain, optional type (LOC, EX, EN ...). Active only unless includeInactive. + [HttpGet("locations")] + public Task> Locations([FromQuery] string? domain, [FromQuery] string? type, + [FromQuery] bool includeInactive, CancellationToken ct) => + service.LocationsAsync(domain, type, includeInactive, ct); + + [HttpGet("cargo-types")] + public Task> CargoTypes([FromQuery] string? domain, CancellationToken ct) => + service.CargoTypesAsync(domain, ct); + + [HttpGet("companies")] + public Task> Companies([FromQuery] bool includeInactive, CancellationToken ct) => + service.CompaniesAsync(includeInactive, ct); + + [HttpGet("nationalities")] + public Task> Nationalities(CancellationToken ct) => service.NationalitiesAsync(ct); + + [HttpGet("cities")] + public Task> Cities(CancellationToken ct) => service.CitiesAsync(ct); +} diff --git a/src/NTP.Api/Controllers/V1/PermissionsController.cs b/src/NTP.Api/Controllers/V1/PermissionsController.cs new file mode 100644 index 0000000..1c9f1e0 --- /dev/null +++ b/src/NTP.Api/Controllers/V1/PermissionsController.cs @@ -0,0 +1,17 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Mvc; +using NTP.Application.Access; + +namespace NTP.Api.Controllers.V1; + +/// Tells the front end which modules, screens and actions the caller's role code may see. +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/auth/permissions")] +[Produces("application/json")] +public sealed class PermissionsController(IPermissionService permissions) : ControllerBase +{ + /// { roleCode, all, allowed[] }. SU gets all = true and an empty list. + [HttpGet] + public Task Get(CancellationToken ct) => permissions.GetForCurrentUserAsync(ct); +} diff --git a/src/NTP.Api/Controllers/V1/ShipmentsController.cs b/src/NTP.Api/Controllers/V1/ShipmentsController.cs new file mode 100644 index 0000000..edd28bd --- /dev/null +++ b/src/NTP.Api/Controllers/V1/ShipmentsController.cs @@ -0,0 +1,57 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Mvc; +using NTP.Application.Common; +using NTP.Application.Shipments; + +namespace NTP.Api.Controllers.V1; + +/// SAMPLE controller - thin: HTTP in, service call, HTTP out. No SQL, no business rules. +[ApiController] +[ApiVersion(1.0)] +[Route("api/v{version:apiVersion}/shipments")] +[Produces("application/json")] +public sealed class ShipmentsController(IShipmentService service) : ControllerBase +{ + [HttpGet] + [ProducesResponseType>(StatusCodes.Status200OK)] + public Task> Search( + [FromQuery] string? shipmentNo, + [FromQuery] string? status, + [FromQuery] bool? isActive, + [FromQuery] int page = 1, + [FromQuery] int pageSize = 20, + CancellationToken ct = default) => + service.SearchAsync(new ShipmentQuery(shipmentNo, status, isActive), new PageRequest(page, pageSize), ct); + + [HttpGet("{id:long}", Name = nameof(GetShipment))] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public Task GetShipment(long id, CancellationToken ct) => service.GetAsync(id, ct); + + [HttpPost] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Create(CreateShipmentRequest request, CancellationToken ct) + { + var created = await service.CreateAsync(request, ct); + return CreatedAtRoute(nameof(GetShipment), + new { id = created.ShipmentId, version = "1" }, created); + } + + [HttpPut("{id:long}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public Task Update(long id, UpdateShipmentRequest request, CancellationToken ct) => + service.UpdateAsync(id, request, ct); + + [HttpDelete("{id:long}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + public async Task Delete(long id, [FromQuery] int rowVersion, CancellationToken ct) + { + await service.DeleteAsync(id, rowVersion, ct); + return NoContent(); + } +} diff --git a/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs b/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs new file mode 100644 index 0000000..9a0ee12 --- /dev/null +++ b/src/NTP.Api/ErrorHandling/GlobalExceptionHandler.cs @@ -0,0 +1,80 @@ +using FluentValidation; +using Microsoft.AspNetCore.Diagnostics; +using Microsoft.AspNetCore.Mvc; +using NTP.Application.Common; +using Oracle.ManagedDataAccess.Client; + +namespace NTP.Api.ErrorHandling; + +/// +/// Turns exceptions into RFC 7807 ProblemDetails. Oracle error codes are translated so clients +/// get meaningful 4xx/503 responses instead of a generic 500 - and raw ORA- text never leaks +/// outside Development. +/// +internal sealed class GlobalExceptionHandler( + IProblemDetailsService problemDetails, + IHostEnvironment env, + ILogger logger) : IExceptionHandler +{ + public async ValueTask TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct) + { + var (status, title, detail, errors) = Map(exception); + + 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 + ? new ProblemDetails() + : new ValidationProblemDetails(errors); + + problem.Status = status; + problem.Title = title; + problem.Detail = detail; + problem.Instance = http.Request.Path; + if (exception is OracleException ora) problem.Extensions["oraCode"] = $"ORA-{ora.Number:D5}"; + if (exception is BusinessException biz) problem.Extensions["code"] = biz.Code; + if (env.IsDevelopment() && status >= 500) problem.Extensions["exception"] = exception.ToString(); + + http.Response.StatusCode = status; + return await problemDetails.TryWriteAsync(new ProblemDetailsContext + { + HttpContext = http, + ProblemDetails = problem, + Exception = exception + }); + } + + private static (int Status, string Title, string? Detail, IDictionary? Errors) Map(Exception ex) => + ex switch + { + 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. + AuthenticationFailedException af => (401, af.Message, af.Message, null), + ForbiddenException fe => (403, fe.Message, fe.Message, null), + BusinessException be => (422, be.Message, be.Message, null), + NotFoundException nf => (404, "Not found", nf.Message, null), + ConcurrencyException cc => (409, "Concurrency conflict", cc.Message, null), + OracleException ora => MapOracle(ora), + OperationCanceledException => (499, "Request cancelled", null, null), + _ => (500, "Unexpected server error", null, null) + }; + + private static (int, string, string?, IDictionary?) MapOracle(OracleException ora) => ora.Number switch + { + 1 => (409, "Duplicate value", "A record with the same unique key already exists.", null), // ORA-00001 + 2291 => (409, "Related record not found", "A referenced parent record does not exist.", null), // ORA-02291 + 2292 => (409, "Record in use", "The record is referenced by other records and cannot be removed.", null), // ORA-02292 + 1400 => (400, "Missing required value", "A required column was null.", null), // ORA-01400 + 12899 => (400, "Value too large", "A value exceeds the column size.", null), // ORA-12899 + 1438 => (400, "Number too large", "A numeric value exceeds the column precision.", null), // ORA-01438 + 54 or 30006 => (409, "Record locked", "The record is locked by another session. Retry shortly.", null), // ORA-00054 + 1013 => (504, "Database timeout", "The database operation timed out.", null), // ORA-01013 + // Connectivity / instance availability + 3113 or 3114 or 3135 or 12170 or 12514 or 12528 or 12537 or 12541 or 12543 or 1033 or 1034 or 1089 => + (503, "Database unavailable", "The database is temporarily unavailable.", null), + _ => (500, "Database error", null, null) + }; +} diff --git a/src/NTP.Api/NTP.Api.csproj b/src/NTP.Api/NTP.Api.csproj new file mode 100644 index 0000000..3074b91 --- /dev/null +++ b/src/NTP.Api/NTP.Api.csproj @@ -0,0 +1,19 @@ + + + ntp-api-7c1e2f4a + + + + + + + + + + + + + + + + diff --git a/src/NTP.Api/Program.cs b/src/NTP.Api/Program.cs new file mode 100644 index 0000000..1985cef --- /dev/null +++ b/src/NTP.Api/Program.cs @@ -0,0 +1,70 @@ +using Asp.Versioning; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; +using Microsoft.Extensions.Options; +using NTP.Api.Auth; +using NTP.Api.ErrorHandling; +using NTP.Application; +using NTP.Infrastructure; +using NTP.Infrastructure.Persistence; + +var builder = WebApplication.CreateBuilder(args); + +// Optional per-machine overrides (git-ignored). Copy appsettings.Local.example.json to start. +builder.Configuration.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: false); + +builder.Services.AddControllers(); + +builder.Services + .AddApiVersioning(o => + { + o.DefaultApiVersion = new ApiVersion(1, 0); + o.AssumeDefaultVersionWhenUnspecified = true; + o.ReportApiVersions = true; + o.ApiVersionReader = new UrlSegmentApiVersionReader(); + }) + .AddMvc() + .AddApiExplorer(o => + { + o.GroupNameFormat = "'v'VVV"; // -> "v1", matches the OpenAPI document name + o.SubstituteApiVersionInUrl = true; // /api/v1/... instead of /api/v{version}/... + }); + +builder.Services.AddOpenApi("v1", o => o.AddDocumentTransformer()); +builder.Services.AddProblemDetails(); +builder.Services.AddExceptionHandler(); + +builder.Services.AddNtpAuthentication(builder.Configuration, builder.Environment); + +// CORS for the Vite dev server (Cors:AllowedOrigins). Bearer tokens, so no credentials needed. +var corsOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get() ?? ["http://localhost:5173"]; +builder.Services.AddCors(o => o.AddPolicy("Frontend", p => p.WithOrigins(corsOrigins).AllowAnyHeader().AllowAnyMethod())); + +builder.Services.AddApplication(); +builder.Services.AddInfrastructure(builder.Configuration); + +var app = builder.Build(); + +// Fails fast here if no connection is configured; logs the target DB without the password. +var oracle = app.Services.GetRequiredService>().Value; +app.Logger.LogInformation("Oracle connection: {ConnectionString}", oracle.ToSafeString()); + +app.UseCors("Frontend"); // first, so error responses also carry CORS headers +app.UseExceptionHandler(); +app.UseStatusCodePages(); + +if (app.Environment.IsDevelopment()) +{ + app.MapOpenApi().AllowAnonymous(); // /openapi/v1.json + app.UseSwaggerUI(o => o.SwaggerEndpoint("/openapi/v1.json", "NTP API v1")); +} + +app.UseHttpsRedirection(); +app.UseAuthentication(); +app.UseAuthorization(); +app.MapControllers(); + +// Liveness: process is up. Readiness: Oracle reachable. +app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false }).AllowAnonymous(); +app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = c => c.Tags.Contains("ready") }).AllowAnonymous(); + +app.Run(); diff --git a/src/NTP.Api/Properties/launchSettings.json b/src/NTP.Api/Properties/launchSettings.json new file mode 100644 index 0000000..c2800d2 --- /dev/null +++ b/src/NTP.Api/Properties/launchSettings.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7180;http://localhost:5180", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https-qa": { + "commandName": "Project", + "launchBrowser": false, + "applicationUrl": "https://localhost:7181;http://localhost:5181", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "QA" + } + } + } +} diff --git a/src/NTP.Api/appsettings.Development.json b/src/NTP.Api/appsettings.Development.json new file mode 100644 index 0000000..545ff69 --- /dev/null +++ b/src/NTP.Api/appsettings.Development.json @@ -0,0 +1,18 @@ +{ + "Auth": { + "SuperUsers": [ "samer", "QA", "MATHHER" ] + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "NTP.Infrastructure": "Debug" + } + }, + "Oracle": { + "Host": "dev-oracle-host", + "Port": 1521, + "ServiceName": "ORCL", + "UserId": "NTP_APP" + // Password: set in appsettings.Local.json, user-secrets, or env var Oracle__Password + } +} diff --git a/src/NTP.Api/appsettings.Local.example.json b/src/NTP.Api/appsettings.Local.example.json new file mode 100644 index 0000000..11775c2 --- /dev/null +++ b/src/NTP.Api/appsettings.Local.example.json @@ -0,0 +1,17 @@ +{ + // Copy this file to appsettings.Local.json (git-ignored) and fill in your own values. + // It is loaded last, so anything here overrides appsettings.json / appsettings.{Environment}.json. + + // TWO connections (legacy ColdFusion datasources): + // NAFITHTCS = primary (IDbSession / OracleRepositoryBase): PERMITS, NTP_TRUCKS, EVENTS, GRAINS*, UTT, LOCATIONS, STATUS ... + // NtpSchema = NTP schema (INtpDbSession / NtpRepositoryBase): NTPUSERS, ROLES, LOGS, COMPANIES, NATIONALITY ... + "ConnectionStrings": { + "NAFITHTCS": "User Id=NAFITHTCS;Password=;Data Source=:1521/;Min Pool Size=1;Max Pool Size=50;Connection Timeout=15;Statement Cache Size=50", + "NtpSchema": "User Id=NTP;Password=;Data Source=:1521/;Min Pool Size=1;Max Pool Size=50;Connection Timeout=15;Statement Cache Size=50" + }, + + // JWT signing key - DEV ONLY value, min 32 characters. In production use env var Jwt__Key (a long random secret). + "Jwt": { + "Key": "dev-only-ntp-signing-key-change-me-0123456789" + } +} diff --git a/src/NTP.Api/appsettings.Production.json b/src/NTP.Api/appsettings.Production.json new file mode 100644 index 0000000..a3081ff --- /dev/null +++ b/src/NTP.Api/appsettings.Production.json @@ -0,0 +1,24 @@ +{ + // Production environment (ASPNETCORE_ENVIRONMENT=Production). Only NON-SECRET settings live in this file; see docs/ENVIRONMENTS.md. + // Supplied by the production server environment (environment variables / secret store), never committed: + // ConnectionStrings__NAFITHTCS, ConnectionStrings__NtpSchema Oracle connection strings of the production database + // Jwt__Key JWT signing key, at least 32 random characters (the app will not start without it) + // Cors__AllowedOrigins__0 origin of the production web app, e.g. https:// + // Auth__SuperUsers__0 ... logins that may hold role SU (none by default in production) + "Logging": { + "LogLevel": { + "Default": "Warning", + "NTP": "Information" + } + }, + + // Index 0 replaces the localhost default of appsettings.json. Until it is set the API allows no browser origin (fails closed). + "Cors": { + "AllowedOrigins": [ "https://REPLACE-WITH-PRODUCTION-WEB-ORIGIN" ] + }, + + "Oracle": { + "MinPoolSize": 5, + "MaxPoolSize": 100 + } +} diff --git a/src/NTP.Api/appsettings.QA.json b/src/NTP.Api/appsettings.QA.json new file mode 100644 index 0000000..4818854 --- /dev/null +++ b/src/NTP.Api/appsettings.QA.json @@ -0,0 +1,28 @@ +{ + // QA environment (ASPNETCORE_ENVIRONMENT=QA). Only NON-SECRET settings live in this file; see docs/ENVIRONMENTS.md. + // Supplied by the QA server environment (environment variables / secret store), never committed: + // ConnectionStrings__NAFITHTCS, ConnectionStrings__NtpSchema Oracle connection strings of the QA database + // Jwt__Key JWT signing key, at least 32 random characters + // Cors__AllowedOrigins__0 origin of the QA web app, e.g. https:// + "Logging": { + "LogLevel": { + "Default": "Information", + "NTP.Infrastructure": "Information" + } + }, + + // Index 0 replaces the localhost default of appsettings.json. Until it is set the API allows no browser origin (fails closed). + "Cors": { + "AllowedOrigins": [ "https://REPLACE-WITH-QA-WEB-ORIGIN" ] + }, + + // Role SU is only granted to these logins (Application.cfc). QA keeps the same people as development. + "Auth": { + "SuperUsers": [ "samer", "QA", "MATHHER" ] + }, + + "Oracle": { + "MinPoolSize": 2, + "MaxPoolSize": 50 + } +} diff --git a/src/NTP.Api/appsettings.json b/src/NTP.Api/appsettings.json new file mode 100644 index 0000000..d63cad0 --- /dev/null +++ b/src/NTP.Api/appsettings.json @@ -0,0 +1,52 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + + // Jwt:Key is a SECRET (min 32 chars): set it via env var Jwt__Key, user-secrets or appsettings.Local.json. + // The app refuses to start outside Development when it is missing. + "Jwt": { + "Key": "", + "Issuer": "NTP", + "Audience": "NTP.Web", + "ExpiryMinutes": 480, + "ActiveCheckCacheSeconds": 10 + }, + + // Application.cfc: role SU is only allowed for these logins. Empty here on purpose: Development and QA list their own logins + // (appsettings.Development.json / appsettings.QA.json); production sets Auth__SuperUsers__0... in its environment. + "Auth": { + "SuperUsers": [] + }, + + "Cors": { + "AllowedOrigins": [ "http://localhost:5173" ] + }, + + // 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": { + "NAFITHTCS": "", + "NtpSchema": "" + }, + + // Option B - individual settings (used for the PRIMARY connection when ConnectionStrings:NAFITHTCS is empty). + // Put real passwords in appsettings.Local.json or environment variables, not in this file. + "Oracle": { + "Host": "", + "Port": 1521, + "ServiceName": "", + "Sid": "", + "UserId": "", + "Password": "", + "MinPoolSize": 1, + "MaxPoolSize": 50, + "ConnectionTimeoutSeconds": 15, + "StatementCacheSize": 50, + "CommandTimeoutSeconds": 30 + } +} diff --git a/src/NTP.Application/Abstractions/ICurrentUser.cs b/src/NTP.Application/Abstractions/ICurrentUser.cs new file mode 100644 index 0000000..4d69f9a --- /dev/null +++ b/src/NTP.Application/Abstractions/ICurrentUser.cs @@ -0,0 +1,69 @@ +namespace NTP.Application.Abstractions; + +/// +/// The authenticated caller. Replaces legacy session.*. Values come from JWT claims (see ); +/// when the request is anonymous strings are empty and numbers null/0. +/// +public interface ICurrentUser +{ + bool IsAuthenticated { get; } + /// NTPUSERS.ID. + long Id { get; } + /// Upper-cased login, like legacy session.userid. + string UserId { get; } + /// legacy session.username (NTPUSERS.FIRSTNAME). + string Name { get; } + /// legacy session.userRoleCode. + string RoleCode { get; } + /// legacy session.rolecodeName (ROLES.NAME). + string RoleName { get; } + /// legacy session.domain (NTPUSERS.DOMAINNAME, e.g. ASEZA, GN). + string Domain { get; } + long? LocationId { get; } + string LocationName { get; } + /// legacy session.STKID (GROUPS.STAKEHOLDERID). + long? StkId { get; } + /// legacy session.COMPID (hierarchy query companyid). + long? CompId { get; } + /// legacy session.CompanyId. + long? CompanyId { get; } + string CompanyName { get; } + /// legacy session.companyCode (COMPANIES.DESCRIPTION). + string CompanyCode { get; } + string EmpNo { get; } + /// "AR" or "EN". + string Lang { get; } + /// legacy session.nafithEmp (CompanyId = 15). + bool IsStaff { get; } + + /// Case-insensitive role-code check (legacy listFindNoCase(..., session.userrolecode)). + bool IsInRole(string roleCode); + bool IsInAnyRole(params string[] roleCodes); +} + +/// JWT claim names shared by the token issuer and . +public static class AppClaims +{ + public const string UserId = "sub"; + public const string Id = "uid"; + public const string Name = "name"; + public const string Role = "role"; + public const string RoleName = "role_name"; + public const string Domain = "domain"; + public const string LocationId = "loc_id"; + public const string LocationName = "loc_name"; + public const string StkId = "stk_id"; + public const string CompId = "comp_id"; + public const string CompanyId = "company_id"; + public const string CompanyName = "company_name"; + public const string CompanyCode = "company_code"; + public const string EmpNo = "empno"; + public const string Lang = "lang"; + public const string IsStaff = "staff"; +} + +/// Issues the signed access token (implemented in Api). +public interface ITokenIssuer +{ + (string Token, DateTime ExpiresAtUtc) Issue(NTP.Application.Auth.AuthenticatedUser user); +} diff --git a/src/NTP.Application/Abstractions/IEventLogger.cs b/src/NTP.Application/Abstractions/IEventLogger.cs new file mode 100644 index 0000000..986bbce --- /dev/null +++ b/src/NTP.Application/Abstractions/IEventLogger.cs @@ -0,0 +1,32 @@ +namespace NTP.Application.Abstractions; + +/// +/// One row of the legacy EVENTS audit table (port of services.cfc addEvent). +/// RefColumn is the id column to fill: PERMITID, CRID, ORDERID, WAYBILLID (any identifier ^[A-Z][A-Z0-9_]{0,29}$). +/// +public sealed record EventEntry( + string RefColumn, + long RefId, + string? PrevStatus, + string? CurrentStatus, + string? DoneBy, + string EventType, + string? Domain, + string? LocationId, + string UpdatedType = "NTP", + string? Weight = null, + IReadOnlyDictionary? ExtraColumns = null); + +public interface IEventLogger +{ + /// + /// Inserts into EVENTS using SEQ_EVENTS.nextval and bind variables. Participates in the active + /// unit-of-work transaction. DONEBY is upper-cased (legacy). Extra column names are validated as plain Oracle + /// identifiers and must not collide with the fixed columns; they must exist on EVENTS (e.g. REMARKS). + /// + Task AddAsync(EventEntry entry, CancellationToken ct = default); + + /// Same, taking DoneBy/Domain/LocationId from (legacy session.userid/domain/locationid). + Task AddForCurrentUserAsync(string refColumn, long refId, string? prevStatus, string? currentStatus, + string eventType, string? remarks = null, string? weight = null, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Abstractions/IShipmentRepository.cs b/src/NTP.Application/Abstractions/IShipmentRepository.cs new file mode 100644 index 0000000..71ff1ee --- /dev/null +++ b/src/NTP.Application/Abstractions/IShipmentRepository.cs @@ -0,0 +1,19 @@ +using NTP.Application.Common; +using NTP.Application.Shipments; +using NTP.Domain.Entities; + +namespace NTP.Application.Abstractions; + +public interface IShipmentRepository +{ + Task GetByIdAsync(long id, CancellationToken ct = default); + Task> SearchAsync(ShipmentQuery query, PageRequest page, CancellationToken ct = default); + Task ExistsByNumberAsync(string shipmentNo, long? excludeId = null, CancellationToken ct = default); + Task InsertAsync(Shipment shipment, CancellationToken ct = default); + + /// Number of rows affected (0 = not found or concurrency conflict). + Task UpdateAsync(Shipment shipment, CancellationToken ct = default); + + /// Number of rows affected. + Task DeleteAsync(long id, int rowVersion, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Abstractions/IUnitOfWork.cs b/src/NTP.Application/Abstractions/IUnitOfWork.cs new file mode 100644 index 0000000..bc1fcba --- /dev/null +++ b/src/NTP.Application/Abstractions/IUnitOfWork.cs @@ -0,0 +1,21 @@ +namespace NTP.Application.Abstractions; + +/// +/// Wraps a single Oracle connection + optional transaction for the current request. +/// Repositories resolved in the same scope automatically enlist in the active transaction. +/// +public interface IUnitOfWork +{ + Task BeginAsync(CancellationToken ct = default); + Task CommitAsync(CancellationToken ct = default); + Task RollbackAsync(CancellationToken ct = default); + + /// Runs inside a transaction; commits on success, rolls back on exception. + Task ExecuteInTransactionAsync(Func> work, CancellationToken ct = default); +} + +/// +/// Unit of work on the second connection (NTP schema: NTPUSERS, LOGS ...). Separate from +/// (primary NAFITHTCS connection); there is no distributed transaction across the two. +/// +public interface INtpUnitOfWork : IUnitOfWork; diff --git a/src/NTP.Application/Access/PermissionDefaults.cs b/src/NTP.Application/Access/PermissionDefaults.cs new file mode 100644 index 0000000..8df346d --- /dev/null +++ b/src/NTP.Application/Access/PermissionDefaults.cs @@ -0,0 +1,103 @@ +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 key of each entry (see web/src/features/*/routes.tsx). +/// +public static class PermissionKeys +{ + // Screens (menu keys) + public const string OrdersList = "grains.orders.list"; + /// Action: new order (طلبية جديدة) button, create page and POST /orders. + public const string OrdersCreate = "grains.orders.create"; + public const string OrdersQuotas = "grains.orders.quotas"; + public const string OrdersBilling = "grains.orders.billing"; + public const string OrdersInvoices = "grains.orders.invoices"; + public const string OrdersWeights = "grains.orders.weights"; + public const string OrdersCompanyDest = "grains.orders.companyDest"; + public const string OrdersReportOrders = "grains.orders.reportOrders"; + public const string OrdersReportFinance = "grains.orders.reportFinance"; + + public const string PermitsList = "grains.permits.list"; + public const string PermitsQueue = "grains.permits.queue"; + public const string PermitsDestinations = "grains.permits.destinations"; + public const string PermitsDistribution = "grains.permits.distribution"; + public const string PermitsWeighbridge = "grains.permits.weighbridge"; + + public const string RegistryTrucks = "grains.registry.trucks"; + public const string RegistryTrailers = "grains.registry.trailers"; + public const string RegistryDrivers = "grains.registry.drivers"; + public const string RegistryBlacklist = "grains.registry.blacklist"; + public const string RegistryWeighbridge = "grains.registry.weighbridge"; + public const string RegistryLocationCounts = "grains.registry.locationCounts"; + + // Actions: register (add) a truck / trailer / driver. Granted ONLY by rows in GRAINS_SCREEN_PERMISSIONS (SU always). + public const string RegistryTrucksCreate = "grains.registry.trucks.create"; + public const string RegistryTrailersCreate = "grains.registry.trailers.create"; + public const string RegistryDriversCreate = "grains.registry.drivers.create"; + + // Actions: edit an existing truck / trailer (the record status rules still apply). Granted ONLY by rows in GRAINS_SCREEN_PERMISSIONS. + public const string RegistryTrucksEdit = "grains.registry.trucks.edit"; + public const string RegistryTrailersEdit = "grains.registry.trailers.edit"; + + // 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 + public const string PermitsTruckStatus = "grains.permits.truckStatus"; // legacy distributionDetails.cfm + 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 + + // Report screens outside the business sheet allow-list: SU only (no seed rows) + public const string ReportsDashboard = "grains.reports.dashboard"; + public const string ReportsNumOfTrips = "grains.reports.numOfTrips"; + public const string ReportsQuota = "grains.reports.quota"; + public const string ReportsFrequency = "grains.reports.frequency"; + public const string ReportsDistribution = "grains.reports.distribution"; + public const string ReportsDetails = "grains.reports.details"; + public const string ReportsMotMulti = "grains.reports.motMulti"; + + /// Prefix of the per-table report keys (const so attributes can use it). + public const string TableKeyPrefix = "grains.reports.t."; + + /// Tabular report menu key (grains.reports.t.; keys in web/src/features/grains-reports/meta.tsx). + public static string ReportTable(string tableKey) => TableKeyPrefix + tableKey; +} + +/// +/// Built-in permission table, taken from the business sheet authorities.xlsx (role codes per screen). Used only when +/// the database table GRAINS_SCREEN_PERMISSIONS does not exist yet (see db/grains-screen-permissions.sql); once the +/// table exists the database is the single source of truth. SU is not listed: it is always allowed everything. +/// Screens that are not listed here are hidden from every role except SU (allow-list). +/// +public static class PermissionDefaults +{ + public static readonly IReadOnlyDictionary RolesByResource = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [PermissionKeys.PermitsList] = ["GTO", "GGO", "GOO", "GPO"], // ارسالية عطاء التموين + [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.PermitsTruckStatus] = ["GTO", "GOO"], // استعلام عن حالة التوزيع لسيارة + [PermissionKeys.PermitsActivation] = ["GTO"], // شاشة تفعيل الطلبية + [PermissionKeys.PermitsManualEntry] = ["GTO"], // شاشة الادخال اليدوي + [PermissionKeys.PermitsAbsence] = ["GTO"], // إيقاف\تفعيل الاستنكاف + [PermissionKeys.OrdersWeights] = ["GTO"], // تثبيت أوزان التحميل + [PermissionKeys.ReportTable("weighbridge-events")] = ["GTO", "GOO"], // تقارير حركات قبان التحميل والتفريغ + [PermissionKeys.ReportTable("waybridge-summary")] = ["GTO", "GOO"], + [PermissionKeys.ReportTable("waybridge-details")] = ["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"], // تحديد وجهة ارسالية تموين + }; +} diff --git a/src/NTP.Application/Access/PermissionService.cs b/src/NTP.Application/Access/PermissionService.cs new file mode 100644 index 0000000..0e75e0b --- /dev/null +++ b/src/NTP.Application/Access/PermissionService.cs @@ -0,0 +1,69 @@ +using System.Collections.Concurrent; +using NTP.Application.Abstractions; + +namespace NTP.Application.Access; + +/// What the front end needs to show or hide modules, screens and actions for the caller's role. +/// Caller's role code. +/// True for SU: everything is allowed, is then empty. +/// Allowed resource keys (see ), e.g. grains.orders.list. +public sealed record PermissionsDto(string RoleCode, bool All, IReadOnlyList Allowed); + +public interface IPermissionRepository +{ + /// + /// Resource keys allowed for the role from GRAINS_SCREEN_PERMISSIONS, or null when that table does not + /// exist yet (the caller then falls back to ). + /// + Task?> GetAllowedAsync(string roleCode, CancellationToken ct = default); +} + +public interface IPermissionService +{ + /// Permissions of the current caller. + Task GetForCurrentUserAsync(CancellationToken ct = default); + + /// True if the current caller may use the resource (SU: always). + Task IsAllowedAsync(string resourceKey, CancellationToken ct = default); +} + +/// Role -> allowed resource keys. SU is always allowed everything; any other role is allow-listed. +public sealed class PermissionService(IPermissionRepository repository, ICurrentUser user) : IPermissionService +{ + private const string SuperUser = "SU"; + private static readonly TimeSpan CacheTtl = TimeSpan.FromSeconds(60); + private static readonly ConcurrentDictionary Keys)> Cache = new(StringComparer.OrdinalIgnoreCase); + + public async Task GetForCurrentUserAsync(CancellationToken ct = default) + { + var role = user.RoleCode ?? string.Empty; + if (IsSuper(role)) return new PermissionsDto(role, true, []); + var keys = await KeysAsync(role, ct); + return new PermissionsDto(role, false, keys.OrderBy(k => k, StringComparer.Ordinal).ToList()); + } + + public async Task IsAllowedAsync(string resourceKey, CancellationToken ct = default) + { + var role = user.RoleCode ?? string.Empty; + if (IsSuper(role)) return true; + if (!user.IsAuthenticated) return false; + return (await KeysAsync(role, ct)).Contains(resourceKey); + } + + private static bool IsSuper(string role) => string.Equals(role, SuperUser, StringComparison.OrdinalIgnoreCase); + + private async Task> KeysAsync(string role, CancellationToken ct) + { + if (Cache.TryGetValue(role, out var hit) && hit.ExpiresUtc > DateTime.UtcNow) return hit.Keys; + + var fromDb = await repository.GetAllowedAsync(role, ct); + var keys = new HashSet(fromDb ?? DefaultsFor(role), StringComparer.OrdinalIgnoreCase); + Cache[role] = (DateTime.UtcNow + CacheTtl, keys); + return keys; + } + + private static IEnumerable DefaultsFor(string role) => + PermissionDefaults.RolesByResource + .Where(kv => kv.Value.Contains(role, StringComparer.OrdinalIgnoreCase)) + .Select(kv => kv.Key); +} diff --git a/src/NTP.Application/Auth/AuthContracts.cs b/src/NTP.Application/Auth/AuthContracts.cs new file mode 100644 index 0000000..6c13397 --- /dev/null +++ b/src/NTP.Application/Auth/AuthContracts.cs @@ -0,0 +1,46 @@ +namespace NTP.Application.Auth; + +/// UserName is the legacy "DOMAIN.login" form (e.g. "ASEZA.50034" or "GN.company1"). +public sealed record LoginRequest(string UserName, string Password); + +public sealed record ChangePasswordRequest(string OldPassword, string NewPassword, string? ConfirmNewPassword = null); + +/// Lang is "AR" or "EN". +public sealed record SetLanguageRequest(string Lang); + +public sealed record ClientInfo(string? IpAddress, string? UserAgent); + +/// Everything the legacy assignUserVariables put in the session that the new system needs. +public sealed record AuthenticatedUser( + long Id, + string UserId, + string Name, + string RoleCode, + string RoleName, + string Domain, + long? LocationId, + string LocationName, + long? StkId, + long? CompId, + long? CompanyId, + string CompanyName, + string CompanyCode, + string EmpNo, + string Lang, + bool IsStaff); + +public sealed record CurrentUserDto( + long Id, string UserId, string Name, string RoleCode, string RoleName, string Domain, + long? LocationId, string LocationName, long? StkId, long? CompId, long? CompanyId, + string CompanyName, string CompanyCode, string EmpNo, string Lang, bool IsStaff) +{ + public static CurrentUserDto From(AuthenticatedUser u) => new( + u.Id, u.UserId, u.Name, u.RoleCode, u.RoleName, u.Domain, u.LocationId, u.LocationName, + u.StkId, u.CompId, u.CompanyId, u.CompanyName, u.CompanyCode, u.EmpNo, u.Lang, u.IsStaff); +} + +public sealed record LoginResponse(string AccessToken, string TokenType, DateTime ExpiresAtUtc, CurrentUserDto User, bool MustChangePassword); + +public sealed record TokenResponse(string AccessToken, string TokenType, DateTime ExpiresAtUtc, CurrentUserDto User); + +public sealed record MessageResponse(string Code, string Message); diff --git a/src/NTP.Application/Auth/AuthService.cs b/src/NTP.Application/Auth/AuthService.cs new file mode 100644 index 0000000..fc931f6 --- /dev/null +++ b/src/NTP.Application/Auth/AuthService.cs @@ -0,0 +1,190 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; + +namespace NTP.Application.Auth; + +public interface IAuthService +{ + Task LoginAsync(LoginRequest request, ClientInfo client, CancellationToken ct); + Task SetLanguageAsync(SetLanguageRequest request, CancellationToken ct); + Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken ct); + Task SignOutAsync(ClientInfo client, CancellationToken ct); + + /// Application.cfc: user still active with the same role code. + Task IsUserStillActiveAsync(string login, string roleCode, CancellationToken ct); +} + +/// Port of NTP_LIVE components/signon.cfc (checkLogin, assignUserVariables, changePass, signOut). +public sealed class AuthService( + IAuthRepository repository, + ITokenIssuer tokenIssuer, + ICurrentUser currentUser, + IValidator loginValidator, + IValidator changePasswordValidator, + IValidator languageValidator) : IAuthService +{ + // Legacy messages (kept verbatim). + public const string InvalidLoginMessage = "معلومات الدخول خاطئة ... حاول مرة أخرى"; + private const string NoActiveBoothMessage = "لا يمكنك الدخول, يرجى مراجعة رئيس الشفت"; + private const string OldPasswordWrongMessage = "الرجاء التأكد من كلمة السر القديمة"; + private const string PasswordChangedMessage = "تم تغيير كلمة السر بنجاح"; + + // GateEventsFactory.CheckAuthorization roles that need an active booth (UTT row). + private static readonly string[] BoothRoles = ["GINOP", "GOTOP", "THOP", "GOP", "YOTOP", "GOPTS"]; + // checkLogin: roles whose login IP is compared with LOCATIONS_IPS. + private static readonly string[] IpCheckedRoles = ["GOP", "OPOFF", "GOPTS", "ONO", "YO"]; + + private const int LogSignIn = 1; + private const int LogSignOut = 2; + private const long StaffCompanyId = 15; + + public async Task LoginAsync(LoginRequest request, ClientInfo client, CancellationToken ct) + { + await loginValidator.ValidateAndThrowAsync(request, ct); + + var parts = request.UserName.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (parts.Length != 2) + throw Invalid(); + + var domain = parts[0]; + var login = parts[1].ToLowerInvariant(); + + var candidates = PasswordHasher.Candidates(domain, login, request.Password); + var found = await repository.FindActiveUserByPasswordAsync(login, domain, candidates, + requireActiveCompany: PasswordHasher.IsAseza(domain), ct) ?? throw Invalid(); + + var roleCode = found.RoleCode ?? string.Empty; + + if (BoothRoles.Contains(roleCode, StringComparer.OrdinalIgnoreCase) && + !await repository.HasActiveBoothAsync(login, ct)) + throw new AuthenticationFailedException("NO_ACTIVE_BOOTH", NoActiveBoothMessage); + + // ---- assignUserVariables ---- + var profile = await repository.GetProfileAsync(login, domain, ct); + if (profile is null || string.IsNullOrEmpty(profile.RoleCode)) + throw Invalid(); + + var hierarchy = await repository.GetHierarchyAsync(profile.Id, ct); + + LocationRow? location = null; + if (profile.LocationId is { } locId) + { + // Legacy: for YDADM/YOCC/GOP at location 5 the lookup is restricted to domain ASEZA. + var restrict = locId == 5 && + new[] { "YDADM", "YOCC", "GOP" }.Contains(profile.RoleCode, StringComparer.OrdinalIgnoreCase); + location = await repository.GetLocationAsync(locId, restrict ? "ASEZA" : null, ct); + } + + var roleName = await repository.GetRoleNameAsync(profile.RoleCode, ct); + if (roleName is null) + throw new AuthenticationFailedException("NO_PRIVILEGES", $"{login} - لا توجد لديك صلاحيات"); + + var user = new AuthenticatedUser( + Id: profile.Id, + UserId: login.ToUpperInvariant(), + Name: profile.Name ?? string.Empty, + RoleCode: profile.RoleCode, + RoleName: roleName, + Domain: profile.DomainName ?? domain, + LocationId: profile.LocationId, + LocationName: location?.Name ?? string.Empty, + StkId: hierarchy?.StakeholderId, + CompId: hierarchy?.CompanyId, + CompanyId: profile.CompanyId, + CompanyName: profile.CompanyName ?? string.Empty, + CompanyCode: profile.CompanyCode ?? string.Empty, + EmpNo: profile.EmpNo ?? string.Empty, + Lang: "AR", + IsStaff: profile.CompanyId == StaffCompanyId); + + // 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)); + + await TryAsync(() => LogInvalidAccessAsync(user, profile, client, ct)); + + var (token, expires) = tokenIssuer.Issue(user); + return new LoginResponse(token, "Bearer", expires, CurrentUserDto.From(user), IsTruthy(profile.ResetPassword)); + } + + public async Task SetLanguageAsync(SetLanguageRequest request, CancellationToken ct) + { + await languageValidator.ValidateAndThrowAsync(request, ct); + var user = FromCurrent() with { Lang = request.Lang.ToUpperInvariant() }; + var (token, expires) = tokenIssuer.Issue(user); + return new TokenResponse(token, "Bearer", expires, CurrentUserDto.From(user)); + } + + public async Task ChangePasswordAsync(ChangePasswordRequest request, CancellationToken ct) + { + await changePasswordValidator.ValidateAndThrowAsync(request, ct); + + var login = currentUser.UserId; + var domain = currentUser.Domain; + + var old = await repository.FindActiveUserByPasswordAsync(login, domain, + PasswordHasher.Candidates(domain, login, request.OldPassword), requireActiveCompany: false, ct); + if (old is null) + throw new BusinessException("OLD_PASSWORD_WRONG", OldPasswordWrongMessage); + + // Gap: for ASEZA legacy writes EncryptPwd.doEncryption(new); we write the SHA-1 form, which login also accepts. + await repository.UpdatePasswordAsync(login, domain, PasswordHasher.Sha1Hex(login, request.NewPassword), login, ct); + return new MessageResponse("PASSWORD_CHANGED", PasswordChangedMessage); + } + + public Task SignOutAsync(ClientInfo client, CancellationToken ct) => + TryAsync(() => repository.InsertLogAsync( + new AuditLogEntry(currentUser.UserId, client.IpAddress, currentUser.RoleCode, LogSignOut, currentUser.Name, client.UserAgent), ct)); + + public Task IsUserStillActiveAsync(string login, string roleCode, CancellationToken ct) => + repository.IsActiveWithRoleAsync(login, roleCode, ct); + + // ---- helpers ---- + + private async Task LogInvalidAccessAsync(AuthenticatedUser user, UserProfileRow profile, ClientInfo client, CancellationToken ct) + { + var ip = client.IpAddress ?? string.Empty; + var locationId = user.LocationId?.ToString(); + + if (IpCheckedRoles.Contains(user.RoleCode, StringComparer.OrdinalIgnoreCase)) + { + if (locationId is null) return; + var allowed = await repository.GetLocationIpsAsync(locationId, ct); + if (allowed.Count > 0 && !string.IsNullOrEmpty(allowed[0]) && + !allowed.Contains(ip, StringComparer.OrdinalIgnoreCase)) + { + var ipLocation = await repository.GetLocationForIpAsync(ip, ct); + // reason 2: login from another NAFITH location, 1: from outside. + await repository.InsertInvalidAccessLogAsync(new InvalidAccessEntry( + profile.Id, user.LocationId, user.RoleCode, string.Join(',', allowed), ip, + ipLocation, client.UserAgent, string.IsNullOrEmpty(ipLocation) ? 1 : 2), ct); + } + } + else if (string.Equals(user.RoleCode, "DISP", StringComparison.OrdinalIgnoreCase)) + { + // Legacy: a dispatcher logging in from inside a NAFITH location is logged with reason 3. + var ipLocation = await repository.GetLocationForIpAsync(ip, ct); + if (!string.IsNullOrEmpty(ipLocation)) + await repository.InsertInvalidAccessLogAsync(new InvalidAccessEntry( + profile.Id, user.LocationId, "DISP", ip, ip, ipLocation, client.UserAgent, 3), ct); + } + } + + private AuthenticatedUser FromCurrent() => new( + currentUser.Id, currentUser.UserId, currentUser.Name, currentUser.RoleCode, currentUser.RoleName, + currentUser.Domain, currentUser.LocationId, currentUser.LocationName, currentUser.StkId, currentUser.CompId, + currentUser.CompanyId, currentUser.CompanyName, currentUser.CompanyCode, currentUser.EmpNo, + currentUser.Lang, currentUser.IsStaff); + + private static AuthenticationFailedException Invalid() => new("INVALID_CREDENTIALS", InvalidLoginMessage); + + private static bool IsTruthy(string? v) => + v is not null && (v == "1" || v.Equals("Y", StringComparison.OrdinalIgnoreCase) || v.Equals("true", StringComparison.OrdinalIgnoreCase)); + + private static async Task TryAsync(Func action) + { + try { await action(); } + catch { /* legacy swallows audit-log failures; they must never block sign-in/out */ } + } +} diff --git a/src/NTP.Application/Auth/AuthValidators.cs b/src/NTP.Application/Auth/AuthValidators.cs new file mode 100644 index 0000000..96b6349 --- /dev/null +++ b/src/NTP.Application/Auth/AuthValidators.cs @@ -0,0 +1,34 @@ +using FluentValidation; + +namespace NTP.Application.Auth; + +public sealed class LoginRequestValidator : AbstractValidator +{ + public LoginRequestValidator() + { + RuleFor(x => x.UserName).NotEmpty().MaximumLength(100); + RuleFor(x => x.Password).NotEmpty().MaximumLength(200); + } +} + +public sealed class ChangePasswordRequestValidator : AbstractValidator +{ + public ChangePasswordRequestValidator() + { + 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("كلمة السر الجديدة غير متطابقة"); + } +} + +public sealed class SetLanguageRequestValidator : AbstractValidator +{ + public SetLanguageRequestValidator() + { + RuleFor(x => x.Lang).NotEmpty() + .Must(l => l is not null && (l.Equals("AR", StringComparison.OrdinalIgnoreCase) || l.Equals("EN", StringComparison.OrdinalIgnoreCase))) + .WithMessage("Lang must be AR or EN"); + } +} diff --git a/src/NTP.Application/Auth/IAuthRepository.cs b/src/NTP.Application/Auth/IAuthRepository.cs new file mode 100644 index 0000000..b804226 --- /dev/null +++ b/src/NTP.Application/Auth/IAuthRepository.cs @@ -0,0 +1,71 @@ +namespace NTP.Application.Auth; + +public sealed class UserLoginRow +{ + public long Id { get; set; } + public string? RoleCode { get; set; } + public string? EmpNo { get; set; } + public long? LocationId { get; set; } +} + +/// Legacy info.getConactInfo (ntpusers joined to companies). +public sealed class UserProfileRow +{ + public long Id { get; set; } + public string? DomainName { get; set; } + public string? Name { get; set; } + public string? RoleCode { get; set; } + public string? EmpNo { get; set; } + public long? LocationId { get; set; } + public long? CompanyId { get; set; } + public string? ResetPassword { get; set; } + public string? CompanyName { get; set; } + public string? CompanyCode { get; set; } +} + +public sealed class UserHierarchyRow +{ + public long? CompanyId { get; set; } + public long? GroupId { get; set; } + public long? StakeholderId { get; set; } +} + +public sealed class LocationRow +{ + public string? Type { get; set; } + public string? Name { get; set; } +} + +public sealed record AuditLogEntry(string? DoneBy, string? Ip, string? DoneByRole, int LogType, string? DoneByName, string? Browser); + +public sealed record InvalidAccessEntry( + long UserDbId, long? LocationId, string RoleCode, string ValidIps, string RemoteIp, + string? RemoteIpLocationId, string? UserAgent, int ReasonId); + +public interface IAuthRepository +{ + /// Credential check. mirrors the ASEZA branch (join COMPANIES, status = 1). + Task FindActiveUserByPasswordAsync(string login, string domain, IReadOnlyList passwordCandidates, + bool requireActiveCompany, CancellationToken ct = default); + + /// GateEventsFactory.CheckAuthorization: active UTT (booth) row for the login. + Task HasActiveBoothAsync(string login, CancellationToken ct = default); + + Task GetProfileAsync(string login, string domain, CancellationToken ct = default); + Task GetRoleNameAsync(string roleCode, CancellationToken ct = default); + Task GetHierarchyAsync(long userDbId, CancellationToken ct = default); + Task GetLocationAsync(long locationId, string? domain, CancellationToken ct = default); + + /// Application.cfc onRequestStart: still active, same role. + Task IsActiveWithRoleAsync(string login, string roleCode, CancellationToken ct = default); + + Task UpdatePasswordAsync(string login, string domain, string newPassword, string updatedBy, CancellationToken ct = default); + + Task> GetLocationIpsAsync(string locationId, CancellationToken ct = default); + /// LOCATIONS_IPS.LOCATION_ID that owns this IP, or null. + Task GetLocationForIpAsync(string ip, CancellationToken ct = default); + Task InsertInvalidAccessLogAsync(InvalidAccessEntry entry, CancellationToken ct = default); + + /// logs.addLog: LOGS row (1 = sign in, 2 = sign out, 35 = SSO). + Task InsertLogAsync(AuditLogEntry entry, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Auth/PasswordHasher.cs b/src/NTP.Application/Auth/PasswordHasher.cs new file mode 100644 index 0000000..3b97bcf --- /dev/null +++ b/src/NTP.Application/Auth/PasswordHasher.cs @@ -0,0 +1,36 @@ +using System.Security.Cryptography; +using System.Text; + +namespace NTP.Application.Auth; + +/// +/// Port of the legacy password scheme (signon.cfc): +/// non-ASEZA: hash(ucase(login) & password, 'SHA-1') -> 40 char UPPERCASE hex (ColdFusion hash() default). +/// ASEZA : accepts BOTH application.encryptPwd.doEncryption(password) AND the SHA-1 above. +/// doEncryption is the Java class pwd.EncryptPwd (not in the repo). Its comment says "SH1 with Base64"; +/// is a best-effort GUESS (Base64 of raw SHA-1 of the UTF-8 password) and is UNVERIFIED. +/// The SHA-1 hex path is exact. New passwords are always written with the exact SHA-1 hex form. +/// +public static class PasswordHasher +{ + public const string AsezaDomain = "ASEZA"; + + public static string Sha1Hex(string login, string password) + { + var bytes = SHA1.HashData(Encoding.UTF8.GetBytes(login.ToUpperInvariant() + password)); + return Convert.ToHexString(bytes); // uppercase, like CF hash() + } + + /// UNVERIFIED guess of EncryptPwd.doEncryption (see class remarks). + public static string Sha1Base64(string password) => + Convert.ToBase64String(SHA1.HashData(Encoding.UTF8.GetBytes(password))); + + public static bool IsAseza(string domain) => + string.Equals(domain, AsezaDomain, StringComparison.OrdinalIgnoreCase); + + /// Stored-password values that count as a match for this login (legacy "password in (...)"). + public static IReadOnlyList Candidates(string domain, string login, string password) => + IsAseza(domain) + ? [Sha1Base64(password), Sha1Hex(login, password)] + : [Sha1Hex(login, password)]; +} diff --git a/src/NTP.Application/Common/ConventionRegistration.cs b/src/NTP.Application/Common/ConventionRegistration.cs new file mode 100644 index 0000000..8117fc1 --- /dev/null +++ b/src/NTP.Application/Common/ConventionRegistration.cs @@ -0,0 +1,27 @@ +using System.Reflection; +using Microsoft.Extensions.DependencyInjection; + +namespace NTP.Application.Common; + +public static class ConventionRegistration +{ + /// + /// Registers every concrete, non-generic class whose name ends with "Service" or "Repository" against + /// the interface "I{ClassName}" (scoped). Internal classes are included. Classes without a matching + /// interface are ignored. Used by both AddApplication and AddInfrastructure. + /// + public static IServiceCollection AddConventionalServices(this IServiceCollection services, Assembly assembly) + { + foreach (var type in assembly.GetTypes()) + { + if (!type.IsClass || type.IsAbstract || type.IsGenericTypeDefinition || type.IsNested) continue; + if (!type.Name.EndsWith("Service", StringComparison.Ordinal) && + !type.Name.EndsWith("Repository", StringComparison.Ordinal)) continue; + + var contract = type.GetInterfaces().FirstOrDefault(i => i.Name == "I" + type.Name); + if (contract is not null) + services.AddScoped(contract, type); + } + return services; + } +} diff --git a/src/NTP.Application/Common/Exceptions.cs b/src/NTP.Application/Common/Exceptions.cs new file mode 100644 index 0000000..ba2e7b8 --- /dev/null +++ b/src/NTP.Application/Common/Exceptions.cs @@ -0,0 +1,24 @@ +namespace NTP.Application.Common; + +public sealed class NotFoundException(string entity, object key) + : Exception($"{entity} '{key}' was not found."); + +/// Raised when an UPDATE/DELETE affects 0 rows because ROW_VERSION changed. +public sealed class ConcurrencyException(string entity, object key) + : Exception($"{entity} '{key}' was modified by another user. Reload and retry."); + +/// +/// A business-rule violation ported from legacy code (HTTP 422). message is the user-facing text +/// (keep the legacy Arabic wording); code is a stable machine-readable code returned to the client +/// as the ProblemDetails extension "code". +/// +public class BusinessException(string code, string message) : Exception(message) +{ + public string Code { get; } = code; +} + +/// Credentials / account state rejected (HTTP 401). Same shape as . +public sealed class AuthenticationFailedException(string code, string message) : BusinessException(code, message); + +/// Authenticated but the role/rules do not allow the action (HTTP 403). +public sealed class ForbiddenException(string code, string message) : BusinessException(code, message); diff --git a/src/NTP.Application/Common/Paging.cs b/src/NTP.Application/Common/Paging.cs new file mode 100644 index 0000000..631444f --- /dev/null +++ b/src/NTP.Application/Common/Paging.cs @@ -0,0 +1,25 @@ +namespace NTP.Application.Common; + +public sealed record PageRequest(int Page = 1, int PageSize = 20) +{ + public const int MaxPageSize = 200; + + public int SafePage => Page < 1 ? 1 : Page; + public int SafePageSize => PageSize switch + { + < 1 => 20, + > MaxPageSize => MaxPageSize, + _ => PageSize + }; + + /// Exclusive lower ROWNUM bound for the Oracle 11g paging pattern. + public int MinRow => (SafePage - 1) * SafePageSize; + + /// Inclusive upper ROWNUM bound for the Oracle 11g paging pattern. + public int MaxRow => SafePage * SafePageSize; +} + +public sealed record PagedResult(IReadOnlyList Items, int Page, int PageSize, long TotalCount) +{ + public int TotalPages => PageSize == 0 ? 0 : (int)Math.Ceiling(TotalCount / (double)PageSize); +} diff --git a/src/NTP.Application/DependencyInjection.cs b/src/NTP.Application/DependencyInjection.cs new file mode 100644 index 0000000..5ef395d --- /dev/null +++ b/src/NTP.Application/DependencyInjection.cs @@ -0,0 +1,20 @@ +using FluentValidation; +using Microsoft.Extensions.DependencyInjection; +using NTP.Application.Common; + +namespace NTP.Application; + +public static class DependencyInjection +{ + /// + /// Convention based: *Service classes are registered against I*Service (scoped) and all + /// FluentValidation validators are discovered. Do NOT add per-slice lines here. + /// + public static IServiceCollection AddApplication(this IServiceCollection services) + { + var assembly = typeof(DependencyInjection).Assembly; + services.AddValidatorsFromAssembly(assembly, includeInternalTypes: true); + services.AddConventionalServices(assembly); + return services; + } +} diff --git a/src/NTP.Application/Grains/Orders/BillingService.cs b/src/NTP.Application/Grains/Orders/BillingService.cs new file mode 100644 index 0000000..4223d12 --- /dev/null +++ b/src/NTP.Application/Grains/Orders/BillingService.cs @@ -0,0 +1,108 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Orders; + +namespace NTP.Application.Grains.Orders; + +public interface IBillingService +{ + Task GetPermitAsync(long pn, long? scac, CancellationToken ct); + Task AddAsync(AddBillingRequest request, CancellationToken ct); + Task> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct); +} + +/// Port of Invoice.cfc getBillingInfo / addBillingInfo / getBillingGrid (BillingScreen.cfm, BillingGrid.cfm). +public sealed class BillingService( + IBillingRepository repository, + IUnitOfWork unitOfWork, + IValidator validator) : IBillingService +{ + private static string? Date(DateTime? d) => d?.ToString("yyyy-MM-dd"); + + public async Task GetPermitAsync(long pn, long? scac, CancellationToken ct) + { + 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); + 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, + BillingPrices.Get(info.Destination), BillingPrices.Get(info.CargoType)); + } + + public async Task AddAsync(AddBillingRequest request, CancellationToken ct) + { + await validator.ValidateAndThrowAsync(request, ct); + + // 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(); + + if (!BillingCalculator.IsDischargeAfterLoad(request.LoadDate, request.DischargeDate)) throw OrdersErrors.DischargeBeforeLoad(); + + 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(); + + // 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 => + { + 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(); + + 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, 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), token); + + return new OrdersResult(OrdersErrors.Success, id); + }, ct); + } + + /// Legacy returned an empty grid when no filter was supplied. + public async Task> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct) + { + if (!query.HasFilter) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + + var r = await repository.SearchAsync(query, page, ct); + var items = r.Items.Select(x => new BillingDto( + x.Id, x.CargoType, x.Scac, x.Pn, x.Tn, Date(x.LoadDate), x.Destination, Date(x.DischargeDate), + x.Lnw, x.Dnw, x.Price, x.FinePrice)).ToList(); + return new PagedResult(items, r.Page, r.PageSize, r.TotalCount); + } +} + +public interface IInvoiceService +{ + Task> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct); +} + +/// Port of Invoice.cfc getInvoiceGrid (InvoiceGrid.cfm). +public sealed class InvoiceService(IInvoiceRepository repository) : IInvoiceService +{ + public async Task> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct) + { + // Legacy returned an empty grid when no invoice number was given. + if (!invoiceNumber.HasValue) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + + var r = await repository.SearchAsync(invoiceNumber, page, ct); + var items = r.Items.Select(x => new InvoiceDto(x.Id, x.InvoiceNumber, x.StatusCode, x.Cnt, x.CompanyName, x.Scac, x.InvoiceDate)).ToList(); + return new PagedResult(items, r.Page, r.PageSize, r.TotalCount); + } +} diff --git a/src/NTP.Application/Grains/Orders/OrderReportService.cs b/src/NTP.Application/Grains/Orders/OrderReportService.cs new file mode 100644 index 0000000..0bc64ba --- /dev/null +++ b/src/NTP.Application/Grains/Orders/OrderReportService.cs @@ -0,0 +1,162 @@ +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Orders; + +namespace NTP.Application.Grains.Orders; + +public interface IOrderReportService +{ + Task GetTenderOrderReportAsync(DateTime orderDate, CancellationToken ct); + Task ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct); + + Task GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct); + Task ExportFinancialBillingAsync(long scac, long invoiceNumber, string format, CancellationToken ct); + Task> GetInvoiceNumbersAsync(long scac, CancellationToken ct); +} + +/// +/// Grains reports: tenderOrderReport_xls.cfm and FinancialBilling.cfm / FinancialRpts.cfm as JSON grids plus CSV/XLSX +/// exports (the legacy PDF variant FinancialBilling_pdf.cfm is not ported). +/// +public sealed class OrderReportService(IOrderReportRepository repository, ICurrentUser user) : IOrderReportService +{ + private bool Ar => !string.Equals(user.Lang, "EN", StringComparison.OrdinalIgnoreCase); + private string L(string ar, string en) => Ar ? ar : en; + + private static string Date(object? v) => v switch + { + null => string.Empty, + DateTime d => d.ToString("dd/MM/yyyy"), + _ => v.ToString() ?? string.Empty + }; + + // ------------------------------------------------------------------ tender order report + public async Task GetTenderOrderReportAsync(DateTime orderDate, CancellationToken ct) + { + // Access is decided by the permission grains.orders.reportOrders on the controller (the legacy hard-coded role block was removed). + var day = orderDate.Date; + var byType = await repository.GetTenderTypeTotalsAsync(day, ct); + var byDest = await repository.GetTenderDestinationTotalsAsync(day, ct); + + var typeTotal = byType.Sum(x => x.Quantity); + var typeRows = byType.Select(x => new TenderTypeSummaryDto( + TenderOrderRules.NormalizeType(x.Type), x.Quantity, ReportMath.Percent2(x.Quantity, typeTotal))).ToList(); + + // PIVOT(sum(quant) FOR type IN ('COMP' AS company, 'AHALE' AS ahale)): other types are not part of this table. + var destRows = byDest + .Where(x => x.Type is TenderOrderType.Company or TenderOrderType.Individuals) + .GroupBy(x => x.Destination ?? string.Empty) + .OrderBy(g => g.Key, StringComparer.Ordinal) + .Select(g => + { + var ahale = g.Where(x => x.Type == TenderOrderType.Individuals).Sum(x => x.Quantity); + var comp = g.Where(x => x.Type == TenderOrderType.Company).Sum(x => x.Quantity); + var all = ahale + comp; + return new TenderDestinationSummaryDto( + g.Key, ahale, ReportMath.Percent1(ahale, all), comp, ReportMath.Percent1(comp, all), all); + }).ToList(); + + return new TenderOrderReportDto( + day.ToString("yyyy-MM-dd"), typeRows, typeTotal, destRows, + destRows.Sum(x => x.Individuals), destRows.Sum(x => x.Companies)); + } + + public async Task ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct) + { + var r = await GetTenderOrderReportAsync(orderDate, ct); + string TypeLabel(string? t) => t switch + { + TenderOrderType.Individuals => L("افراد", "Individuals"), + TenderOrderType.Company => L("شركات", "Companies"), + _ => string.Empty + }; + + var title = new[] { L("شركة نافذ للخدمات اللوجستية", "Nafith Logistics Services"), L("نسب التوزيع في طلبيات السائب", "Distribution ratios of bulk orders"), $"{L("تاريخ الطلبية", "Order date")}: {r.OrderDate}" }; + var t1 = new ExportTable(title, + [L("افراد \\ شركات", "Individuals / Companies"), L("العدد", "Count"), L("النسبة", "Ratio")], + r.ByType.Select(x => (IReadOnlyList)new object?[] { TypeLabel(x.Type), x.Quantity, x.Percent }).ToList(), + [L("المجموع", "Total"), r.TypeTotal, "100%"]); + + var t2 = new ExportTable([], + [L("الوجهة", "Destination"), L("عدد الافراد", "Individuals"), L("نسبة الافراد", "Individuals %"), + L("عدد الشركات", "Companies"), L("نسبة الشركات", "Companies %"), L("المجموع", "Total")], + r.ByDestination.Select(x => (IReadOnlyList)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 + private static FinancialBillingDto Map(FinancialBillingRow x) => new( + x.Id, x.CargoType, x.CompanyName, x.Pn, x.Tn, Date(x.LoadDate), x.Name, Date(x.DischargeDate), + x.Lnw, x.Dnw, x.Dnw - x.Lnw, x.Price, x.FinePrice, x.SerialNo, x.Origin, x.LoseFine, x.DemurrageFine, + x.OtherFine, x.FinalCost, x.InvoiceNumber, x.Scac); + + private static FinancialBillingTotals Totals(IEnumerable rows) + { + decimal lnw = 0, dnw = 0, lose = 0, dem = 0, other = 0, final = 0; + foreach (var x in rows) + { + lnw += x.Lnw; dnw += x.Dnw; lose += x.LoseFine; dem += x.DemurrageFine; other += x.OtherFine; final += x.FinalCost; + } + return new FinancialBillingTotals(lnw, dnw, lose, dem, other, final); + } + + public async Task GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct) + { + var paged = await repository.GetFinancialBillingPageAsync(scac, invoiceNumber, page, ct); + // Totals cover the whole invoice (legacy totalled every row), not just the current page. + var all = await repository.GetFinancialBillingAsync(scac, invoiceNumber, ct); + return new FinancialBillingPage(paged.Items.Select(Map).ToList(), paged.Page, paged.PageSize, paged.TotalCount, Totals(all)); + } + + public async Task ExportFinancialBillingAsync(long scac, long invoiceNumber, string format, CancellationToken ct) + { + var rows = await repository.GetFinancialBillingAsync(scac, invoiceNumber, ct); + var first = rows.FirstOrDefault(); + var totals = Totals(rows); + + var title = new List + { + L("شركة نافذ للخدمات اللوجستية", "Nafith Logistics Services"), + L("قائمة بنماذج المعدة لصرف أجور النقل حسب رقم المطالبة", "Transport wages forms by invoice number"), + $"{L("إسم الشركة", "Company")}: {first?.CompanyName}", + $"{L("رقم المطالبة", "Invoice number")}: {invoiceNumber}", + $"{L("رقم العطاء", "Tender number")}: {GrainsOrderConstants.BillingTenderNumber}", + $"{L("التاريخ", "Date")}: {Date(first?.LoadDate)}", + }; + var headers = new[] + { + L("التسلسل", "#"), L("رقم الارسالية", "Permit no."), L("رقم المستند", "Document no."), L("تاريخ التحميل", "Load date"), + L("من", "From"), L("الى", "To"), L("نوع المادة", "Cargo"), L("رقم السيارة", "Truck"), L("الوزن المرسل", "Sent weight"), + L("تاريخ التفريغ", "Discharge date"), L("الوزن المستلم", "Received weight"), L("الفرق", "Difference"), L("السعر", "Price"), + L("سعر التغريم", "Fine price"), L("غرامة النقص", "Shortage fine"), L("غرامة التاخير", "Demurrage fine"), + L("غرامات آخرى", "Other fines"), L("القيمة النهائية", "Final value"), + }; + var origin = L("عقبة", "Aqaba"); + var data = rows.Select((x, i) => (IReadOnlyList)new object?[] + { + i + 1, x.Pn, x.SerialNo, Date(x.LoadDate), origin, x.Name, x.CargoType, x.Tn, x.Lnw, Date(x.DischargeDate), x.Dnw, + x.Dnw - x.Lnw, x.Price, x.FinePrice, x.LoseFine, x.DemurrageFine, x.OtherFine, x.FinalCost + }).ToList(); + IReadOnlyList? totalRow = rows.Count == 0 ? null : new object?[] + { + L("المجموع", "Total"), null, null, null, null, null, null, null, totals.Lnw, null, totals.Dnw, null, null, null, + totals.LoseFine, totals.DemurrageFine, totals.OtherFine, totals.FinalCost + }; + return Build([new ExportTable(title, headers, data, totalRow)], format, $"FinancialReport_{scac}_{invoiceNumber}"); + } + + public Task> GetInvoiceNumbersAsync(long scac, CancellationToken ct) => + repository.GetInvoiceNumbersAsync(scac, ct); + + // ------------------------------------------------------------------ helpers + private ExportFile Build(IReadOnlyList tables, string format, string baseName) + { + var safe = new string(baseName.Where(c => char.IsLetterOrDigit(c) || c is '_' or '-').ToArray()); + return string.Equals(format, "xlsx", StringComparison.OrdinalIgnoreCase) + ? new ExportFile(TabularExport.ToXlsx(tables, Ar), TabularExport.XlsxContentType, safe + ".xlsx") + : new ExportFile(TabularExport.ToCsv(tables), TabularExport.CsvContentType, safe + ".csv"); + } +} diff --git a/src/NTP.Application/Grains/Orders/OrdersContracts.cs b/src/NTP.Application/Grains/Orders/OrdersContracts.cs new file mode 100644 index 0000000..4dd6108 --- /dev/null +++ b/src/NTP.Application/Grains/Orders/OrdersContracts.cs @@ -0,0 +1,254 @@ +namespace NTP.Application.Grains.Orders; + +/// Envelope for write operations: message is the legacy Arabic success text (toasted by the client). +public sealed record OrdersResult(string Message, long? Id = null); + +public sealed record LookupOptionDto(long Id, string? Name); + +/// NTP_TENDERS_COMPANIES (ACTIVE) row: Label = "scac-company name" (legacy getCompanies.companycode). +public sealed record CompanyOptionDto(long Scac, string? Label); + +// ---------------------------------------------------------------- tender orders +public sealed record TenderOrderQuery(DateTime? OrderDate); + +/// Raw row of the legacy getTenderOrders query. +public sealed class TenderOrderRow +{ + public long Id { get; set; } + public DateTime OrderDate { get; set; } + public int? MobileShift { get; set; } + public int Quantity { get; set; } + public string? Ct { get; set; } + public string? StatusCode { get; set; } + public string? CargoType { get; set; } + public string? Location { get; set; } + public string? Destination { get; set; } + public string? Type { get; set; } + public int? MobileShow { get; set; } + public int UsedQuota { get; set; } +} + +// Type: COMP, AHALE or null (= everyone). +// Ct: PCKD, BULK or BULK_GALLAB. +// MobileShow: MOBILE_SHOW flag; null when the column is empty (legacy then showed no toggle). +// CanDelete: Legacy only showed the delete icon when the order date is after today. +public sealed record TenderOrderDto( + long Id, + string OrderDate, + int? MobileShift, + int Quantity, + int UsedQuota, + string? CargoType, + string? Location, + string? Destination, + string? Type, + string? Ct, + bool IsTipper, + bool? MobileShow, + bool CanDelete); + +// 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 Quantity, + bool IsTipper, + string? Type); + +public sealed record MobilePublishRequest(bool Show); + +// ---------------------------------------------------------------- quotas +public sealed class QuotaRow +{ + public long DestinationId { get; set; } + public string? Name { get; set; } + public int? Quota { get; set; } + public int? DoneQuota { get; set; } + public string? CreatedBy { get; set; } + public DateTime? CreationDate { get; set; } +} + +public sealed record QuotaDto( + long DestinationId, string? Name, string QuotaDate, int? Quota, int DoneQuota, string? CreatedBy, DateTime? CreationDate); + +public sealed record ActiveQuota(long Id, int Quota, int DoneQuota); + +public sealed record SetQuotaRequest(long DestinationId, DateTime QuotaDate, int Quota); + +// ---------------------------------------------------------------- billing +/// Result of the legacy getBillingInfo query (events-based weights for a CLOSEd permit). +public sealed class PermitBillingInfo +{ + public long Pn { get; set; } + public long Scac { get; set; } + public string? CompanyName { get; set; } + public long? CargoType { get; set; } + public string? Tn { get; set; } + public long? Origin { get; set; } + public DateTime? LoadDate { get; set; } + public decimal Ltw { get; set; } + public decimal Lgw { get; set; } + public long? Destination { get; set; } + public DateTime? DischargeDate { get; set; } + public decimal Dtw { get; set; } + public decimal Dgw { get; set; } + public long? LastInvoice { get; set; } +} + +/// Billing screen prefill (page JS getAllInformation + price table). +public sealed record BillingPermitDto( + long Pn, long Scac, string? CompanyName, long? CargoType, string? Tn, long? Destination, + string? LoadDate, string? DischargeDate, decimal Lnw, decimal? Dnw, long? LastInvoice, + decimal? Price, decimal? FinePrice); + +public sealed record AddBillingRequest( + long Pn, + long Scac, + long InvoiceNumber, + string SerialNo, + DateTime LoadDate, + DateTime DischargeDate, + long Destination, + long CargoType, + string Tn); + +public sealed record WageRate(decimal Wage); +public sealed record FineRate(decimal Allowance, decimal Fine); + +public sealed record BillingQuery(string? Tn, long? Pn, long? Scac) +{ + public bool HasFilter => !string.IsNullOrWhiteSpace(Tn) || Pn.HasValue || Scac.HasValue; +} + +public sealed class BillingRow +{ + public long Id { get; set; } + public string? CargoType { get; set; } + public string? Scac { get; set; } + public long Pn { get; set; } + public string? Tn { get; set; } + public DateTime? LoadDate { get; set; } + public string? Destination { get; set; } + public DateTime? DischargeDate { get; set; } + public decimal? Lnw { get; set; } + public decimal? Dnw { get; set; } + public decimal? Price { get; set; } + public decimal? FinePrice { get; set; } +} + +public sealed record BillingDto( + long Id, string? CargoType, string? Scac, long Pn, string? Tn, string? LoadDate, string? Destination, + string? DischargeDate, decimal? Lnw, decimal? Dnw, decimal? Price, decimal? FinePrice); + +// ---------------------------------------------------------------- invoices +public sealed class InvoiceRow +{ + public long Id { get; set; } + public long InvoiceNumber { get; set; } + public string? StatusCode { get; set; } + public int Cnt { get; set; } + public string? CompanyName { get; set; } + public long Scac { get; set; } + public string? InvoiceDate { get; set; } +} + +public sealed record InvoiceDto( + long Id, long InvoiceNumber, string? StatusCode, int Count, string? CompanyName, long Scac, string? InvoiceDate); + +// ---------------------------------------------------------------- weights (addGrainsWeights.cfm) +public sealed class PermitWeightsRow +{ + public long Id { get; set; } + public string? ShipmentStatusCode { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Drvr { get; set; } +} + +public sealed class SavedWeightsRow +{ + public long Id { get; set; } + public string? EmptyWeight { get; set; } + public string? GrossWeight { get; set; } + public string? DocumentNumber { get; set; } +} + +public sealed record PermitWeightsDto( + long Pn, string? Tn, string? Trn, string? Driver, string? EmptyWeight, string? GrossWeight, string? DocumentNumber); + +public sealed record SaveWeightsRequest(long Pn, string EmptyWeight, string GrossWeight, string DocumentNumber); + +// ---------------------------------------------------------------- company destinations (compdest.cfm) +public sealed record CompanyDestinationsDto(long Scac, IReadOnlyList LocationIds); +public sealed record SaveCompanyDestinationsRequest(IReadOnlyList LocationIds); + +// ---------------------------------------------------------------- reports +public sealed class TenderTypeTotalRow +{ + public string? Type { get; set; } + public decimal Quantity { get; set; } +} + +public sealed class TenderDestinationTotalRow +{ + public string? Destination { get; set; } + public string? Type { get; set; } + public decimal Quantity { get; set; } +} + +public sealed record TenderTypeSummaryDto(string? Type, decimal Quantity, decimal Percent); + +public sealed record TenderDestinationSummaryDto( + string? Destination, decimal Individuals, decimal IndividualsPercent, decimal Companies, decimal CompaniesPercent, decimal Total); + +public sealed record TenderOrderReportDto( + string OrderDate, + IReadOnlyList ByType, + decimal TypeTotal, + IReadOnlyList ByDestination, + decimal TotalIndividuals, + decimal TotalCompanies); + +/// Row of view/table billing1 (GNB datasource in legacy) used by FinancialBilling*.cfm. +public sealed class FinancialBillingRow +{ + public long Id { get; set; } + public string? CargoType { get; set; } + public string? CompanyName { get; set; } + public long Pn { get; set; } + public string? Tn { get; set; } + public object? LoadDate { get; set; } + public string? Name { get; set; } + public object? DischargeDate { get; set; } + public decimal Lnw { get; set; } + public decimal Dnw { get; set; } + public decimal Price { get; set; } + public decimal FinePrice { get; set; } + public string? SerialNo { get; set; } + public string? Origin { get; set; } + public decimal FinalCost { get; set; } + public decimal LoseFine { get; set; } + public long InvoiceNumber { get; set; } + public long Scac { get; set; } + public decimal OtherFine { get; set; } + public decimal DemurrageFine { get; set; } +} + +public sealed record FinancialBillingDto( + long Id, string? CargoType, string? CompanyName, long Pn, string? Tn, string? LoadDate, string? Destination, + string? DischargeDate, decimal Lnw, decimal Dnw, decimal Difference, decimal Price, decimal FinePrice, + string? SerialNo, string? Origin, decimal LoseFine, decimal DemurrageFine, decimal OtherFine, decimal FinalCost, + long InvoiceNumber, long Scac); + +public sealed record FinancialBillingTotals( + decimal Lnw, decimal Dnw, decimal LoseFine, decimal DemurrageFine, decimal OtherFine, decimal FinalCost); + +/// Same JSON shape as PagedResult plus totals over the whole invoice. +public sealed record FinancialBillingPage( + IReadOnlyList Items, int Page, int PageSize, long TotalCount, FinancialBillingTotals Totals); + +public sealed record ExportFile(byte[] Content, string ContentType, string FileName); diff --git a/src/NTP.Application/Grains/Orders/OrdersRepositories.cs b/src/NTP.Application/Grains/Orders/OrdersRepositories.cs new file mode 100644 index 0000000..c38772f --- /dev/null +++ b/src/NTP.Application/Grains/Orders/OrdersRepositories.cs @@ -0,0 +1,99 @@ +using NTP.Application.Common; +using NTP.Domain.Grains.Orders; + +namespace NTP.Application.Grains.Orders; + +public interface ITenderOrderRepository +{ + /// Legacy getTenderOrders query (non-deleted orders, active EN/EX GN locations), newest first. + Task> SearchAsync(DateTime? orderDate, PageRequest page, CancellationToken ct = default); + + Task InsertAsync(NewTenderOrder order, CancellationToken ct = default); + + /// Status and date of an order (null when the id does not exist). + Task<(string? StatusCode, DateTime OrderDate)?> GetHeaderAsync(long id, CancellationToken ct = default); + + /// Permits with SCRN = order id in shipment status REQST/PLND (orders already distributed). + Task HasDistributedPermitsAsync(long id, CancellationToken ct = default); + + Task MarkDeletedAsync(long id, CancellationToken ct = default); + + Task SetMobileShowAsync(long id, bool show, string userId, CancellationToken ct = default); +} + +public interface IOrderLookupRepository +{ + /// CARGOTYPE where DOMAIN='GN'. + Task> GetCargoTypesAsync(CancellationToken ct = default); + + /// LOCATIONS where DOMAIN='GN', STATUS=1 and TYPE = EN (loading) or EX (destination). + Task> GetLocationsAsync(string type, CancellationToken ct = default); + + /// Invoice.cfc getLocations: GN exit locations with AREA IS NULL and STATUS=1. + Task> GetBillingDestinationsAsync(CancellationToken ct = default); + + /// register.getDistination: GN exit locations of GN_TYPE 'PCKD', ordered by SORTORDER. + Task> GetPackedDestinationsAsync(CancellationToken ct = default); + + /// NTP_TENDERS_COMPANIES with STATUSCODE='ACTIVE' (grains.cfc getCompanies). + Task> GetCompaniesAsync(CancellationToken ct = default); +} + +public interface IQuotaRepository +{ + /// All GN DESTINATIONS left-joined with their active DESTINATION_QUOTA row of the date. + Task> GetListAsync(DateTime date, PageRequest page, CancellationToken ct = default); + + Task DestinationExistsAsync(long destinationId, CancellationToken ct = default); + + Task GetActiveAsync(long destinationId, DateTime date, CancellationToken ct = default); + + Task DeactivateAsync(long destinationId, DateTime date, string userId, CancellationToken ct = default); + + Task InsertAsync(long destinationId, DateTime date, int quota, string userId, int doneQuota, CancellationToken ct = default); +} + +public interface IBillingRepository +{ + Task GetPermitBillingInfoAsync(long pn, CancellationToken ct = default); + Task GetWageRateAsync(long destination, DateTime loadDate, CancellationToken ct = default); + Task GetFineRateAsync(DateTime loadDate, CancellationToken ct = default); + Task InsertAsync(NewGrainsBilling billing, CancellationToken ct = default); + Task> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct = default); +} + +public interface IInvoiceRepository +{ + Task> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct = default); +} + +public interface IGrainsWeightRepository +{ + /// permits by PN in status CLOSE/RESD/ACTRL, company 327, domain GN (permitAutoComplete). + Task GetPermitAsync(long pn, CancellationToken ct = default); + + Task GetWeightsAsync(long permitId, CancellationToken ct = default); + Task UpdateWeightsAsync(long weightsId, string empty, string gross, string document, string userId, CancellationToken ct = default); + Task InsertWeightsAsync(long permitId, string empty, string gross, string document, string userId, CancellationToken ct = default); +} + +public interface ICompanyDestinationRepository +{ + Task> GetLocationIdsAsync(long scac, CancellationToken ct = default); + + /// Deletes the company's rows whose LOCATIONID is in and inserts the new ones. + Task ReplaceAsync(long scac, IReadOnlyCollection scopeLocationIds, IReadOnlyCollection newLocationIds, + string userId, CancellationToken ct = default); +} + +public interface IOrderReportRepository +{ + Task> GetTenderTypeTotalsAsync(DateTime orderDate, CancellationToken ct = default); + Task> GetTenderDestinationTotalsAsync(DateTime orderDate, CancellationToken ct = default); + + Task> GetFinancialBillingPageAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct = default); + Task> GetFinancialBillingAsync(long scac, long invoiceNumber, CancellationToken ct = default); + + /// Distinct invoice numbers already present in GRAINS_BILLING for a company (newest first). + Task> GetInvoiceNumbersAsync(long scac, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Grains/Orders/OrdersRules.cs b/src/NTP.Application/Grains/Orders/OrdersRules.cs new file mode 100644 index 0000000..9f7744f --- /dev/null +++ b/src/NTP.Application/Grains/Orders/OrdersRules.cs @@ -0,0 +1,166 @@ +using NTP.Application.Common; +using NTP.Domain.Grains.Orders; + +namespace NTP.Application.Grains.Orders; + +/// Stable error codes + legacy Arabic messages for the orders slice. +public static class OrdersErrors +{ + public static BusinessException OrderHasDistribution() => + new("ORDER_HAS_DISTRIBUTION", "لا تستطيع حذف هذه الطلبية، تم التوزيع عليها"); + + public static BusinessException QuantityRange() => + new("ORDER_QUANTITY_RANGE", "عدد السيارات يجب ان يكون بين 1 - 200"); + + public static BusinessException OrderDateRange() => + new("ORDER_DATE_RANGE", "تاريخ الطلبية يجب أن يكون من اليوم وحتى 4 أيام قادمة"); + + public static BusinessException InvalidLookup(string what) => + new("ORDER_INVALID_LOOKUP", $"قيمة غير صحيحة: {what}"); + + public static BusinessException QuotaBelowUsed(int done) => + new("QUOTA_BELOW_USED", $"الحصة اليومية لا يمكن أن تكون أقل من الحصة المستخدمة ({done})"); + + public static BusinessException InvalidPn() => + new("BILLING_PN_INVALID", "رقم الارسالية غير صحيح"); + + public static BusinessException PnNotOfCompany() => + new("BILLING_PN_NOT_OF_COMPANY", "هذه الارسالية غير تابعة لهذه الشركة"); + + public static BusinessException DischargeBeforeLoad() => + new("BILLING_DISCHARGE_BEFORE_LOAD", "يجب أن يكون تاريخ التفريغ بعد تاريخ التحميل"); + + public static BusinessException ReceivedWeightMissing() => + new("BILLING_DNW_MISSING", "الوزن المستلم مطلوب"); + + public static BusinessException SentWeightRange() => + new("BILLING_LNW_RANGE", "يجب أن يكون الوزن بين 0 - 50000"); + + public static BusinessException PriceNotDefined() => + new("BILLING_PRICE_NOT_DEFINED", "لا يوجد سعر محدد لهذه الوجهة أو نوع المادة"); + + public static BusinessException RatesNotFound() => + new("BILLING_RATES_NOT_FOUND", "لا توجد أجور أو غرامات محددة لهذه الوجهة في تاريخ التحميل"); + + public static BusinessException WeightLength() => + new("WEIGHTS_LENGTH", "يجب ان يكون الوزن من 5 خانات"); + + public static BusinessException WeightsPermitNotFound() => + new("WEIGHTS_PERMIT_NOT_FOUND", "الرجاء التأكد من رقم الارسالية"); + + public static BusinessException CompanyNotFound() => + new("COMPANY_NOT_FOUND", "الشركة غير موجودة"); + + public static BusinessException InvalidDestination() => + new("COMPANY_DESTINATION_INVALID", "وجهة غير صحيحة"); + + public const string Success = "تمت العملية بنجاح"; +} + +/// Pure business rules of tender orders (ported from createNewTenderOrder.cfm / tenderOrder.cfc). +public static class TenderOrderRules +{ + /// Legacy createTenderOrder: packed cargo => PCKD; tipper destinations or the tipper tick => BULK_GALLAB; else BULK. + public static string ResolveCargoClass(long cargoTypeId, long destinationId, bool isTipper) + { + if (cargoTypeId == GrainsOrderConstants.PackedCargoTypeId) return TenderCargoClass.Packed; + if (GrainsOrderConstants.TipperDestinationIds.Contains(destinationId)) return TenderCargoClass.BulkTipper; + return isTipper ? TenderCargoClass.BulkTipper : TenderCargoClass.Bulk; + } + + /// Order date dropdown offered today .. today + 4 days. + public static bool IsAllowedOrderDate(DateTime orderDate, DateTime today) + { + var d = orderDate.Date; + return d >= today.Date && d <= today.Date.AddDays(GrainsOrderConstants.MaxDaysAhead); + } + + public static bool IsQuantityValid(int quantity) => + quantity is >= GrainsOrderConstants.MinTrucksPerOrder and <= GrainsOrderConstants.MaxTrucksPerOrder; + + /// The type (individuals/companies) is mandatory except for packed cargo. + public static bool IsTypeRequired(long cargoTypeId) => cargoTypeId != GrainsOrderConstants.PackedCargoTypeId; + + public static bool IsValidType(string? type) => + type is TenderOrderType.Company or TenderOrderType.Individuals; + + /// Legacy showed the delete icon only when DateCompare(orderDate, now()) > 0, i.e. strictly after today. + public static bool CanDelete(DateTime orderDate, DateTime today) => orderDate.Date > today.Date; + + /// Empty type means "everyone" in the legacy grid. + public static string? NormalizeType(string? type) => + string.IsNullOrWhiteSpace(type) ? null : type.Trim().ToUpperInvariant(); +} + +public static class QuotaRules +{ + /// Legacy editQuota silently ignored a new quota lower than the used quota. + public static bool CanSetQuota(int newQuota, int doneQuota) => newQuota - doneQuota >= 0; +} + +/// Static price table of legacy Invoice.cfc getPrices (destination ids 215/220/225, cargo ids 38-41). +public static class BillingPrices +{ + private static readonly IReadOnlyDictionary Table = new Dictionary + { + [215] = 14.67m, + [220] = 14.902m, + [225] = 17.219m, + [38] = 243.076m, + [39] = 235.006m, + [40] = 243.076m, + [41] = 235.006m, + }; + + public static decimal? Get(long? id) => id.HasValue && Table.TryGetValue(id.Value, out var v) ? v : null; +} + +/// Port of the wage/fine maths of legacy Invoice.cfc addBillingInfo. +public static class BillingCalculator +{ + private static decimal Round3(decimal v) => Math.Round(v, 3, MidpointRounding.AwayFromZero); + + /// Net weight: gross minus tare. + public static decimal NetWeight(decimal gross, decimal tare) => gross - tare; + + /// round(wage * LNW / 1000, 3). + public static decimal Wage(decimal wagePerTon, decimal lnw) => Round3(wagePerTon * lnw / 1000m); + + /// + /// CASE WHEN (LNW - DNW) > allowance * LNW THEN round(((LNW - DNW) - allowance * LNW) * fine / 1000, 3) ELSE 0 END. + /// + public static decimal ShortageFine(decimal lnw, decimal dnw, decimal allowance, decimal fineRate) + { + var loss = lnw - dnw; + var allowed = allowance * lnw; + return loss > allowed ? Round3((loss - allowed) * fineRate / 1000m) : 0m; + } + + /// Page JS checkDate: discharge date must not be before load date. + public static bool IsDischargeAfterLoad(DateTime load, DateTime discharge) => discharge.Date >= load.Date; + + /// Page JS checkNumber: sent weight between 0 and 50000. + public static bool IsSentWeightInRange(decimal lnw) => lnw >= 0 && lnw <= 50000; +} + +public static class GrainsWeightRules +{ + /// The page masks weights as 99999 and legacy rejected anything shorter than 5 characters. + public static bool IsValidWeight(string? w) => + w is { Length: 5 } && w.All(char.IsAsciiDigit); + + /// Legacy EVENTS.REMARKS text of ADD_WEIGHTS. + public static string EventRemarks(string gross, string empty) => + $"الوزن القائم: {gross} الوزن الفارغ: {empty}"; +} + +public static class ReportMath +{ + /// Percentage with 1 decimal (legacy NumberFormat '__._'). + public static decimal Percent1(decimal part, decimal whole) => + whole == 0 ? 0m : Math.Round(part * 100m / whole, 1, MidpointRounding.AwayFromZero); + + /// Percentage with 2 decimals (legacy SQL round(x*100, 2)). + public static decimal Percent2(decimal part, decimal whole) => + whole == 0 ? 0m : Math.Round(part * 100m / whole, 2, MidpointRounding.AwayFromZero); +} diff --git a/src/NTP.Application/Grains/Orders/OrdersValidators.cs b/src/NTP.Application/Grains/Orders/OrdersValidators.cs new file mode 100644 index 0000000..c1c191b --- /dev/null +++ b/src/NTP.Application/Grains/Orders/OrdersValidators.cs @@ -0,0 +1,70 @@ +using FluentValidation; +using NTP.Domain.Grains.Orders; + +namespace NTP.Application.Grains.Orders; + +public sealed class CreateTenderOrderValidator : AbstractValidator +{ + public CreateTenderOrderValidator() + { + RuleFor(x => x.CargoType).GreaterThan(0).WithMessage("نمط الحمولة مطلوب"); + RuleFor(x => x.Location).GreaterThan(0).WithMessage("موقع التحميل مطلوب"); + RuleFor(x => x.Destination).GreaterThan(0).WithMessage("الوجهه مطلوبة"); + RuleFor(x => x.OrderDate).NotEmpty().WithMessage("تاريخ الطلبية مطلوب"); + RuleFor(x => x.Shift).InclusiveBetween(1, 3).WithMessage("الفترة مطلوبة"); + RuleFor(x => x.Quantity) + .Must(TenderOrderRules.IsQuantityValid).WithMessage("عدد السيارات يجب ان يكون بين 1 - 200"); + RuleFor(x => x.Type) + .NotEmpty().WithMessage("شركات \\ أفراد مطلوب") + .When(x => TenderOrderRules.IsTypeRequired(x.CargoType)); + RuleFor(x => x.Type) + .Must(TenderOrderRules.IsValidType).WithMessage("قيمة شركات \\ أفراد غير صحيحة") + .When(x => !string.IsNullOrWhiteSpace(x.Type)); + } +} + +public sealed class SetQuotaValidator : AbstractValidator +{ + public SetQuotaValidator() + { + RuleFor(x => x.DestinationId).GreaterThan(0); + RuleFor(x => x.QuotaDate).NotEmpty(); + RuleFor(x => x.Quota).GreaterThanOrEqualTo(0).LessThanOrEqualTo(1_000_000); + } +} + +public sealed class AddBillingValidator : AbstractValidator +{ + public AddBillingValidator() + { + RuleFor(x => x.Pn).GreaterThan(0).WithMessage("رقم الارسالية مطلوب"); + RuleFor(x => x.Scac).GreaterThan(0).WithMessage("اسم الشركة مطلوب"); + RuleFor(x => x.InvoiceNumber).GreaterThan(0).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("رقم السيارة مطلوب"); + } +} + +public sealed class SaveWeightsValidator : AbstractValidator +{ + public SaveWeightsValidator() + { + RuleFor(x => x.Pn).GreaterThan(0).WithMessage("رقم الارسالية مطلوب"); + RuleFor(x => x.EmptyWeight).NotEmpty().WithMessage("الوزن الفارغ مطلوب"); + RuleFor(x => x.GrossWeight).NotEmpty().WithMessage("الوزن القائم مطلوب"); + RuleFor(x => x.DocumentNumber).NotEmpty().MaximumLength(12).WithMessage("رقم مستند الشحن مطلوب"); + } +} + +public sealed class SaveCompanyDestinationsValidator : AbstractValidator +{ + public SaveCompanyDestinationsValidator() + { + RuleFor(x => x.LocationIds).NotNull(); + RuleForEach(x => x.LocationIds).GreaterThan(0); + } +} diff --git a/src/NTP.Application/Grains/Orders/QuotaService.cs b/src/NTP.Application/Grains/Orders/QuotaService.cs new file mode 100644 index 0000000..bc357a2 --- /dev/null +++ b/src/NTP.Application/Grains/Orders/QuotaService.cs @@ -0,0 +1,54 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; + +namespace NTP.Application.Grains.Orders; + +public interface IQuotaService +{ + Task> GetListAsync(DateTime date, PageRequest page, CancellationToken ct); + Task SetQuotaAsync(SetQuotaRequest request, CancellationToken ct); +} + +/// Port of grains.cfc getQuotaList / editQuota (quotaGrid.cfm). +public sealed class QuotaService( + IQuotaRepository repository, + IUnitOfWork unitOfWork, + ICurrentUser user, + IValidator validator) : IQuotaService +{ + public async Task> GetListAsync(DateTime date, PageRequest page, CancellationToken ct) + { + var day = date.Date; + var result = await repository.GetListAsync(day, page, ct); + var items = result.Items.Select(r => new QuotaDto( + r.DestinationId, r.Name, day.ToString("yyyy-MM-dd"), r.Quota, r.DoneQuota ?? 0, r.CreatedBy, r.CreationDate)).ToList(); + return new PagedResult(items, result.Page, result.PageSize, result.TotalCount); + } + + /// + /// Deactivates the active quota row of the destination/date and inserts a new active one (history is kept). + /// DONEQUOTA is carried over from the row being replaced (legacy trusted the client's grid row; the server value is used here). + /// + public async Task SetQuotaAsync(SetQuotaRequest request, CancellationToken ct) + { + await validator.ValidateAndThrowAsync(request, ct); + var day = request.QuotaDate.Date; + + return await unitOfWork.ExecuteInTransactionAsync(async token => + { + if (!await repository.DestinationExistsAsync(request.DestinationId, token)) + throw new NotFoundException("Destination", request.DestinationId); + + var active = await repository.GetActiveAsync(request.DestinationId, day, token); + var done = active?.DoneQuota ?? 0; + + // Legacy returned silently when the new quota was lower than the used quota; now the user is told. + if (!QuotaRules.CanSetQuota(request.Quota, done)) throw OrdersErrors.QuotaBelowUsed(done); + + await repository.DeactivateAsync(request.DestinationId, day, user.UserId, token); + await repository.InsertAsync(request.DestinationId, day, request.Quota, user.UserId, done, token); + return new OrdersResult(OrdersErrors.Success, request.DestinationId); + }, ct); + } +} diff --git a/src/NTP.Application/Grains/Orders/TabularExport.cs b/src/NTP.Application/Grains/Orders/TabularExport.cs new file mode 100644 index 0000000..2416e14 --- /dev/null +++ b/src/NTP.Application/Grains/Orders/TabularExport.cs @@ -0,0 +1,172 @@ +using System.Globalization; +using System.IO.Compression; +using System.Security; +using System.Text; + +namespace NTP.Application.Grains.Orders; + +/// A titled block of a report: optional title lines, a header row, data rows and an optional totals row. +public sealed record ExportTable( + IReadOnlyList TitleLines, + IReadOnlyList Headers, + IReadOnlyList> Rows, + IReadOnlyList? TotalsRow = null); + +/// +/// Writes report tables as CSV (UTF-8 with BOM so Excel shows Arabic) or as a real .xlsx workbook +/// (right-to-left sheet, inline strings, no external packages). Replaces the legacy HTML-as-.xls output. +/// +public static class TabularExport +{ + public const string CsvContentType = "text/csv; charset=utf-8"; + public const string XlsxContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + public static string FormatCell(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 + }; + + // ------------------------------------------------------------------ CSV + public static byte[] ToCsv(IReadOnlyList tables) + { + var sb = new StringBuilder(); + for (var i = 0; i < tables.Count; i++) + { + var t = tables[i]; + if (i > 0) sb.Append("\r\n"); + foreach (var line in t.TitleLines) sb.Append(Csv(line)).Append("\r\n"); + sb.Append(string.Join(',', t.Headers.Select(Csv))).Append("\r\n"); + foreach (var row in t.Rows) sb.Append(string.Join(',', row.Select(c => Csv(FormatCell(c))))).Append("\r\n"); + if (t.TotalsRow is not null) sb.Append(string.Join(',', t.TotalsRow.Select(c => Csv(FormatCell(c))))).Append("\r\n"); + } + var preamble = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true).GetPreamble(); + var body = Encoding.UTF8.GetBytes(sb.ToString()); + var result = new byte[preamble.Length + body.Length]; + preamble.CopyTo(result, 0); + body.CopyTo(result, preamble.Length); + return result; + } + + /// RFC 4180 quoting; also neutralises spreadsheet formula injection (leading = + - @). + public static string Csv(string value) + { + if (value.Length > 0 && value[0] is '=' or '+' or '@' || (value.Length > 1 && value[0] == '-' && !char.IsDigit(value[1]) && value[1] != '.')) + value = "'" + value; + return value.IndexOfAny([',', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"") + "\"" : value; + } + + // ------------------------------------------------------------------ XLSX + public static string ColumnName(int zeroBasedIndex) + { + var n = zeroBasedIndex + 1; + var sb = new StringBuilder(); + while (n > 0) + { + var rem = (n - 1) % 26; + sb.Insert(0, (char)('A' + rem)); + n = (n - 1) / 26; + } + return sb.ToString(); + } + + public static byte[] ToXlsx(IReadOnlyList tables, bool rightToLeft) + { + using var ms = new MemoryStream(); + using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) + { + Add(zip, "[Content_Types].xml", + """ + + + """); + Add(zip, "_rels/.rels", + """ + + + """); + Add(zip, "xl/workbook.xml", + """ + + + """); + Add(zip, "xl/_rels/workbook.xml.rels", + """ + + + """); + Add(zip, "xl/styles.xml", + """ + + + """); + Add(zip, "xl/worksheets/sheet1.xml", Sheet(tables, rightToLeft)); + } + return ms.ToArray(); + } + + 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.TrimStart()); + s.Write(bytes, 0, bytes.Length); + } + + private static string Sheet(IReadOnlyList tables, bool rtl) + { + var sb = new StringBuilder(); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + var r = 1; + for (var ti = 0; ti < tables.Count; ti++) + { + var t = tables[ti]; + if (ti > 0) r++; // blank separator row + foreach (var line in t.TitleLines) Row(sb, r++, [line], bold: true); + Row(sb, r++, t.Headers.Cast().ToList(), bold: true); + foreach (var row in t.Rows) Row(sb, r++, row, bold: false); + if (t.TotalsRow is not null) Row(sb, r++, t.TotalsRow, bold: true); + } + sb.Append(""); + return sb.ToString(); + } + + private static void Row(StringBuilder sb, int r, IReadOnlyList cells, bool bold) + { + sb.Append(""); + for (var c = 0; c < cells.Count; c++) + { + var v = cells[c]; + if (v is null) continue; + var refName = ColumnName(c) + r.ToString(CultureInfo.InvariantCulture); + var style = bold ? " s=\"1\"" : ""; + 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("") + .Append(Convert.ToString(v, CultureInfo.InvariantCulture)).Append(""); + } + else + { + sb.Append("") + .Append(Escape(FormatCell(v))).Append(""); + } + } + sb.Append(""); + } + + private static string Escape(string s) + { + // Drop characters that are illegal in XML 1.0, then escape. + var clean = new StringBuilder(s.Length); + foreach (var ch in s) + if (ch == '\t' || ch == '\n' || ch == '\r' || ch >= 0x20 && ch != 0xFFFE && ch != 0xFFFF && !char.IsSurrogate(ch) || char.IsSurrogate(ch)) + clean.Append(ch); + return SecurityElement.Escape(clean.ToString()) ?? string.Empty; + } +} diff --git a/src/NTP.Application/Grains/Orders/TenderOrderService.cs b/src/NTP.Application/Grains/Orders/TenderOrderService.cs new file mode 100644 index 0000000..1de93f4 --- /dev/null +++ b/src/NTP.Application/Grains/Orders/TenderOrderService.cs @@ -0,0 +1,120 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Orders; + +namespace NTP.Application.Grains.Orders; + +public interface ITenderOrderService +{ + Task> SearchAsync(TenderOrderQuery query, PageRequest page, CancellationToken ct); + Task CreateAsync(CreateTenderOrderRequest request, CancellationToken ct); + Task DeleteAsync(long id, CancellationToken ct); +} + +/// Port of tenderOrder.cfc (getTenderOrders, createTenderOrder, deleteTenderOrder). +public sealed class TenderOrderService( + ITenderOrderRepository repository, + IOrderLookupRepository lookups, + IUnitOfWork unitOfWork, + ICurrentUser user, + IValidator createValidator) : ITenderOrderService +{ + public async Task> SearchAsync(TenderOrderQuery query, PageRequest page, CancellationToken ct) + { + var result = await repository.SearchAsync(query.OrderDate?.Date, page, ct); + var today = DateTime.Today; + var items = result.Items.Select(r => new TenderOrderDto( + r.Id, + r.OrderDate.ToString("yyyy-MM-dd"), + r.MobileShift, + r.Quantity, + r.UsedQuota, + r.CargoType, + r.Location, + r.Destination, + TenderOrderRules.NormalizeType(r.Type), + r.Ct, + string.Equals(r.Ct, TenderCargoClass.BulkTipper, StringComparison.OrdinalIgnoreCase), + r.MobileShow is null ? null : r.MobileShow == 1, + TenderOrderRules.CanDelete(r.OrderDate, today))).ToList(); + return new PagedResult(items, result.Page, result.PageSize, result.TotalCount); + } + + public async Task CreateAsync(CreateTenderOrderRequest request, CancellationToken ct) + { + // Who may create orders is decided by the permission grains.orders.create (GRAINS_SCREEN_PERMISSIONS), enforced on the + // controller. The legacy hard-coded block of GOO, OPOFF and ONO (tenderOrderGrid.cfm) was removed on purpose. + await createValidator.ValidateAndThrowAsync(request, ct); + if (!TenderOrderRules.IsAllowedOrderDate(request.OrderDate, DateTime.Today)) throw OrdersErrors.OrderDateRange(); + + // The legacy form only offered these values; make sure the ids are really offered ones. + if (!(await lookups.GetCargoTypesAsync(ct)).Any(x => x.Id == request.CargoType)) throw OrdersErrors.InvalidLookup("نمط الحمولة"); + if (!(await lookups.GetLocationsAsync("EN", ct)).Any(x => x.Id == request.Location)) throw OrdersErrors.InvalidLookup("موقع التحميل"); + if (!(await lookups.GetLocationsAsync("EX", ct)).Any(x => x.Id == request.Destination)) throw OrdersErrors.InvalidLookup("الوجهه"); + + var order = new NewTenderOrder( + request.CargoType, request.Location, request.Destination, request.OrderDate.Date, request.Shift, request.Quantity, + TenderOrderRules.NormalizeType(request.Type), + TenderOrderRules.ResolveCargoClass(request.CargoType, request.Destination, request.IsTipper), + user.UserId); + + var id = await repository.InsertAsync(order, ct); + return new OrdersResult(OrdersErrors.Success, id); + } + + public Task DeleteAsync(long id, CancellationToken ct) => + unitOfWork.ExecuteInTransactionAsync(async token => + { + var header = await repository.GetHeaderAsync(id, token); + if (header is null || header.Value.StatusCode == TenderOrderStatus.Deleted) + throw new NotFoundException("TenderOrder", id); + + if (await repository.HasDistributedPermitsAsync(id, token)) throw OrdersErrors.OrderHasDistribution(); + + await repository.MarkDeletedAsync(id, token); + return new OrdersResult(OrdersErrors.Success, id); + }, ct); +} + +/// +/// "Show on the mobile app" switch (legacy publishMobile). Kept behind its own interface so a real push/notify +/// integration can replace the DB flag later without touching the controller. +/// +public interface IMobilePublishService +{ + Task SetVisibilityAsync(long orderId, bool show, CancellationToken ct); +} + +public sealed class MobilePublishService(ITenderOrderRepository repository, ICurrentUser user) : IMobilePublishService +{ + public async Task SetVisibilityAsync(long orderId, bool show, CancellationToken ct) + { + var header = await repository.GetHeaderAsync(orderId, ct); + if (header is null || header.Value.StatusCode == TenderOrderStatus.Deleted) + throw new NotFoundException("TenderOrder", orderId); + + await repository.SetMobileShowAsync(orderId, show, user.UserId, ct); + return new OrdersResult(OrdersErrors.Success, orderId); + } +} + +public interface IOrderLookupService +{ + Task> CargoTypesAsync(CancellationToken ct); + Task> LoadingLocationsAsync(CancellationToken ct); + Task> DestinationsAsync(CancellationToken ct); + Task> BillingDestinationsAsync(CancellationToken ct); + Task> PackedDestinationsAsync(CancellationToken ct); + Task> CompaniesAsync(CancellationToken ct); +} + +public sealed class OrderLookupService(IOrderLookupRepository repository) : IOrderLookupService +{ + public Task> CargoTypesAsync(CancellationToken ct) => repository.GetCargoTypesAsync(ct); + public Task> LoadingLocationsAsync(CancellationToken ct) => repository.GetLocationsAsync("EN", ct); + public Task> DestinationsAsync(CancellationToken ct) => repository.GetLocationsAsync("EX", ct); + public Task> BillingDestinationsAsync(CancellationToken ct) => repository.GetBillingDestinationsAsync(ct); + public Task> PackedDestinationsAsync(CancellationToken ct) => repository.GetPackedDestinationsAsync(ct); + public Task> CompaniesAsync(CancellationToken ct) => repository.GetCompaniesAsync(ct); +} diff --git a/src/NTP.Application/Grains/Orders/WeightsAndDestinationsService.cs b/src/NTP.Application/Grains/Orders/WeightsAndDestinationsService.cs new file mode 100644 index 0000000..f35c37d --- /dev/null +++ b/src/NTP.Application/Grains/Orders/WeightsAndDestinationsService.cs @@ -0,0 +1,91 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Orders; + +namespace NTP.Application.Grains.Orders; + +public interface IGrainsWeightService +{ + Task GetAsync(long pn, CancellationToken ct); + Task SaveAsync(SaveWeightsRequest request, CancellationToken ct); +} + +/// Port of grains.cfc permitAutoComplete / saveGrainsWeights (addGrainsWeights.cfm). +public sealed class GrainsWeightService( + IGrainsWeightRepository repository, + IEventLogger events, + IUnitOfWork unitOfWork, + ICurrentUser user, + IValidator validator) : IGrainsWeightService +{ + public async Task GetAsync(long pn, CancellationToken ct) + { + var permit = await repository.GetPermitAsync(pn, ct) ?? throw OrdersErrors.WeightsPermitNotFound(); + var saved = await repository.GetWeightsAsync(permit.Id, ct); + return new PermitWeightsDto(pn, permit.Tn, permit.Trn, permit.Drvr, saved?.EmptyWeight, saved?.GrossWeight, saved?.DocumentNumber); + } + + public async Task SaveAsync(SaveWeightsRequest request, CancellationToken ct) + { + await validator.ValidateAndThrowAsync(request, ct); + // Legacy only checked the empty weight (a copy/paste bug); the page mask requires 5 digits for both. + if (!GrainsWeightRules.IsValidWeight(request.EmptyWeight) || !GrainsWeightRules.IsValidWeight(request.GrossWeight)) + throw OrdersErrors.WeightLength(); + + return await unitOfWork.ExecuteInTransactionAsync(async token => + { + var permit = await repository.GetPermitAsync(request.Pn, token) ?? throw OrdersErrors.WeightsPermitNotFound(); + var existing = await repository.GetWeightsAsync(permit.Id, token); + + if (existing is not null) + await repository.UpdateWeightsAsync(existing.Id, request.EmptyWeight, request.GrossWeight, request.DocumentNumber, user.UserId, token); + else + await repository.InsertWeightsAsync(permit.Id, request.EmptyWeight, request.GrossWeight, request.DocumentNumber, user.UserId, token); + + await events.AddAsync(new EventEntry( + "PERMITID", permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, user.UserId, "ADD_WEIGHTS", "GN", null, + "NTP", null, + new Dictionary { ["REMARKS"] = GrainsWeightRules.EventRemarks(request.GrossWeight, request.EmptyWeight) }), token); + + return new OrdersResult(OrdersErrors.Success, permit.Id); + }, ct); + } +} + +public interface ICompanyDestinationService +{ + Task GetAsync(long scac, CancellationToken ct); + Task SaveAsync(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct); +} + +/// Port of grains.cfc getCompDest / saveCompDest (compdest.cfm) over GRAINS_COMPANIES_LOCATION. +public sealed class CompanyDestinationService( + ICompanyDestinationRepository repository, + IOrderLookupRepository lookups, + IUnitOfWork unitOfWork, + ICurrentUser user, + IValidator validator) : ICompanyDestinationService +{ + public async Task GetAsync(long scac, CancellationToken ct) => + new(scac, await repository.GetLocationIdsAsync(scac, ct)); + + public async Task SaveAsync(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct) + { + await validator.ValidateAndThrowAsync(request, ct); + + if (!(await lookups.GetCompaniesAsync(ct)).Any(c => c.Scac == scac)) throw OrdersErrors.CompanyNotFound(); + + var packed = (await lookups.GetPackedDestinationsAsync(ct)).Select(x => x.Id).ToHashSet(); + var chosen = request.LocationIds.Distinct().ToList(); + if (chosen.Any(id => !packed.Contains(id))) throw OrdersErrors.InvalidDestination(); + + // Only the destinations the screen can show (packed ones) are replaced; other rows of the company are kept. + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.ReplaceAsync(scac, packed, chosen, user.UserId, token); + return 0; + }, ct); + return new OrdersResult(OrdersErrors.Success, scac); + } +} diff --git a/src/NTP.Application/Grains/Permits/DestinationService.cs b/src/NTP.Application/Grains/Permits/DestinationService.cs new file mode 100644 index 0000000..5c56f7d --- /dev/null +++ b/src/NTP.Application/Grains/Permits/DestinationService.cs @@ -0,0 +1,299 @@ +using System.Globalization; +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Permits; + +namespace NTP.Application.Grains.Permits; + +public interface IDestinationService +{ + Task> GetGrainsLocationsAsync(CancellationToken ct = default); + Task> GetExitLocationsAsync(CancellationToken ct = default); + Task> GetPermitFilterDestinationsAsync(CancellationToken ct = default); + Task> GetCargoTypesAsync(CancellationToken ct = default); + Task GetLocationGroupsAsync(CancellationToken ct = default); + Task> GetCompaniesAsync(CancellationToken ct = default); + Task> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default); + Task SaveCompanyDestinationsAsync(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct = default); + Task AssignByPnAsync(AssignByPnRequest request, CancellationToken ct = default); + + Task> GetOrderDatesAsync(CancellationToken ct = default); + Task> GetAllowedDestinationsAsync(string pn, string orderDate, CancellationToken ct = default); + Task> GetAllowedCargoAsync(long permitId, CancellationToken ct = default); + Task> GetOrdersForPermitAsync(string pn, string orderDate, CancellationToken ct = default); + Task ManualInputAsync(ManualInputRequest request, CancellationToken ct = default); + + /// assignDestination: picks the best open tender order for the truck. Business outcomes are returned, not thrown. + Task AssignDestinationAsync(string tn, long locationId, string userId, CancellationToken ct = default); + Task SearchDestinationAsync(string tn, CancellationToken ct = default); + + Task> GetActivationAsync(CancellationToken ct = default); + Task ActivateOrdersAsync(ActivateOrdersRequest request, CancellationToken ct = default); + Task ActivatePendingCompanyDestinationsAsync(CancellationToken ct = default); +} + +public sealed class DestinationService( + IDestinationRepository repo, + IPermitRepository permits, + IEventLogger events, + IUnitOfWork uow, + ICurrentUser user, + IGrainsPermitsSettingsService settings) : IDestinationService +{ + private GrainsPermitsOptions options => settings.Value; + + // ------------------------------------------------------------------------------------------------ lookups / company destinations + + public Task> GetGrainsLocationsAsync(CancellationToken ct = default) => repo.GetGrainsLocationsAsync(ct); + public Task> GetExitLocationsAsync(CancellationToken ct = default) => repo.GetLocationsByTypeAsync("EX", ct); + public Task> GetPermitFilterDestinationsAsync(CancellationToken ct = default) => repo.GetPermitFilterDestinationsAsync(ct); + public Task> GetCargoTypesAsync(CancellationToken ct = default) => repo.GetCargoTypesAsync(ct); + public Task GetLocationGroupsAsync(CancellationToken ct = default) => repo.GetLocationGroupsAsync(ct); + public Task> GetCompaniesAsync(CancellationToken ct = default) => repo.GetCompaniesAsync(ct); + public Task> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default) => repo.GetCompanyLocationsAsync(scac, ct); + + public async Task 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 AssignByPnAsync(AssignByPnRequest r, CancellationToken ct = default) + { + new AssignByPnValidator().ValidateAndThrow(r); + var permit = await permits.GetByPnAsync(r.Pn, ct) ?? throw new BusinessException("PN_NOT_FOUND", "رقم الارسالية غير موجود"); + var loc = await repo.GetLocationNameAsync(r.DestId, ct); + var ct2 = await repo.GetCargoTypeNameAsync(r.ShipmentMode, ct); + await uow.ExecuteInTransactionAsync(async token => + { + await repo.AssignByPnAsync(permit.Id, r.DestId, r.ShipmentMode, token); + await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.AssignGrainsDest, + $"تم تحديد وجهة بنجاح - الموقع:{loc}- الحمولة: {ct2}", withLocation: false, ct: token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, permit.Id); + } + + // ------------------------------------------------------------------------------------------------ orders for a permit + + public async Task> GetOrderDatesAsync(CancellationToken ct = default) => + (await repo.GetOrderDatesAsync(ct)).Select(d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ToList(); + + public async Task> GetAllowedDestinationsAsync(string pn, string orderDate, CancellationToken ct = default) + { + pn = pn.Trim(); + var date = PermitDates.ParseLegacy(orderDate) ?? throw new ValidationException("تاريخ الطلبية غير صحيح"); + var permit = await permits.GetByPnAsync(pn, ct); + if (permit is not null) + { + var packed = permit.Tt == GrainsCargo.Packed; + if (pn.StartsWith('1')) + { + var allowed = await repo.GetCompanyLocationsAsync(permit.CompanyCode ?? 0, ct); + if (allowed.Count > 0) + return await repo.GetAllowedDestinationsAsync(pn, date, allowed, companyBranch: true, packed, ct); + } + else + { + var allowed = await repo.GetTruckDestinationsAsync(permit.Tn ?? string.Empty, ct); + if (allowed.Count > 0) + { + var rows = await repo.GetAllowedDestinationsAsync(pn, date, allowed, companyBranch: false, packed, ct); + if (rows.Count > 0) return rows; + } + } + } + return [new AllowedDestinationDto { OrderId = 0, Name = "لا توجد طلبيات متاحة", OrderDate = string.Empty }]; + } + + public async Task> GetAllowedCargoAsync(long permitId, CancellationToken ct = default) + { + var permit = await permits.GetAsync(permitId, ct) ?? throw new NotFoundException("Permit", permitId); + return await repo.GetAllowedCargoAsync(permit, options.BadiyaScac, ct); + } + + public async Task> GetOrdersForPermitAsync(string pn, string orderDate, CancellationToken ct = default) + { + if (!pn.All(char.IsDigit) || pn.Length == 0) return []; + var date = PermitDates.ParseLegacy(orderDate) ?? throw new ValidationException("تاريخ الطلبية غير صحيح"); + return await repo.GetOrdersForPermitDateAsync(pn.Trim(), date, ct); + } + + public async Task ManualInputAsync(ManualInputRequest r, CancellationToken ct = default) + { + new ManualInputValidator().ValidateAndThrow(r); + var permit = await permits.GetByPnAsync(r.Pn, ct) ?? throw new BusinessException("PN_NOT_FOUND", "رقم الارسالية غير موجود"); + var order = await repo.GetManualOrderAsync(r.OrderId, ct) ?? throw new NotFoundException("Order", r.OrderId); + + var message = await uow.ExecuteInTransactionAsync(token => + SetDestToPermitAsync(order.Location ?? 0, order.Destination ?? 0, order.CargoType ?? 0, order.Id, user.UserId, permit.Id, + permit.ShipmentStatusCode, r.Ltw, r.Lgw, isManual: true, token), ct); + return PermitOperationResult.Ok(message, permit.Id); + } + + // ------------------------------------------------------------------------------------------------ assignDestination + + public async Task AssignDestinationAsync(string tn, long locationId, string userId, CancellationToken ct = default) + { + tn = tn.Trim(); + var rows = await repo.GetTruckPermitsForAssignmentAsync(tn, ct); + var p = rows.Count > 0 ? rows[0] : null; + if (p is null) return new(false, "حالة السيارة غير صحيحة"); + + var window = Window(); + PermitRow? full = null; + OrderForPermitRow? ownOrder = null; + if (p.Scrn is long scrn) + { + ownOrder = await repo.GetOrderAsync(scrn, ct); + // a permit that already holds today's / tomorrow's order simply takes its destination + if (ownOrder?.OrderDate is { } od && (od.Date == DateTime.Today || od.Date == DateTime.Today.AddDays(1))) + { + var dn = await repo.GetLocationNameAsync(ownOrder.Destination ?? 0, ct); + var cn = await repo.GetCargoTypeNameAsync(ownOrder.CargoType ?? 0, ct); + var okMsg = $"تم توزيع وجهة بنجاح - الموقع:{dn} - الحمولة: {cn}"; + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetPermitDestinationAsync(p.Id, ownOrder.Location ?? 0, ownOrder.Destination ?? 0, ownOrder.CargoType ?? 0, scrn, userId, token); + await events.LogAsAsync(userId, locationId.ToString(CultureInfo.InvariantCulture), p.Id, p.ShipmentStatusCode, p.ShipmentStatusCode, + PermitEventType.AssignDest, okMsg, ct: token); + return true; + }, ct); + return new(true, okMsg); + } + } + + IReadOnlyList companyLocations = p.CompanyCode == options.BadiyaScac + ? await repo.GetTruckDestinationsAsync(tn, ct) + : await repo.GetCompanyLocationsAsync(p.CompanyCode ?? 0, ct); + companyLocations = DestinationRules.FilterCompanyLocations(companyLocations, await repo.GetLastAsrnAsync(tn, ct)); + if (companyLocations.Count == 0) return new(false, "لا توجد وجهات معرفة"); + + long[]? cargoGroup = null; + long? orderLocation = null; + if (ownOrder is not null) + { + cargoGroup = DestinationRules.CargoGroup(ownOrder.CargoType); + orderLocation = ownOrder.Location; + } + + var candidates = await repo.GetTenderOrderCandidatesAsync(tn, companyLocations, cargoGroup, cargoGroup is null ? null : orderLocation, window, ct); + if (candidates.Count == 0) + { + const string msg = "لا توجد أي وجهة مناسبة لطلب الشركة أو القاطرة"; + await events.LogAsAsync(userId, locationId.ToString(CultureInfo.InvariantCulture), p.Id, p.ShipmentStatusCode, p.ShipmentStatusCode, + PermitEventType.AssignDest, msg, ct: ct); + return new(false, msg); + } + + long tenderTotal = 0, trucksTotal = 0; + foreach (var c in candidates) + { + tenderTotal += c.Quantity; + trucksTotal += await repo.CountAssignedTrucksAsync(c.Id, ct); + } + if (trucksTotal >= tenderTotal) + { + const string msg = "لا توجد وجهات متاحة لهذا الشفت، تم توزيع كامل عدد الطلبية"; + await events.LogAsAsync(userId, locationId.ToString(CultureInfo.InvariantCulture), p.Id, p.ShipmentStatusCode, p.ShipmentStatusCode, + PermitEventType.AssignDest, msg, ct: ct); + return new(false, msg); + } + + var best = candidates[0]; + _ = full; + var message = await uow.ExecuteInTransactionAsync(token => + SetDestToPermitAsync(locationId, best.Destenation, best.CargoType, best.Id, userId, p.Id, p.ShipmentStatusCode, null, null, + isManual: false, token), ct); + return new(true, message); + } + + /// setDestToPermit: writes origin/destination/cargo/order on the permit and the ASSIGNDEST (or MANASGNDST) event. + private async Task SetDestToPermitAsync(long locationId, long destinationId, long cargoType, long orderId, string userId, + long permitId, string? status, decimal? ltw, decimal? lgw, bool isManual, CancellationToken ct) + { + var destName = await repo.GetLocationNameAsync(destinationId, ct); + var cargoName = await repo.GetCargoTypeNameAsync(cargoType, ct); + await repo.SetPermitDestinationAsync(permitId, locationId, destinationId, cargoType, orderId, userId, ct); + + var sessionLoc = user.IsAuthenticated ? user.LocationText() : null; + if (ltw.HasValue) + await events.LogAsAsync(userId, sessionLoc, permitId, status, status, PermitEventType.LoadingTare, string.Empty, + ltw.Value.ToString(CultureInfo.InvariantCulture), ct: ct); + + var text = (isManual ? "تم توزيع وجهة يدويا بنجاح - الموقع:" : "تم توزيع وجهة بنجاح - الموقع:") + destName + " - الحمولة: " + cargoName; + await events.LogAsAsync(userId, locationId.ToString(CultureInfo.InvariantCulture), permitId, status, status, + isManual ? PermitEventType.ManualAssignDest : PermitEventType.AssignDest, text, ct: ct); + + if (lgw.HasValue) + await events.LogAsAsync(userId, sessionLoc, permitId, status, status, PermitEventType.LoadingGross, string.Empty, + lgw.Value.ToString(CultureInfo.InvariantCulture), ct: ct); + return "تم توزيع وجهة بنجاح - الموقع:" + destName + " - الحمولة: " + cargoName; + } + + public async Task SearchDestinationAsync(string tn, CancellationToken ct = default) + { + tn = tn.Trim(); + string? message = null; + try + { + if (!await repo.HasAssignDestEventAsync(tn, ct)) + { + var assigned = await AssignDestinationAsync(tn, user.LocationId ?? 0, user.UserId, ct); + message = assigned.Message; + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return new(null, null, "رقم السيارة غير صحيح"); + } + + var (dest, origin) = await repo.GetAssignedDestinationAsync(tn, ct); + if (string.IsNullOrEmpty(dest) || origin is null) + return new(null, null, "رقم السيارة غير صحيح"); + return new(dest, origin, message); + } + + // ------------------------------------------------------------------------------------------------ activation of today's orders + + public Task> GetActivationAsync(CancellationToken ct = default) => + repo.GetActivationRowsAsync(Window(), ct); + + public async Task ActivateOrdersAsync(ActivateOrdersRequest r, CancellationToken ct = default) + { + var current = await repo.GetCurrentWindowOrdersAsync(Window(), ct); + if (current.Count == 0) throw new BusinessException("NO_ORDERS_TODAY", "لا توجد اي طلبية اليوم"); + + var chosen = new HashSet<(long Loc, long Ct)>(); + foreach (var s in r.Selected) + { + var parts = s.Split('-'); + if (parts.Length >= 2 && long.TryParse(parts[0], out var l) && long.TryParse(parts[1], out var c)) chosen.Add((l, c)); + } + + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetOrdersStatusAsync(current.Select(o => o.Id).ToList(), "INACTIVE", user.UserId, token); + var activate = current.Where(o => o.Location is long l && o.CargoType is long c && chosen.Contains((l, c))).Select(o => o.Id).ToList(); + if (activate.Count > 0) await repo.SetOrdersStatusAsync(activate, "ACTIVE", user.UserId, token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk); + } + + public Task ActivatePendingCompanyDestinationsAsync(CancellationToken ct = default) => + repo.ActivatePendingCompanyDestinationsAsync("GrainDestJob", ct); + + private ShiftWindow Window() => new() + { + Shift1First = options.OperationShift1[0], Shift1Last = options.OperationShift1[1], + Shift2First = options.OperationShift2[0], Shift2Last = options.OperationShift2[1] + }; +} diff --git a/src/NTP.Application/Grains/Permits/DistributionService.cs b/src/NTP.Application/Grains/Permits/DistributionService.cs new file mode 100644 index 0000000..e119ddc --- /dev/null +++ b/src/NTP.Application/Grains/Permits/DistributionService.cs @@ -0,0 +1,526 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text; +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Permits; + +namespace NTP.Application.Grains.Permits; + +public interface IDistributionService +{ + Task DistributeAsync(DistributeRequest request, CancellationToken ct = default); + Task ReleaseAsync(ReleasePermitRequest request, CancellationToken ct = default); + Task ProcessOpenPermitAsync(OpenPermitRequest request, CancellationToken ct = default); + Task ProcessOpenPermitWithDestinationAsync(OpenPermitWithDestinationRequest request, CancellationToken ct = default); + Task ProcessCompanyOpenPermitsAsync(CompanyOpenPermitsRequest request, CancellationToken ct = default); + Task DistributeSingleTruckAsync(string tn, CancellationToken ct = default); + + Task> GetSummaryAsync(CancellationToken ct = default); + Task> GetPivotAsync(CancellationToken ct = default); + Task SearchTruckAsync(string tn, CancellationToken ct = default); + Task> GetBlacklistedAsync(string tn, CancellationToken ct = default); + Task CheckTripsAsync(CheckTripsRequest request, CancellationToken ct = default); + Task RevokeAllRequestedAsync(long scrnBelow, CancellationToken ct = default); + + /// jobs/checkForGabanEvents.cfm: permits whose loading window passed without an ASSIGNDEST go back to OPEN. + Task RevertUnloadedPermitsAsync(string actor, CancellationToken ct = default); + + // auto call + Task SendAutoCallFileAsync(AutoCallRequest request, CancellationToken ct = default); + Task TriggerIvrAsync(CancellationToken ct = default); + bool IsValidDialerApiKey(string? key); + Task HandleDialerCallbackAsync(AutoCallResponse response, CancellationToken ct = default); +} + +/// Per-user position in the company queue between two "distribute companies" runs (legacy session.QueueStart). +internal static class DistributionCursor +{ + private static readonly ConcurrentDictionary Positions = new(StringComparer.OrdinalIgnoreCase); + public static long Get(string user) => Positions.GetValueOrDefault(user, 1); + public static void Set(string user, long value) => Positions[user] = value; +} + +public sealed class DistributionService( + IDistributionRepository repo, + IDestinationRepository destinations, + IPermitRepository permits, + IPhoneEventRepository phoneRepo, + IPermitService permitService, + IMobileNotificationGatewayService notifications, + IAutoCallGatewayService autoCall, + IEventLogger events, + IUnitOfWork uow, + ICurrentUser user, + IGrainsPermitsSettingsService settings) : IDistributionService +{ + private GrainsPermitsOptions options => settings.Value; + + // ------------------------------------------------------------------------------------------------ distributePackedBulk + + private sealed record ReleaseOutcome(string ErrorMsg, long? Scac = null, string? CargoLabel = null); + + public async Task DistributeAsync(DistributeRequest r, CancellationToken ct = default) + { + new DistributeValidator().ValidateAndThrow(r); + var cat = DistributionCategory.Parse(r.Category)!; + + var totals = await repo.GetOrderTotalsAsync(cat.DistributionCode, cat.QueueType, cat.IsPacked, ct); + var used = await repo.GetUsedOrdersAsync(cat.DistributionCode, cat.QueueType, cat.IsPacked, ct); + if (totals.AllQuantity <= 0) + return PermitOperationResult.Fail("NO_ORDERS", cat.NoOrdersMessage); + + await repo.PrepareDataAsync(cat.PermitCargoType, options.BadiyaScac, ct); + + decimal available; + if (cat.IsPacked) + { + var comps = totals.TotalComps - (used?.UsedComps ?? 0); + var owners = totals.TotalOwners - (used?.UsedOwners ?? 0); + available = comps + owners; + } + else + { + available = totals.AllQuantity - (used is null ? 0 : used.UsedComps + used.UsedOwners); + } + var queueAvailable = (long)available; + if (available < 0) + return PermitOperationResult.Fail("NO_ORDERS", cat.IsPacked + ? "لا توجد طلبات مشول مسجلة على النظام ، او قد تم توزيع كامل الطلبية" + : "لا توجد طلبات سائب مسجلة على النظام ، او قد تم توزيع كامل الطلبية"); + + var start = DistributionCursor.Get(user.UserId); + var (code, type) = cat.QueueFilter; + var shares = await repo.GetCompanyShareAsync(code, type, cat.IsGallabCompany, start, queueAvailable, ct); + if (shares.Count == 0) + return PermitOperationResult.Fail("NO_ORDERS", cat.NoOrdersMessage); + + var picks = await repo.GetCompanyQueuePermitsAsync(shares, cat.DistributionCode, cat.PermitCargoType, cat.IsGallabCompany, + cat.DistributionCode == GrainsCargo.BulkGallab, options.BadiyaScac, ct); + + var companyCounter = 0; + var ownerCounter = 0; + var ownerNotes = new List>(); + var companyNotes = new Dictionary(); + + await uow.ExecuteInTransactionAsync(async token => + { + foreach (var p in picks) + { + var outcome = await ReleaseCoreAsync(p.Pn ?? string.Empty, p.Scac, cat.DistributionCode, cat.QueueType, token); + if (outcome.ErrorMsg.Length > 0) continue; + + if (outcome.Scac == options.BadiyaScac) ownerCounter++; else companyCounter++; + await repo.IncrementQueueCounterAsync(p.Qid, token); + if (cat.IsGallabCompany) await repo.IncrementCompanyQueueAsync(p.Scac, "BULK", "COMP", token); + await repo.SetTrackingNoAsync(p.Pn ?? string.Empty, p.Qid, token); + + var label = cat.DistributionCode == GrainsCargo.BulkGallab ? outcome.CargoLabel + " قلاب " : outcome.CargoLabel; + if (!string.IsNullOrEmpty(p.Tn)) + { + var d = await repo.GetOwnerDistributionDataAsync(p.Tn, options.BadiyaScac, token); + ownerNotes.Add(new Dictionary + { + ["TN"] = p.Tn, ["PN"] = p.Pn, + ["TT"] = cat.DistributionCode == GrainsCargo.BulkGallab ? d?.Name + " قلاب " : d?.Name, + ["LOCATION"] = d?.Location, ["ORDERDATE"] = d?.OrderDate, ["SHIFT"] = d?.Shift + }); + } + else + { + var key = p.Scac.ToString(CultureInfo.InvariantCulture).PadLeft(3, '0'); + companyNotes[key] = companyNotes.TryGetValue(key, out var n) ? (int)n! + 1 : 1; + companyNotes["TT"] = label; + } + } + return true; + }, ct); + + await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS", new Dictionary { ["NOTIFICATIONARY"] = ownerNotes }, ct); + await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_COMP", companyNotes, ct); + + if (cat.Request is "BULK_COMP" or "BULK_GALLAB_COMP") + DistributionCursor.Set(user.UserId, companyCounter == 0 ? start + queueAvailable : 1); + + return PermitOperationResult.Ok($"تم توزيع {companyCounter} شركات - {ownerCounter} أفراد ، من أصل{queueAvailable}", + data: new Dictionary { ["companies"] = companyCounter, ["owners"] = ownerCounter, ["available"] = queueAvailable }); + } + + // ------------------------------------------------------------------------------------------------ releasePermit + + public async Task ReleaseAsync(ReleasePermitRequest r, CancellationToken ct = default) + { + if (!long.TryParse(r.Scac, out var scac)) throw new ValidationException("رقم الشركة غير صحيح"); + var outcome = await uow.ExecuteInTransactionAsync(token => ReleaseCoreAsync(r.Pn, scac, r.Category, r.QueueType, token), ct); + return outcome.ErrorMsg.Length == 0 + ? PermitOperationResult.Ok(PermitOperationResult.DefaultOk) + : PermitOperationResult.Fail(outcome.ErrorMsg == "noDist" ? "NO_DESTINATION" : "INVALID_PERMIT", outcome.ErrorMsg); + } + + private async Task ReleaseCoreAsync(string pn, long scac, string category, string queueType, CancellationToken ct) + { + var permit = await repo.GetOpenPermitWithFirmsAsync(pn, scac, ct); + if (permit is null) return new("INVALID PERMITID"); + + var locations = await repo.GetAllowedLocationsForReleaseAsync(permit, scac, options.BadiyaScac, ct); + NextOrderPick? order = locations.Count == 0 + ? null + : await repo.GetNextOrderAsync(locations, category, category == GrainsCargo.Packed ? null : queueType, ct); + + if (order is null) + { + if (scac == options.BadiyaScac) + await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Open, PermitEventType.Override, + $"لم يتم توزيع أي وجهة للسيارة رقم {permit.Tn} لعدم وجود مجهة متناسبة مع طلب الشركة", ct: ct); + return new("noDist"); + } + + await repo.SetRequestedWithOrderAsync(permit.Id, order.Id, ct); + var d = await destinations.GetOrderDetailsAsync(order.Id, ct); + await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, + $"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: ct); + + if (scac == options.BadiyaScac) + { + await repo.UpdateLastPermitAsync(order.Id, options.BadiyaScac, ct); + await repo.DeletePendingDistributionAsync(permit.Id, permit.Tn ?? string.Empty, order.Id, ct); + var orderDate = PermitDates.ParseLegacy(d?.OrderDate) ?? DateTime.Today; + await repo.InsertDistributionLogAsync(permit.Id, order.Id, orderDate, permit.Tn ?? string.Empty, "AUTO_DEST", d?.CargoTypeCode, ct); + } + return new(string.Empty, scac, d?.CargoType); + } + + // ------------------------------------------------------------------------------------------------ procssOpenPermit* + + public async Task ProcessOpenPermitAsync(OpenPermitRequest r, CancellationToken ct = default) + { + var permit = await repo.GetFirstOpenPermitByTnAsync(r.Tn.Trim(), r.CargoType, ct) + ?? throw new BusinessException("TRUCK_NOT_QUEUED", "السيارة ليست على الدور"); + + await uow.ExecuteInTransactionAsync(async token => + { + if (r.SaveScrn) + { + var orders = await repo.GetNextOrdersForTruckAsync(r.Tn.Trim(), token); + if (orders.Count == 0) + throw new BusinessException("NO_MATCHING_DESTINATION", "لا توجد وجهات مناسبة متوافقة مع طلب الشركة"); + + long orderId = 0; + foreach (var o in orders) + { + if (permit.CompanyCode == options.BadiyaScac + || await repo.IsLocationAllowedForCompanyAsync(permit.CompanyCode ?? 0, o.Destenation, token)) + { + orderId = o.Id; + break; + } + } + if (orderId == 0) throw new BusinessException("NO_ORDERS_AVAILABLE", "لا توجد طلبيات متاحة"); + + await repo.SetRequestedWithOrderAsync(permit.Id, orderId, token); + var d = await destinations.GetOrderDetailsAsync(orderId, token); + await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, + $"تحميل: {d?.Location} / {d?.CargoType}", ct: token); + } + else + { + await repo.SetRequestedAsync(permit.Id, token); + await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token); + } + return true; + }, ct); + return PermitOperationResult.Ok("تم تحويل حالة السيارة إلى توزيع طلبية", permit.Id); + } + + public async Task ProcessOpenPermitWithDestinationAsync(OpenPermitWithDestinationRequest r, CancellationToken ct = default) + { + new OpenPermitWithDestinationValidator().ValidateAndThrow(r); + var permit = await permits.GetByPnAsync(r.Pn, ct) ?? throw new BusinessException("PN_INVALID", "رقم الارسالية غير صحيح"); + if (permit.ShipmentStatusCode != PermitStatus.Open) + throw new BusinessException("PERMIT_BAD_STATE", "حالة الارسالية غير صحيحة"); + + var order = await repo.GetOrderForManualAsync(r.Locations, ct) ?? throw new NotFoundException("Order", r.Locations); + var d = await destinations.GetOrderDetailsAsync(r.Locations, ct); + var orderDate = PermitDates.ParseLegacy(r.OrderDate) ?? DateTime.Today; + + await uow.ExecuteInTransactionAsync(async token => + { + var scac = permit.CompanyCode ?? 0; + var code = order.Ct == GrainsCargo.BulkGallab ? "BULK" : order.Ct ?? string.Empty; + var type = string.IsNullOrEmpty(order.Type) ? null : order.Type.Replace("AHALE", "AHALI"); + var queueId = await repo.PickQueueIdAsync(scac, code, type, token) + ?? throw new BusinessException("NO_QUEUE", "لا يوجد دور مسجل للشركة"); + await repo.IncrementQueueCounterAsync(queueId, token); + if (order.Ct == GrainsCargo.BulkGallab && scac != options.BadiyaScac) + await repo.IncrementCompanyQueueAsync(scac, "GALLAB", "COMP", token); + + await repo.SetRequestedManualAsync(permit.Id, r.Locations, queueId, token); + await events.LogAsAsync(user.UserId, null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, + $"تحميل: {d?.Location} / {d?.CtCaption} / {d?.MobileShift}", ct: token); + + if (scac == options.BadiyaScac) + { + if (!r.ReservedQueue) await repo.SetLastPermitAsync(r.Locations, permit.Id, token); + await repo.DeletePendingDistributionAsync(permit.Id, permit.Tn ?? string.Empty, null, token); + await repo.InsertDistributionLogAsync(permit.Id, r.Locations, orderDate, permit.Tn ?? string.Empty, "MANUAL_DEST", d?.CargoTypeCode, token); + } + return true; + }, ct); + + var payload = new Dictionary + { + ["TN"] = permit.Tn, ["PN"] = r.Pn, ["TT"] = order.Ct == GrainsCargo.BulkGallab ? d?.CargoType + " قلاب " : d?.CargoType, + ["LOCATION"] = d?.Location, ["ORDERDATE"] = r.OrderDate, ["SHIFT"] = d?.MobileShift + }; + var wrapper = new Dictionary { ["NOTIFICATIONARY"] = new[] { payload } }; + await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS", wrapper, ct); + await notifications.SendAsync("DISTRIBUTE_PACKED_BULK_OWNERS_COMPANIES", wrapper, ct); + + return PermitOperationResult.Ok("تم تحويل حالة السيارة إلى توزيع طلبية", permit.Id); + } + + public async Task ProcessCompanyOpenPermitsAsync(CompanyOpenPermitsRequest r, CancellationToken ct = default) + { + new CompanyOpenPermitsValidator().ValidateAndThrow(r); + var open = await repo.GetOpenCompanyPermitsAsync(options.BadiyaScac, ct); + if (open.Count == 0) throw new BusinessException("NO_OPEN_PERMITS", "لا توجد سيارات على الدور لأي شركة"); + + var done = 0; + foreach (var p in open) + { + var order = await repo.GetAnyNextOrderAsync(ct); + if (order is null) break; + + if (await repo.IsLocationAllowedForCompanyAsync(p.CompanyCode ?? 0, order.Destenation, ct)) + { + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetRequestedWithOrderAsync(p.Id, order.Id, token); + var d = await destinations.GetOrderDetailsAsync(order.Id, token); + await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, + $"تحميل: {d?.Location} / {d?.CargoType}", ct: token); + return true; + }, ct); + done++; + if (done >= r.Count) break; + } + else + { + await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Open, PermitStatus.Open, PermitEventType.Override, + $"رقم السيارة {p.Tn} لم يتم توزيعة لعدم وجود موقع متوافق مع طلب الشركة", ct: ct); + } + } + return PermitOperationResult.Ok($"نم تحويل {done} من أصل {r.Count} سيارة الى توزيع طلبية"); + } + + public async Task DistributeSingleTruckAsync(string tn, CancellationToken ct = default) + { + var permit = await repo.GetFirstOpenPermitByTnAsync(tn.Trim(), null, ct) + ?? throw new BusinessException("TN_INVALID", "TN is invalid"); + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetRequestedAsync(permit.Id, token); + await events.LogAsAsync("SYSTEM", null, permit.Id, PermitStatus.Open, PermitStatus.Requested, PermitEventType.Override, ct: token); + return true; + }, ct); + return PermitOperationResult.Ok("Done", permit.Id); + } + + // ------------------------------------------------------------------------------------------------ grids / inquiries + + public Task> GetSummaryAsync(CancellationToken ct = default) => repo.GetDistributedSummaryAsync(ct); + + public Task> GetPivotAsync(CancellationToken ct = default) => repo.GetDistributionPivotAsync(ct); + + public async Task SearchTruckAsync(string tn, CancellationToken ct = default) + { + tn = tn.Trim(); + var result = new TruckDistributionDto(); + var active = (await repo.GetTruckPermitStatusesAsync(tn, ct)) + .Where(r => r.Status is PermitStatus.Accepted or PermitStatus.Released or PermitStatus.ArrivedControl).ToList(); + if (active.Count == 0) result.ErrorMsg = "السيارة ليس لديها إرسالية فعالة"; + + result.Status = await repo.GetTruckLatestStatusCaptionAsync(tn, ct) ?? string.Empty; + var company = await repo.GetTruckLatestCompanyAsync(tn, ct); + + IReadOnlyList locations = company == options.BadiyaScac + ? await destinations.GetTruckDestinationsAsync(tn, ct) + : company is long c ? await destinations.GetCompanyLocationsAsync(c, ct) : []; + var names = await repo.GetLocationNamesAsync(locations, ct); + result.CompanyLocations = string.Concat(names.Select(n => " - " + n.Name)); + + var orders = await repo.GetActiveOrdersInWindowAsync(new ShiftWindow + { + Shift1First = options.OperationShift1[0], Shift1Last = options.OperationShift1[1], + Shift2First = options.OperationShift2[0], Shift2Last = options.OperationShift2[1] + }, ct); + + if (orders.Count > 0) + { + var destNames = await repo.GetLocationNamesAsync(orders.Select(o => o.Destenation).ToList(), ct); + result.Order = string.Concat(orders.Select(o => " / " + destNames.FirstOrDefault(n => n.Id == o.Destenation).Name)); + } + else result.Order = "لا توجد طلبيات متاحة"; + + long tender = 0, trucks = 0; + foreach (var o in orders) + { + tender += o.Quantity; + trucks += await destinations.CountAssignedTrucksAsync(o.Id, ct); + } + result.TenderTotalQuantity = tender; + result.TrucksTotalQuantity = trucks; + if (trucks >= tender) result.ErrorMsg += "لا توجد وجهات متاحة لهذا الشفت، تم توزيع كامل عدد الطلبية"; + return result; + } + + public Task> GetBlacklistedAsync(string tn, CancellationToken ct = default) => + repo.GetBlacklistedDistributionsAsync(tn.Trim(), ct); + + public async Task CheckTripsAsync(CheckTripsRequest r, CancellationToken ct = default) + { + var count = await repo.GetTripCountAsync(r.Tn.Trim(), ct); + if (r.MaxTnCount - count <= 0) + { + // legacy wrote this event twice; once is enough + await events.LogAsAsync("SYSTEM", null, r.PermitId, PermitStatus.Open, PermitStatus.Open, PermitEventType.Override, + $"لم يتم توزيع أي وجهة للسيارة رقم {r.Tn} لأن السيارة استنفذت عدد رحلاتها", ct: ct); + return PermitOperationResult.Fail("noTrip", "noTrip", r.PermitId); + } + return PermitOperationResult.Ok(string.Empty, r.PermitId); + } + + public async Task RevokeAllRequestedAsync(long scrnBelow, CancellationToken ct = default) + { + if (scrnBelow <= 0) throw new ValidationException("حد رقم الطلبية غير صحيح"); + var rows = await repo.GetRequestedPermitsBelowOrderAsync(scrnBelow, options.BadiyaScac, ct); + var count = 0; + foreach (var p in rows) + { + await uow.ExecuteInTransactionAsync(async token => + { + await repo.ResetPermitToOpenAsync(p.Id, "SYSTEM", token); + await events.LogAsAsync("SYSTEM", null, p.Id, PermitStatus.Requested, PermitStatus.Open, PermitEventType.Override, + "SYSTEM REJECT - Old Permits", ct: token); + return true; + }, ct); + count++; + } + return PermitOperationResult.Ok($"تمت بنجاح ({count})"); + } + + public async Task RevertUnloadedPermitsAsync(string actor, CancellationToken ct = default) + { + var rows = await repo.GetUnloadedPermitsAsync(options.OperationShift1[0], ct); + if (rows.Count == 0) return 0; + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetStatusOpenAsync(rows.Select(r => r.Id).ToList(), token); + foreach (var r in rows) + await events.LogAsAsync(actor, null, r.Id, r.ShipmentStatusCode, null, PermitEventType.Override, + "تم تبويش هذه الارسالية بسبب تجاوز المهلة الزمنية الخاصة بالتحميل", ct: token); + return true; + }, ct); + return rows.Count; + } + + // ------------------------------------------------------------------------------------------------ auto call + + public async Task SendAutoCallFileAsync(AutoCallRequest r, CancellationToken ct = default) + { + // staff choose the company, company users are limited to their own (GrainsFactoryWeb.autoCallService2) + var company = user.IsCompany(options) ? user.CompanyCodeNo()?.ToString(CultureInfo.InvariantCulture) : r.CompanyCode; + var filter = r with { CompanyCode = company }; + var tender = PermitService.ParseTenderOrder(r.TenderOrder); + var rows = await repo.GetCallingDriverRowsAsync(filter, tender, ct); + + var ok = await autoCall.SendCallFileAsync(BuildCallingFile(rows), ct); + return ok + ? PermitOperationResult.Ok(PermitOperationResult.DefaultOk, data: new Dictionary { ["rows"] = rows.Count }) + : PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي"); + } + + public async Task TriggerIvrAsync(CancellationToken ct = default) => + await autoCall.TriggerIvrAsync(ct) + ? PermitOperationResult.Ok(PermitOperationResult.DefaultOk) + : PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي"); + + /// writeCallingDriverFile: CSV consumed by the auto dialer. + internal static byte[] BuildCallingFile(IReadOnlyList rows) + { + var sb = new StringBuilder(); + sb.AppendLine("\"Name\",\"Phone\",\"Code1\",\"Code2\",\"Number1\",\"Number2\",\"Number3\",\"Number4\",\"Number5\",\"Item\",\"from\",\"origin\",\"Week\",\"Day\",\"Month\",\"DayNight\",\"ID\",\"Confirmation\",\"No\",\"status\""); + foreach (var r in rows) + { + var dayNight = r.MobileShift switch { 1 => "c:\\\\D.wav", 2 => "c:\\\\E.wav", 3 => "c:\\\\N.wav", _ => string.Empty }; + string[] cols = + [ + r.Name ?? "", r.Phone ?? "", r.Code1 ?? "", r.Code2 ?? "", r.Number1 ?? "", r.Number2 ?? "", r.Number3 ?? "", r.Number4 ?? "", + r.Number5 ?? "", r.Item ?? "", "C:\\\\GN.wav", r.Origin ?? "", r.Week ?? "", r.Day ?? "", r.Month ?? "", dayNight, + r.Id.ToString(CultureInfo.InvariantCulture), "", "", "" + ]; + sb.AppendLine(string.Join(',', cols.Select(c => "\"" + c.Replace("\"", "\"\"") + "\""))); + } + return new UTF8Encoding(false).GetBytes(sb.ToString()); + } + + public bool IsValidDialerApiKey(string? key) => + !string.IsNullOrEmpty(options.AutoCall.ApiKey) && string.Equals(key, options.AutoCall.ApiKey, StringComparison.Ordinal); + + /// autoCallResponse.cfc autoDail: CONFIRMED -> phone accept, POSTPONED -> phone reject for N days, NO_ANSWER -> postpone one day. + public async Task HandleDialerCallbackAsync(AutoCallResponse r, CancellationToken ct = default) + { + const string ok = "SUCCESSFULL_OPERATION"; + try + { + var permitId = string.IsNullOrWhiteSpace(r.ReferenceId) ? null : await repo.GetPermitIdByPnAsync(r.ReferenceId.Trim(), ct); + if (permitId is null) return new("200", ok); + var permit = await permits.GetAsync(permitId.Value, ct); + + switch (r.Key) + { + case "CONFIRMED": + await permitService.PhoneAcceptCoreAsync(permitId.Value, null, "SYSTEM", ct); + break; + case "POSTPONED": + { + if (!int.TryParse(r.Value, out var days) || days <= 0) return new("500", "invalid value"); + await permitService.PhoneRejectCoreAsync(permitId.Value, $" تم التأجيل {days} يوم", days, "SYSTEM", ct); + break; + } + case "NO_ANSWER": + { + if (await phoneRepo.HasPhoneEventTodayAsync(permitId.Value, ct)) return new("200", "ALREADY_HAS_PHONE_EVENT"); + await NoAnswerAsync(permit!, ct); + return new("200", "NO_ANSWER"); + } + } + return new("200", ok); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + return new("500", ex.Message); + } + } + + private async Task NoAnswerAsync(PermitRow permit, CancellationToken ct) + { + var order = permit.Scrn is long o ? await destinations.GetOrderAsync(o, ct) : null; + var sh = options.DistributionShift(order?.Shift ?? 1); + await uow.ExecuteInTransactionAsync(async token => + { + await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.NoAnswer, + "تم التأجيل ليوم واحد", ct: token); + await permits.ResetToOpenAsync(permit.Id, "SYSTEM", token); + await events.LogAsAsync("SYSTEM", null, permit.Id, permit.ShipmentStatusCode, PermitStatus.Open, PermitEventType.Override, ct: token); + await phoneRepo.InsertBlacklistAsync(new NewBlacklistEntry + { + Category = "NO_ANSWER", EntityId = permit.Id, CreatedBy = "SYSTEM", + ExpiryDate = PhoneRejectRules.BlacklistExpiry(DateTime.Now, sh[0], sh[1], 1), + Remarks = "تم التأجيل ليوم واحد" + }, "SYSTEM", token); + return true; + }, ct); + } +} diff --git a/src/NTP.Application/Grains/Permits/GrainsPermitsOptions.cs b/src/NTP.Application/Grains/Permits/GrainsPermitsOptions.cs new file mode 100644 index 0000000..edf3d00 --- /dev/null +++ b/src/NTP.Application/Grains/Permits/GrainsPermitsOptions.cs @@ -0,0 +1,116 @@ +namespace NTP.Application.Grains.Permits; + +/// +/// Configuration for the Grains permits slice (config section "Grains:Permits"). Replaces the legacy ColdFusion +/// application-scope variables that are NOT in the repository (application.GN_BadiyaSCAC, grnsOprationShft_*, +/// grnsdtrbutnshft_*, GN_ALLOWEDSTATUSES, PetWS, autoCallerIP, nafethApiKey). Defaults marked UNVERIFIED must be confirmed. +/// +public sealed class GrainsPermitsOptions +{ + public const string SectionName = "Grains:Permits"; + + /// SCAC of the "owners / individuals" pseudo company (legacy application.GN_BadiyaSCAC; hard-coded 327 elsewhere in grains.cfc). + public long BadiyaScac { get; set; } = 327; + + /// Stakeholder id of trucking companies (legacy session.stkid = 62): they only see their own permits. + public long CompanyStakeholderId { get; set; } = 62; + + /// Operation window of shift 1/2 as [firstHour, lastHour] relative to the order date (legacy grnsOprationShft_1/2). UNVERIFIED defaults. + public int[] OperationShift1 { get; set; } = [6, 18]; + public int[] OperationShift2 { get; set; } = [18, 30]; + + /// Distribution shifts [start, end] used to compute blacklist expiry (legacy grnsdtrbutnshft_N). UNVERIFIED defaults. + public int[] DistributionShift1 { get; set; } = [6, 18]; + public int[] DistributionShift2 { get; set; } = [18, 30]; + public int[] DistributionShift3 { get; set; } = [30, 42]; + + /// Statuses a truck/trailer/driver registration must have to be usable on a permit (legacy GN_ALLOWEDSTATUSES). UNVERIFIED. + public string[] AllowedStatuses { get; set; } = ["OPEN", "ACCPT"]; + + /// Initial value of the in-memory "absence" feature flag (legacy application.GNABSENCEFEATURE). UNVERIFIED. + public bool AbsenceFeatureEnabled { get; set; } = true; + + /// MOT ownership codes allowed for owners / for companies (legacy GN_BadyahOwnership / GN_OthersOwnership). + /// Empty = the check is skipped (UNVERIFIED: the legacy values are not in the repository). + public string[] BadiyaOwnershipCodes { get; set; } = []; + public string[] OtherOwnershipCodes { get; set; } = []; + + public TcsOptions Tcs { get; set; } = new(); + public AutoCallOptions AutoCall { get; set; } = new(); + public NotificationOptions Notifications { get; set; } = new(); + public WeighbridgeSourceOptions WeighbridgeSource { get; set; } = new(); + public JobOptions Jobs { get; set; } = new(); + + public int[] DistributionShift(long shift) => shift switch + { + 2 => DistributionShift2, + 3 => DistributionShift3, + _ => DistributionShift1 + }; + + public int[] OperationShift(long shift) => shift == 1 ? OperationShift1 : OperationShift2; +} + +/// Outbound TCS (petroleum permit web service, legacy application.PetWS) integration. +public sealed class TcsOptions +{ + public bool Enabled { get; set; } + + /// Endpoint of CreatePermitWS (legacy application.PetWS, ApplicationVariables.xml). + public string PermitServiceUrl { get; set; } = "http://192.168.1.90:8080/FDfolioWS/services/CreatePermitWS"; + + public int TimeoutSeconds { get; set; } = 60; +} + +/// Outbound IVR / auto-dialer integration (GrainsFactoryWeb.autoCallService / autoCallService2, autoCallResponse.cfc). +public sealed class AutoCallOptions +{ + public bool Enabled { get; set; } + + /// Legacy application.autoCallerIP: receives {"TYPE":"TEST","FILE":"<base64 csv>"}. + public string SendUrl { get; set; } = string.Empty; + + /// Legacy IVR web service (http://aqtcs.nafith.net/IVR/callivr.cfc) - callAPI. + public string IvrUrl { get; set; } = string.Empty; + + /// Expected X-Api-Key of the dialer's callback (legacy application.nafethApiKey). Empty = callback disabled. + public string ApiKey { get; set; } = string.Empty; + + public int TimeoutSeconds { get; set; } = 30; +} + +/// Mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage). +public sealed class NotificationOptions +{ + public bool Enabled { get; set; } + public string Url { get; set; } = string.Empty; + public int TimeoutSeconds { get; set; } = 15; +} + +/// External weighbridge database (legacy datasource GrainsWeighbridge, table CARGO). +public sealed class WeighbridgeSourceOptions +{ + public string ConnectionString { get; set; } = string.Empty; +} + +/// Scheduled jobs. Every job is disabled by default; set Enabled=true per job to run it inside the API process. +public sealed class JobOptions +{ + public JobSchedule ActivateDestinations { get; set; } = new() { IntervalMinutes = 60 }; + public JobSchedule GabanTimeout { get; set; } = new() { IntervalMinutes = 60 }; + public JobSchedule WeighbridgeSync { get; set; } = new() { IntervalMinutes = 5 }; + public JobSchedule AqabaWeighbridgeSync { get; set; } = new() { IntervalMinutes = 5 }; + public JobSchedule PermitSeeding { get; set; } = new() { IntervalMinutes = 60 }; +} + +public sealed class JobSchedule +{ + public bool Enabled { get; set; } + public int IntervalMinutes { get; set; } = 60; +} + +/// Supplies the bound "Grains:Permits" settings (implemented in Infrastructure; registered by the *Service naming convention). +public interface IGrainsPermitsSettingsService +{ + GrainsPermitsOptions Value { get; } +} diff --git a/src/NTP.Application/Grains/Permits/IDestinationRepository.cs b/src/NTP.Application/Grains/Permits/IDestinationRepository.cs new file mode 100644 index 0000000..4dd8dab --- /dev/null +++ b/src/NTP.Application/Grains/Permits/IDestinationRepository.cs @@ -0,0 +1,100 @@ +namespace NTP.Application.Grains.Permits; + +public sealed class ShiftWindow +{ + public int Shift1First { get; set; } + public int Shift1Last { get; set; } + public int Shift2First { get; set; } + public int Shift2Last { get; set; } +} + +public sealed class TruckPermitForDestination +{ + public long Id { get; set; } + public string? Tn { get; set; } + public string? ShipmentStatusCode { get; set; } + public long? CompanyCode { get; set; } + public long? TrackingNo { get; set; } + public long? Scrn { get; set; } +} + +public sealed class TenderOrderCandidate +{ + public long Id { get; set; } + public long Destenation { get; set; } + public long CargoType { get; set; } + public long Quantity { get; set; } +} + +public sealed class CurrentOrderRow +{ + public long Id { get; set; } + public long? Location { get; set; } + public long? CargoType { get; set; } +} + +public sealed class LocationGroupsDto +{ + public IReadOnlyList Packed { get; set; } = []; + public IReadOnlyList Bulk { get; set; } = []; + public IReadOnlyList BulkGallab { get; set; } = []; +} + +public sealed class CompanyOption +{ + public long Scac { get; set; } + public string? CompanyCode { get; set; } +} + +/// Destinations, tender orders and company locations (assignDestination, setDestToPermit, getCompDest, ActivateOrder ...). +public interface IDestinationRepository +{ + // lookups + Task> GetGrainsLocationsAsync(CancellationToken ct = default); + Task> GetLocationsByTypeAsync(string type, CancellationToken ct = default); + + /// GNPermits.cfm destination filter: LOCATIONS domain GN, type EX, ordered by NAME, including inactive ones (old permits still point to them). + Task> GetPermitFilterDestinationsAsync(CancellationToken ct = default); + Task> GetCargoTypesAsync(CancellationToken ct = default); + Task GetLocationGroupsAsync(CancellationToken ct = default); + Task> GetCompaniesAsync(CancellationToken ct = default); + Task> GetCompanyLocationsAsync(long scac, CancellationToken ct = default); + Task> GetCompanyLocationItemsAsync(long scac, CancellationToken ct = default); + Task ReplaceCompanyLocationsAsync(long scac, IReadOnlyList locations, string userId, CancellationToken ct = default); + Task> GetTruckDestinationsAsync(string tn, CancellationToken ct = default); + Task GetLocationNameAsync(long id, CancellationToken ct = default); + Task GetCargoTypeNameAsync(long id, CancellationToken ct = default); + Task> GetOrderDatesAsync(CancellationToken ct = default); + + // orders + Task GetOrderAsync(long orderId, CancellationToken ct = default); + Task GetOrderDetailsAsync(long orderId, CancellationToken ct = default); + + /// LOCATIONS.NAME (domain GN) of a location id given as text, or null. + Task GetGrainsLocationNameAsync(string locationId, CancellationToken ct = default); + Task> GetAllowedDestinationsAsync(string pn, DateTime orderDate, IReadOnlyList allowed, + bool companyBranch, bool packed, CancellationToken ct = default); + Task> GetAllowedCargoAsync(PermitRow permit, long badiyaScac, CancellationToken ct = default); + Task> GetOrdersForPermitDateAsync(string pn, DateTime orderDate, CancellationToken ct = default); + Task GetManualOrderAsync(long orderId, CancellationToken ct = default); + + // assignment + Task> GetTruckPermitsForAssignmentAsync(string tn, CancellationToken ct = default); + Task GetLastAsrnAsync(string tn, CancellationToken ct = default); + Task> GetTenderOrderCandidatesAsync(string tn, IReadOnlyList locations, + long[]? cargoGroup, long? location, ShiftWindow window, CancellationToken ct = default); + Task CountAssignedTrucksAsync(long orderId, CancellationToken ct = default); + Task SetPermitDestinationAsync(long permitId, long originId, long destinationId, long cargoType, long orderId, string userId, + CancellationToken ct = default); + Task HasAssignDestEventAsync(string tn, CancellationToken ct = default); + Task<(string? Dest, long? Origin)> GetAssignedDestinationAsync(string tn, CancellationToken ct = default); + Task AssignByPnAsync(long permitId, long destId, long shipmentMode, CancellationToken ct = default); + + // activation of today's orders + Task> GetActivationRowsAsync(ShiftWindow window, CancellationToken ct = default); + Task> GetCurrentWindowOrdersAsync(ShiftWindow window, CancellationToken ct = default); + Task SetOrdersStatusAsync(IReadOnlyList ids, string status, string userId, CancellationToken ct = default); + + // activateGrainsDestination job + Task ActivatePendingCompanyDestinationsAsync(string actor, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Grains/Permits/IDistributionRepository.cs b/src/NTP.Application/Grains/Permits/IDistributionRepository.cs new file mode 100644 index 0000000..66acffe --- /dev/null +++ b/src/NTP.Application/Grains/Permits/IDistributionRepository.cs @@ -0,0 +1,116 @@ +namespace NTP.Application.Grains.Permits; + +public sealed class OrderTotalsRow +{ + public decimal TotalOwners { get; set; } + public decimal TotalComps { get; set; } + public decimal AllQuantity { get; set; } +} + +public sealed class OrderUsedRow +{ + public decimal UsedOwners { get; set; } + public decimal UsedComps { get; set; } +} + +public sealed class QueueSharePick +{ + public long Cnt { get; set; } + public long Scac { get; set; } +} + +public sealed class QueuePermitPick +{ + public long Id { get; set; } + public long Qid { get; set; } + public long Scac { get; set; } + public string? Pn { get; set; } + public string? Tn { get; set; } +} + +public sealed class NextOrderPick +{ + public long Id { get; set; } + public long Destenation { get; set; } +} + +public sealed class OwnerNotificationRow +{ + public string? Name { get; set; } + public string? OrderDate { get; set; } + public string? Shift { get; set; } + public string? Location { get; set; } +} + +public sealed class OpenOrderBrief +{ + public long Id { get; set; } + public long Destenation { get; set; } + public long Quantity { get; set; } +} + +public sealed class GabanPermitRow +{ + public long Id { get; set; } + public string? ShipmentStatusCode { get; set; } +} + +/// Distribution of OPEN permits to tender orders: grains.cfc distributePackedBulk, releasePermit, procssOpenPermit*, ... +public interface IDistributionRepository +{ + // distributePackedBulk + Task GetOrderTotalsAsync(string distributionCode, string queueType, bool packed, CancellationToken ct = default); + Task GetUsedOrdersAsync(string distributionCode, string queueType, bool packed, CancellationToken ct = default); + Task PrepareDataAsync(string cargoType, long badiyaScac, CancellationToken ct = default); + Task> GetCompanyShareAsync(string code, string? type, bool gallabCompany, long start, long queueAvailable, + CancellationToken ct = default); + Task> GetCompanyQueuePermitsAsync(IReadOnlyList shares, string distributionCode, + string permitCargoType, bool gallabCompany, bool bulkGallab, long badiyaScac, CancellationToken ct = default); + Task IncrementQueueCounterAsync(long queueId, CancellationToken ct = default); + Task IncrementCompanyQueueAsync(long scac, string code, string type, CancellationToken ct = default); + Task SetTrackingNoAsync(string pn, long queueId, CancellationToken ct = default); + Task GetOwnerDistributionDataAsync(string tn, long badiyaScac, CancellationToken ct = default); + + // releasePermit + Task GetOpenPermitWithFirmsAsync(string pn, long scac, CancellationToken ct = default); + Task> GetAllowedLocationsForReleaseAsync(PermitRow permit, long scac, long badiyaScac, CancellationToken ct = default); + Task GetNextOrderAsync(IReadOnlyList locations, string cargoCode, string? queueType, 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); + Task InsertDistributionLogAsync(long permitId, long orderId, DateTime orderDate, string tn, string notes, long? cargoType, + CancellationToken ct = default); + + // procssOpenPermit* + Task GetFirstOpenPermitByTnAsync(string tn, string? cargoType, CancellationToken ct = default); + Task> GetNextOrdersForTruckAsync(string tn, CancellationToken ct = default); + Task IsLocationAllowedForCompanyAsync(long scac, long location, CancellationToken ct = default); + Task SetRequestedAsync(long permitId, CancellationToken ct = default); + Task GetOrderForManualAsync(long orderId, CancellationToken ct = default); + Task PickQueueIdAsync(long scac, string code, string? type, CancellationToken ct = default); + Task SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default); + Task> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default); + Task GetAnyNextOrderAsync(CancellationToken ct = default); + + // grids / inquiries + Task> GetDistributedSummaryAsync(CancellationToken ct = default); + Task> GetDistributionPivotAsync(CancellationToken ct = default); + Task> GetTruckPermitStatusesAsync(string tn, CancellationToken ct = default); + Task GetTruckLatestStatusCaptionAsync(string tn, CancellationToken ct = default); + Task GetTruckLatestCompanyAsync(string tn, CancellationToken ct = default); + Task> GetActiveOrdersInWindowAsync(ShiftWindow window, CancellationToken ct = default); + Task> GetLocationNamesAsync(IReadOnlyList ids, CancellationToken ct = default); + Task> GetBlacklistedDistributionsAsync(string tn, CancellationToken ct = default); + Task GetTripCountAsync(string tn, CancellationToken ct = default); + + // admin / maintenance + Task> GetRequestedPermitsBelowOrderAsync(long scrnBelow, long badiyaScac, CancellationToken ct = default); + Task ResetPermitToOpenAsync(long permitId, string userId, CancellationToken ct = default); + Task> GetUnloadedPermitsAsync(int shiftOneFirstHour, CancellationToken ct = default); + Task SetStatusOpenAsync(IReadOnlyList ids, CancellationToken ct = default); + + // auto call + Task> GetCallingDriverRowsAsync(AutoCallRequest filter, DateTime? tenderDate, CancellationToken ct = default); + Task GetPermitIdByPnAsync(string pn, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Grains/Permits/IPermitRepository.cs b/src/NTP.Application/Grains/Permits/IPermitRepository.cs new file mode 100644 index 0000000..5c5c5fd --- /dev/null +++ b/src/NTP.Application/Grains/Permits/IPermitRepository.cs @@ -0,0 +1,127 @@ +using NTP.Application.Common; + +namespace NTP.Application.Grains.Permits; + +/// Criteria after the service has applied the caller's company restriction. +public sealed record PermitSearchCriteria( + string? Tn, string? Pn, string? Status, long? DestAddressId, DateTime? TenderOrderDate, string? ShipmentMode, + DateTime? CreationDate, long? CompanyCode); + +public sealed class TruckRegistrationRow +{ + public long? TcsCac { get; set; } + public string? HeadType { get; set; } + public string? StatusCode { get; set; } +} + +public sealed class OwnershipRow +{ + public string? OwnershipCode { get; set; } + public string? TruckTypeCode { get; set; } +} + +public sealed class ActiveConflictRow +{ + public long Id { get; set; } + public string? Pn { get; set; } +} + +public sealed class PermitOrderRow +{ + public long Id { get; set; } + public long? Scrn { get; set; } + public string? Ct { get; set; } +} + +public sealed class OrderForPermitRow +{ + public long Id { get; set; } + public DateTime? OrderDate { get; set; } + public long? Shift { get; set; } + public string? Ct { get; set; } + public string? Type { get; set; } + public long? Destination { get; set; } + public long? CargoType { get; set; } + public long? Location { get; set; } +} + +public sealed class DistributionLogRow +{ + public long Id { get; set; } + public DateTime? OrderDate { get; set; } + public long? PermitId { get; set; } + public long? CargoType { get; set; } + public string? Tn { get; set; } +} + +public sealed class NewBlacklistEntry +{ + public string Category { get; set; } = "PHONEDECLINE"; + public string EntityType { get; set; } = "PERMIT"; + public long EntityId { get; set; } + public string CreatedBy { get; set; } = string.Empty; + public DateTime ExpiryDate { get; set; } + public string Remarks { get; set; } = string.Empty; +} + +/// Permits: lists, details, order lifecycle (grains.cfc getGNPermits ... submitOrder, Accept, revoke ...). +public interface IPermitRepository +{ + // ---- lists / detail + Task> SearchAsync(PermitSearchCriteria c, PageRequest page, CancellationToken ct = default); + Task> SearchGateListAsync(GatePermitQuery q, string domain, long? companyCode, bool restrictToCompany, + PageRequest page, CancellationToken ct = default); + Task GetAsync(long id, CancellationToken ct = default); + Task GetByPnAsync(string pn, CancellationToken ct = default); + Task GetInfoAsync(long id, CancellationToken ct = default); + Task> GetEventsAsync(long permitId, CancellationToken ct = default); + + // ---- truck / trailer / driver lookups (domain GN) + Task GetTruckInfoAsync(string tn, long? companyCode, CancellationToken ct = default); + Task GetTrailerInfoAsync(string trn, long? companyCode, CancellationToken ct = default); + Task GetTrailerScacAsync(string trn, CancellationToken ct = default); + Task GetDriverInfoAsync(string nnpn, CancellationToken ct = default); + Task GetTruckRegistrationAsync(string tn, CancellationToken ct = default); + Task DriverIsRegisteredAsync(string nnpn, CancellationToken ct = default); + Task GetTruckStatusAsync(long scac, string tn, CancellationToken ct = default); + Task GetTrailerStatusAsync(string trn, CancellationToken ct = default); + Task GetDriverStatusAsync(string nnpn, CancellationToken ct = default); + Task> GetMotTruckAsync(long scac, string tn, CancellationToken ct = default); + Task FindActiveConflictAsync(string column, string value, long excludePermitId, CancellationToken ct = default); + Task GetPermitOrderAsync(long permitId, CancellationToken ct = default); + + // ---- order lifecycle writes + Task SubmitAsync(long id, SubmitOrderRequest r, DateTime? dled, string userId, CancellationToken ct = default); + Task UpdateOrderAsync(long id, UpdateOrderRequest r, DateTime? dled, string userId, CancellationToken ct = default); + 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); + Task RevokeNextOpenPermitsAsync(long permitId, string userId, CancellationToken ct = default); + Task FindOpenConflictForReactivationAsync(PermitRow permit, CancellationToken ct = default); + Task FindClosablePermitAsync(string pn, CancellationToken ct = default); + + // ---- stored weights + Task GetStoredWeightsAsync(string pn, long badiyaScac, CancellationToken ct = default); + Task GetStoredWeightsIdAsync(long permitId, CancellationToken ct = default); + Task UpsertStoredWeightsAsync(long permitId, long? existingId, SaveWeightsRequest r, string userId, CancellationToken ct = default); + Task LogActivationAsync(string type, string userId, string roleCode, string json, CancellationToken ct = default); +} + +/// Phone confirmation / rejection data access (addPhoneAcceptEvent / addPhoneRejectEvent / BL_addToBlacklist). +public interface IPhoneEventRepository +{ + Task HasClosedDistributionAsync(long permitId, long orderId, CancellationToken ct = default); + Task CloseDistributionAsync(long permitId, long orderId, string notes, CancellationToken ct = default); + Task GetTruckPhoneAsync(string tn, CancellationToken ct = default); + Task InsertBlacklistAsync(NewBlacklistEntry entry, string lastUpdateUser, CancellationToken ct = default); + Task DecrementQueueCounterAsync(long queueId, CancellationToken ct = default); + Task<(string? Code, string? Type)> GetQueueInfoAsync(long queueId, CancellationToken ct = default); + Task DecrementCompanyBulkQueueAsync(long scac, CancellationToken ct = default); + Task GetOrderDateDiffDaysAsync(long orderId, CancellationToken ct = default); + Task GetClosedDistributionAsync(long permitId, long orderId, CancellationToken ct = default); + Task PostponeApprovedDistributionAsync(DistributionLogRow current, long permitId, long orderId, long blacklistId, string note, + CancellationToken ct = default); + Task MarkDistributionRevokedAsync(long id, long blacklistId, string note, CancellationToken ct = default); + Task MarkPendingDistributionAsync(long permitId, long blacklistId, string note, bool revoke, CancellationToken ct = default); + Task HasPhoneEventTodayAsync(long permitId, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Grains/Permits/IQueueRepository.cs b/src/NTP.Application/Grains/Permits/IQueueRepository.cs new file mode 100644 index 0000000..6dfb5cf --- /dev/null +++ b/src/NTP.Application/Grains/Permits/IQueueRepository.cs @@ -0,0 +1,75 @@ +using NTP.Application.Common; + +namespace NTP.Application.Grains.Permits; + +public sealed class RoutingLegRow +{ + public long LocationId { get; set; } + public long SortOrder { get; set; } +} + +public sealed class PhRouteRow +{ + public long? OrgAddressId { get; set; } + public long? DestAddressId { get; set; } + public string? DefaultLane { get; set; } +} + +public sealed class CompanyShareRow +{ + public long Scac { get; set; } + public long CompanyShare { get; set; } +} + +/// Everything updateGNForm writes onto the QUED permit when the TCS permit is created. +public sealed class TcsPermitUpdate +{ + public string Pn { get; set; } = string.Empty; + public string StatusCode { get; set; } = string.Empty; + public long FinalDestination { get; set; } + public long CompanyCode { get; set; } + public string UserId { get; set; } = string.Empty; + public string Domain { get; set; } = string.Empty; + public CreateTcsPermitRequest Form { get; set; } = null!; +} + +/// Queue (turns) and TCS permit creation: CreateQueue.cfm, queueGrid.cfm, createPermit.cfm, ws.cfc createPermitRecord. +public interface IQueueRepository +{ + Task> ListAsync(QueueSearchQuery q, PageRequest page, CancellationToken ct = default); + Task GetActiveTruckScacAsync(string tn, CancellationToken ct = default); + Task HasActivePermitAsync(string tn, string tt, bool includeRequestedPlanned, CancellationToken ct = default); + Task NextTrackingSequenceAsync(bool owner, CancellationToken ct = default); + Task NextTripCounterAsync(string tt, long badiyaScac, CancellationToken ct = default); + Task GetTenderCountAsync(CancellationToken ct = default); + Task InsertPermitAsync(string pn, string? tn, long scac, string status, string tt, long? tripCounter, CancellationToken ct = default); + Task GetTrailerNumberAsync(string tn, string[] allowedStatuses, CancellationToken ct = default); + + // fleet turn check (checkTrucks) + Task CountFleetAsync(long scac, CancellationToken ct = default); + Task CountActiveValidationsAsync(long scac, CancellationToken ct = default); + Task ValidationExistsAsync(long scac, long tn, CancellationToken ct = default); + Task InsertValidationAsync(long scac, long tn, string userId, CancellationToken ct = default); + Task ClearValidationsAsync(long scac, CancellationToken ct = default); + + // bulk seeding of OPEN permits (parseGrainsPermits job) + Task> GetCompanyQueueSharesAsync(string code, long excludeScac, CancellationToken ct = default); + Task CountOpenPermitsAsync(long scac, string tt, CancellationToken ct = default); + + // TCS permit + Task PickRandomQuotaDestinationAsync(CancellationToken ct = default); + Task GetFormDataAsync(long permitId, string domain, CancellationToken ct = default); + Task> GetRoutingTemplatesAsync(long origin, long destination, string shipmentMode, string firms, + string domain, CancellationToken ct = default); + Task> GetOriginAddressesAsync(long routing, string domain, CancellationToken ct = default); + Task> GetPhRoutesAsync(CancellationToken ct = default); + Task GetPhRouteAsync(long routing, CancellationToken ct = default); + Task GetClearingAgentNameAsync(long can, CancellationToken ct = default); + Task GetPetroleumErrorTextAsync(IReadOnlyList codes, CancellationToken ct = default); + Task UpdateTcsPermitAsync(long permitId, TcsPermitUpdate u, CancellationToken ct = default); + Task GetPermitCreationDateAsync(long permitId, CancellationToken ct = default); + Task> GetRoutingLegsAsync(long routeId, CancellationToken ct = default); + Task InsertPermitStopAsync(long permitId, string domain, long? orgId, long destId, long sortOrder, DateTime? orgDepartDate, + CancellationToken ct = default); + Task IncrementDoneQuotaAsync(long destinationId, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Grains/Permits/IWeighbridgeRepository.cs b/src/NTP.Application/Grains/Permits/IWeighbridgeRepository.cs new file mode 100644 index 0000000..98418e9 --- /dev/null +++ b/src/NTP.Application/Grains/Permits/IWeighbridgeRepository.cs @@ -0,0 +1,44 @@ +namespace NTP.Application.Grains.Permits; + +public sealed class WeighbridgeEventInsert +{ + public long PermitId { get; set; } + public DateTime EventDate { get; set; } + public string EventType { get; set; } = string.Empty; + public string? PrevStatus { get; set; } + public string? CurrentStatus { get; set; } + public string DoneBy { get; set; } = string.Empty; + public long LocationId { get; set; } + public string UpdatedType { get; set; } = "NTP"; + public decimal Weight { get; set; } +} + +public sealed class RawPermitMatch +{ + public long Id { get; set; } + public string? ShipmentStatusCode { get; set; } +} + +/// Weighbridge events and raw weighbridge data (ws.cfc addWeightBridgeEvent, EN/EX_WeightBridge, getWeighbridgeEvents job). +public interface IWeighbridgeRepository +{ + Task GetPermitByTruckAndStatusAsync(string tn, string status, CancellationToken ct = default); + Task GetLatestLoadingTareAsync(long permitId, CancellationToken ct = default); + Task GetWeighbridgePermitAsync(string tn, CancellationToken ct = default); + Task InsertEventAsync(WeighbridgeEventInsert e, CancellationToken ct = default); + Task UpdateStatusByTruckAsync(string tn, string[] fromStatuses, string newStatus, string userId, CancellationToken ct = default); + Task LogIntegrationCallAsync(string ipAddress, string tn, string argsJson, CancellationToken ct = default); + Task GetLocationTypeAsync(long locationId, string domain, CancellationToken ct = default); + Task GetWaybridgeEventAsync(string tn, string? locationType, CancellationToken ct = default); + Task> GetLocationTruckCountsAsync(CancellationToken ct = default); + + // raw data job + Task> GetLastRawTimesAsync(long[] locationIds, CancellationToken ct = default); + Task InsertRawRowAsync(ExternalCargoRow row, string normalizedTruckNo, CancellationToken ct = default); + Task> GetUnprocessedRawRowsAsync(bool aqaba, CancellationToken ct = default); + Task FindPermitForRawAsync(string tn, string[] statuses, CancellationToken ct = default); + Task FindPermitByAssignedDestinationAsync(string tn, string ginTime, string tt, string[] excludedEventTypes, + CancellationToken ct = default); + Task MarkRawRowAsync(string rowId, long permitId, CancellationToken ct = default); + Task SetPermitStatusAsync(long permitId, string status, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Grains/Permits/PermitContracts.cs b/src/NTP.Application/Grains/Permits/PermitContracts.cs new file mode 100644 index 0000000..5dd4c78 --- /dev/null +++ b/src/NTP.Application/Grains/Permits/PermitContracts.cs @@ -0,0 +1,618 @@ +namespace NTP.Application.Grains.Permits; + +// --------------------------------------------------------------------------------------------------------------- +// Shared result type +// --------------------------------------------------------------------------------------------------------------- + +/// +/// Result of a write operation. Message is the legacy Arabic text; Success=false is a business outcome +/// that legacy returned as a normal response (not an exception), e.g. "no destination available". +/// +public sealed record PermitOperationResult(bool Success, string Message, string? Code = null, long? PermitId = null, + IReadOnlyDictionary? Data = null) +{ + public static PermitOperationResult Ok(string message, long? permitId = null, IReadOnlyDictionary? data = null) => + new(true, message, null, permitId, data); + + public static PermitOperationResult Fail(string code, string message, long? permitId = null) => + new(false, message, code, permitId); + + public const string DefaultOk = "تمت العملية بنجاح"; +} + +// --------------------------------------------------------------------------------------------------------------- +// Permit list / detail +// --------------------------------------------------------------------------------------------------------------- + +/// getGNPermits filters (strFilter keys). Dates: creationDate = yyyy-MM-dd, tenderOrder = dd/MM/yyyy. +public sealed record PermitSearchQuery( + string? Tn = null, string? Pn = null, string? Status = null, long? DestAddressId = null, + string? TenderOrder = null, string? ShipmentMode = null, string? CreationDate = null, long? CompanyCode = null) +{ + public bool HasFilter => !string.IsNullOrWhiteSpace(Tn) || !string.IsNullOrWhiteSpace(Pn) || !string.IsNullOrWhiteSpace(Status) + || DestAddressId.HasValue || !string.IsNullOrWhiteSpace(TenderOrder) || !string.IsNullOrWhiteSpace(ShipmentMode) + || !string.IsNullOrWhiteSpace(CreationDate) || CompanyCode.HasValue; +} + +public sealed class PermitListItem +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? TrackingNo { get; set; } + public DateTime? CreationDate { get; set; } + public string? DestinationName { get; set; } + public string? Drvr { get; set; } + public string? CompName { get; set; } + public string? StatusCaption { get; set; } + public string? ShipmentStatusCode { get; set; } + public long? CompanyCode { get; set; } + public string? QueueNo { get; set; } + /// Calculated by the service: which action buttons the caller may use on this row. + public IReadOnlyList Actions { get; set; } = []; +} + +/// getGNList (permitsGrid.cfm): gate/clearance list. +public sealed record GatePermitQuery(string? Tn, string? Trn, string? Pn); + +public sealed class GatePermitItem +{ + public long Id { get; set; } + public string? PermNo { get; set; } + public string? Tn { get; set; } + public string? Drvr { get; set; } + public string? ShipmentMode { get; set; } + public string? ShipmentStatusCode { get; set; } + public string? StatusName { get; set; } + public long? CompanyCode { get; set; } + public string? CreatedBy { get; set; } + public string? LastUpdateDate { get; set; } + public string? FinalDestination { get; set; } +} + +public sealed class PermitRow +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Nnpn { get; set; } + public string? Drvr { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } + public string? Tt { get; set; } + public string? ShipmentStatusCode { get; set; } + public long? CompanyCode { get; set; } + public long? Scrn { get; set; } + public long? Crn { get; set; } + public long? TrackingNo { get; set; } + public long? TripCounter { get; set; } + public string? InbondTypeCode { get; set; } + public long? OriginAddressId { get; set; } + public long? DestinationAddressId { get; set; } + public string? ShipmentMode { get; set; } + public string? IsActive { get; set; } + public string? Notes { get; set; } + public long? Firms { get; set; } + public string? DrvrMobile { get; set; } + public DateTime? CreationDate { get; set; } +} + +public sealed class PermitInfoRow +{ + public string? Pn { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Nnpn { get; set; } + public string? ShipmentStatusCode { get; set; } + public string? Tt { get; set; } + public string? InbondTypeCode { get; set; } + public string? CargoTypeName { get; set; } + public string? QueueNo { get; set; } + public long? MobileShift { get; set; } + public long? CompanyCode { get; set; } + public string? CompanyName { get; set; } + public string? StatusCaption { get; set; } + public long? OrderId { get; set; } +} + +public sealed class TruckInfoRow +{ + public string? Tn { get; set; } + public string? ChasesNumber { get; set; } + public DateTime? RegDate { get; set; } + public string? Axials { get; set; } +} + +public sealed class DriverInfoRow +{ + public string? Nnpn { get; set; } + public string? Name { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } +} + +public sealed record TruckInfoDto(string Tn, string? ChasesNumber, string? Axials, string? RegDate); + +public sealed record TrailerInfoDto(string Trn, string? ChasesNumber, string? Axials, string? RegDate); + +public sealed record DriverInfoDto(string Nnpn, string? Name, string? Dln, string? Dled); + +public sealed class PermitEventDto +{ + public DateTime? EventDate { get; set; } + public string? EventType { get; set; } + public string? EventCaption { get; set; } + public string? DoneBy { get; set; } + public string? CurrentStatusCode { get; set; } + public string? CurrentStatus { get; set; } + public decimal? Weight { get; set; } + public string? Remarks { get; set; } +} + +public sealed class PermitDetailDto +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? StatusCode { get; set; } + public string? StatusCaption { get; set; } + public string? CompanyName { get; set; } + public long? CompanyCode { get; set; } + public string? QueueNo { get; set; } + public string? Shift { get; set; } + public string? CargoType { get; set; } + public string? OperationType { get; set; } + public string? OperationTypeCode { get; set; } + public TruckInfoDto? Truck { get; set; } + public TruckInfoDto? Trailer { get; set; } + public DriverInfoDto? Driver { get; set; } + public IReadOnlyList Actions { get; set; } = []; + public IReadOnlyList Events { get; set; } = []; +} + +// --------------------------------------------------------------------------------------------------------------- +// Order requests (submitOrder / updateOrder / phone / weights ...) +// --------------------------------------------------------------------------------------------------------------- + +public sealed record SubmitOrderRequest(string Tn, string Trn, string Nnpn, string Dln, string? Dled, string Name, string OpType); + +public sealed record UpdateOrderRequest(string Tn, string Trn, string Nnpn, string Dln, string? Dled, string Name); + +public sealed record ReasonRequest(string Reason); + +public sealed record PhoneAcceptRequest(string? Remarks); + +public sealed record PhoneRejectRequest(string Reason, int ExpiryDays); + +public sealed record ClosePermitRequest(string Pn); + +public sealed record SaveWeightsRequest(string Pn, string EmptyWeight, string GrossWeight, string DocumentNumber); + +public sealed class StoredWeightsDto +{ + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Drvr { get; set; } + public string? EmptyWeight { get; set; } + public string? GrossWeight { get; set; } + public string? DocumentNumber { get; set; } +} + +public sealed record AbsenceFeatureDto(bool Enabled); + +// --------------------------------------------------------------------------------------------------------------- +// Queue / TCS permit +// --------------------------------------------------------------------------------------------------------------- + +public sealed record QueueSearchQuery(string? Tn, string? Pn); + +public sealed class QueueItem +{ + public long Id { get; set; } + public string? Tn { get; set; } + public string? Pn { get; set; } + public DateTime? CreationDate { get; set; } +} + +/// AddToQueue (CreateQueue.cfm): create an OPEN permit record (turn) for a truck. +public sealed record AddToQueueRequest(string Tn, string Tt, bool CheckStatuses = false); + +public sealed record SeedPermitsRequest(IReadOnlyList Items); + +public sealed record SeedPermitItem(long Scac, string NextStatus, string Tt, int Count); + +/// createPermit (createPermit.cfm): the TCS "grain permit" form. +public sealed record CreateTcsPermitRequest( + long Routing, string Tn, string TrnAt, string Trn, string Tt, string Asrn, string? Can, string Nnpn, string Drvr, string Dln, + string Cat, string? Dled, string Nat, string ShipmentMode, string InbondTypeCode, string Firms, long OriginAddressId, + long DestinationAddressId, long RoutingTemplateId, string? Fop); + +public sealed class TcsFormDataDto +{ + public string? Tn { get; set; } + public string? TrnAt { get; set; } + public string? Trn { get; set; } + public string? Tt { get; set; } + public string? Drvr { get; set; } + public string? Cat { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } + public string? Nat { get; set; } + public string? Nnpn { get; set; } + public long? RoutingTemplateId { get; set; } + public long? OriginAddressId { get; set; } + public long? DestinationAddressId { get; set; } + public string? Firms { get; set; } + public string? Asrn { get; set; } + public string? Can { get; set; } + public string? CanName { get; set; } +} + +public sealed class RoutingTemplateDto +{ + public long Id { get; set; } + public string? RouteName { get; set; } +} + +public sealed class LookupItem +{ + public long Id { get; set; } + public string? Name { get; set; } +} + +public sealed class CodeLookupItem +{ + public string Code { get; set; } = string.Empty; + public string? Caption { get; set; } +} + +public sealed class DestinationQuotaPick +{ + public long DestId { get; set; } + public string? DestName { get; set; } +} + +public sealed record TcsPermitRequest( + string Firms, string InbondTypeCode, long RoutingTemplateId, string ShipmentMode, long OriginAddressId, long DestinationAddressId, + string Asrn, string? Fop, string? SealN, string? Tst, string CanName, string? Can, string Tn, string Trn, string TrnAt, string Tt, + string Nnpn, string Nat, string Cat, string Dln, string Drvr, string UserId, string CompanyName); + +public sealed record TcsPermitResult(string? PermitNumber, string? StatusCode, string Error) +{ + public bool Success => string.IsNullOrEmpty(Error); +} + +public sealed record TcsFopDetail(string Error, string? Tn, string? Trn, string? TrnAt, string? Tt, string? OriginAddressId, + string? Drvr, string? Nat, string? Nnpn, string? Dln, string? Cat, string? Dled); + +// --------------------------------------------------------------------------------------------------------------- +// Destinations / orders +// --------------------------------------------------------------------------------------------------------------- + +public sealed record AssignByPnRequest(string Pn, long DestId, long ShipmentMode); + +public sealed record AssignDestinationRequest(string Tn); + +public sealed record SaveCompanyDestinationsRequest(IReadOnlyList Destinations); + +public sealed record ManualInputRequest(string Pn, long OrderId, string OrderDate, decimal Ltw, decimal Lgw); + +public sealed class AllowedDestinationDto +{ + public long OrderId { get; set; } + public string? Name { get; set; } + public long? Dest { get; set; } + public string? OrderDate { get; set; } +} + +public sealed class OrderChoiceDto +{ + public long Id { get; set; } + public string? DestName { get; set; } +} + +public sealed class AllowedCargoDto +{ + public long Location { get; set; } + public long Ct { get; set; } + public decimal Q { get; set; } +} + +public sealed class OrderDetailsDto +{ + public long? CargoTypeCode { get; set; } + public string? CargoType { get; set; } + public string? Location { get; set; } + public long? LocationCode { get; set; } + public string? MobileShift { get; set; } + public string? OrderDate { get; set; } + public string? Ct { get; set; } + public string? CtCaption { get; set; } +} + +public sealed class OrderActivationRow +{ + public long LocId { get; set; } + public long CtId { get; set; } + public string? Loc { get; set; } + public string? Ct { get; set; } + public decimal Total { get; set; } + public decimal Used { get; set; } + public string? StatusCode { get; set; } +} + +public sealed record ActivateOrdersRequest(IReadOnlyList Selected); + +public sealed record DestinationSearchResult(string? Destination, long? Origin, string? Message); + +public sealed record AssignDestinationResult(bool Success, string Message); + +// --------------------------------------------------------------------------------------------------------------- +// Distribution +// --------------------------------------------------------------------------------------------------------------- + +public sealed record DistributeRequest(string Category); + +public sealed record ReleasePermitRequest(string Pn, string Scac, string Category, string QueueType); + +public sealed record OpenPermitRequest(string Tn, string? CargoType, bool SaveScrn = true); + +public sealed record OpenPermitWithDestinationRequest(string Pn, long Locations, string OrderDate, bool ReservedQueue); + +public sealed record CompanyOpenPermitsRequest(int Count); + +public sealed record CheckTripsRequest(long PermitId, string Tn, int MaxTnCount); + +public sealed class DistributionSummaryRow +{ + public long? CompanyCode { get; set; } + public string? Comp { get; set; } + public long Cnt { get; set; } +} + +public sealed class DistributionPivotRow +{ + public long? CompanyCode { get; set; } + public string? Company { get; set; } + public long Silos { get; set; } + public long Direct { get; set; } + public long Packed { get; set; } +} + +public sealed class TruckDistributionDto +{ + public string Status { get; set; } = string.Empty; + public string CompanyLocations { get; set; } = string.Empty; + public string Order { get; set; } = string.Empty; + public string ErrorMsg { get; set; } = string.Empty; + public long TrucksTotalQuantity { get; set; } + public long TenderTotalQuantity { get; set; } +} + +public sealed class BlacklistedDistributionDto +{ + public long BlacklistId { get; set; } + public string? Text { get; set; } + public long? CargoType { get; set; } +} + +// --------------------------------------------------------------------------------------------------------------- +// Weighbridge +// --------------------------------------------------------------------------------------------------------------- + +public sealed record WeighbridgeReadingRequest(string Tn, long Weight); + +public sealed record WeighbridgeWeightsRequest(string Tn, long GrossWeight, long TareWeight); + +public sealed record ManualWeighbridgeRequest(string Tn, long LocationId, long WeightIn, long WeightOut); + +/// ws.cfc addWeightBridgeEvent: weighbridge integration reading (EN/EX) at a location. +public sealed record WeighbridgeEventRequest(string Tn, long Weight, long LocationId, string EventDate, string TrxType, string? UserId); + +public sealed class WeighbridgeResult +{ + public bool Success { get; set; } + public string ErrorCode { get; set; } = "0"; + public string Message { get; set; } = string.Empty; + public string? Action { get; set; } + public long? PermitId { get; set; } +} + +public sealed class TruckPermitBriefDto +{ + public long Id { get; set; } + public string? Drvr { get; set; } + public string? Tn { get; set; } + public string? Pn { get; set; } + public string? ShipmentStatusCode { get; set; } +} + +public sealed class WaybridgeEventDto +{ + public string? Tn { get; set; } + public decimal? Weight { get; set; } +} + +public sealed class LocationTruckCountDto +{ + public string? Loc { get; set; } + public long Cnt { get; set; } +} + +public sealed class WeighbridgePermitRow +{ + public long Id { get; set; } + public string? ShipmentStatusCode { get; set; } + public long? OriginAddressId { get; set; } + public long? DestinationAddressId { get; set; } +} + +public sealed class WeighbridgeRawRow +{ + public string RowId { get; set; } = string.Empty; + public long LocationId { get; set; } + public string? CargoTruckNo { get; set; } + public decimal CargoWeightIn { get; set; } + public decimal CargoWeightOut { get; set; } + public decimal CargoWeightNet { get; set; } + public string GinTime { get; set; } = string.Empty; + public string GoutTime { get; set; } = string.Empty; +} + +/// A row read from the external weighbridge database (table CARGO). +public sealed class ExternalCargoRow +{ + public long LocationId { get; set; } + public string? CargoKey { get; set; } + public string? CargoState { get; set; } + public DateTime? CargoTimeIn { get; set; } + public decimal CargoWeightIn { get; set; } + public DateTime? CargoTimeOut { get; set; } + public decimal CargoWeightOut { get; set; } + public decimal CargoWeightNet { get; set; } + public string? CargoType { get; set; } + public string? CargoTypeTxt { get; set; } + public string? CargoDriverName { get; set; } + public string? CargoTruckNo { get; set; } + public string? CargoSource { get; set; } +} + +// --------------------------------------------------------------------------------------------------------------- +// Printing +// --------------------------------------------------------------------------------------------------------------- + +public sealed class AcceptPrintDto +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? ShipmentStatusCode { get; set; } + public string? Shift { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Drvr { get; set; } + public string? CompName { get; set; } + public string? OperationType { get; set; } + public string? Destination { get; set; } + public string? CargoType { get; set; } + public string? Location { get; set; } + public string? NextPn { get; set; } + public long? Crn { get; set; } + public long? Scrn { get; set; } + public string PrintedAt { get; set; } = string.Empty; + public bool HasOrder => Scrn.HasValue; +} + +public sealed class PrintHeaderRow +{ + public string? TrackingNo { get; set; } + public string? CompName { get; set; } + public string? Drvr { get; set; } + public string? Nnpn { get; set; } + public string? Tn { get; set; } + public string? ShipmentMode { get; set; } + public string? Destination { get; set; } + public string? Origin { get; set; } +} + +public sealed class PrintWeightEvent +{ + public long Id { get; set; } + public long? LocationId { get; set; } + public string? LocationName { get; set; } + public string? DoneBy { get; set; } + public decimal? Weight { get; set; } + public string? EventType { get; set; } +} + +public sealed class PrintInDto +{ + public PrintHeaderRow Header { get; set; } = new(); + public decimal LoadingTare { get; set; } + public decimal LoadingGross { get; set; } + public decimal DischargeTare { get; set; } + public decimal DischargeGross { get; set; } + public WeightFigures Loading { get; set; } = new(); + public WeightFigures Discharge { get; set; } = new(); + public long TonDifference { get; set; } + public long KiloDifference { get; set; } + public string Sign { get; set; } = " "; + public string? LoadingLocation { get; set; } + /// Officer of the receiving weighing (discharge gross), else of the first weighing found; legacy printed qry.doneby. + public string? DoneBy { get; set; } + public string? DischargeLocation { get; set; } +} + +public sealed class WeightFigures +{ + public long Net { get; set; } + public long Ton { get; set; } + public long Kilo { get; set; } +} + +public sealed class PrintOutDto +{ + public PrintHeaderRow Header { get; set; } = new(); + public long NetWeight { get; set; } + public long Ton { get; set; } + public long Kilo { get; set; } + public string? Location { get; set; } + public string? DoneBy { get; set; } +} + +public sealed class PermitDetailsPrintDto +{ + public long Id { get; set; } + public string? Pn { get; set; } + public string? StatusCode { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? TruckNationality { get; set; } + public string? TrailerType { get; set; } + public string? DriverName { get; set; } + public string? Nnpn { get; set; } + public string? Dln { get; set; } + public string? Cat { get; set; } + public DateTime? Dled { get; set; } + public string? DriverNationality { get; set; } + public string? ShipmentMode { get; set; } + public string? Operation { get; set; } + public string? Lane { get; set; } + public string? Origin { get; set; } + public string? Destination { get; set; } + public string? RouteName { get; set; } + public IReadOnlyList Events { get; set; } = []; +} + +// --------------------------------------------------------------------------------------------------------------- +// Auto call +// --------------------------------------------------------------------------------------------------------------- + +public sealed record AutoCallRequest(string? Tn, string? ShipmentStatusCode, string? DestAddressId, string? TenderOrder, + string? ShipmentMode, string? CompanyCode); + +public sealed class AutoCallDriverRow +{ + public string? Name { get; set; } + public string? Phone { get; set; } + public string? Code1 { get; set; } + public string? Code2 { get; set; } + public string? Number1 { get; set; } + public string? Number2 { get; set; } + public string? Number3 { get; set; } + public string? Number4 { get; set; } + public string? Number5 { get; set; } + public string? Item { get; set; } + public string? FromDist { get; set; } + public string? Origin { get; set; } + public string? Week { get; set; } + public string? Day { get; set; } + public string? Month { get; set; } + public long Id { get; set; } + public long? MobileShift { get; set; } +} + +/// Body of the dialer's callback (autoDail): referenceId = PN, key = CONFIRMED | POSTPONED | NO_ANSWER. +public sealed record AutoCallResponse(string? ReferenceId, string? Key, string? Value); + +public sealed record AutoCallCallbackResult(string Code, string Message); diff --git a/src/NTP.Application/Grains/Permits/PermitEventLog.cs b/src/NTP.Application/Grains/Permits/PermitEventLog.cs new file mode 100644 index 0000000..6993a26 --- /dev/null +++ b/src/NTP.Application/Grains/Permits/PermitEventLog.cs @@ -0,0 +1,24 @@ +using NTP.Application.Abstractions; + +namespace NTP.Application.Grains.Permits; + +/// Writes legacy-style GN events (EVENTS row with PERMITID, domain 'GN', updated type 'NTP'). +public static class PermitEventLog +{ + public const string Domain = "GN"; + + /// addEvent('PERMITID', id, prev, curr, user, role?, 'GN', location, 'NTP', remarks, weight) for the signed-in user. + public static Task LogAsync(this IEventLogger events, ICurrentUser user, long permitId, string? prev, string? curr, + string eventType, string? remarks = null, string? weight = null, bool withLocation = true, CancellationToken ct = default) => + events.AddAsync(new EventEntry("PERMITID", permitId, prev, curr, user.UserId, eventType, Domain, + withLocation ? user.LocationText() : null, "NTP", weight, Remarks(remarks)), ct); + + /// Same, performed by a named actor (SYSTEM for jobs / dialer callbacks, W{location} for weighbridges). + public static Task LogAsAsync(this IEventLogger events, string doneBy, string? locationId, long permitId, string? prev, string? curr, + string eventType, string? remarks = null, string? weight = null, string updatedType = "NTP", CancellationToken ct = default) => + events.AddAsync(new EventEntry("PERMITID", permitId, prev, curr, doneBy, eventType, Domain, locationId, updatedType, weight, + Remarks(remarks)), ct); + + private static IReadOnlyDictionary? Remarks(string? remarks) => + string.IsNullOrEmpty(remarks) ? null : new Dictionary { ["REMARKS"] = remarks }; +} diff --git a/src/NTP.Application/Grains/Permits/PermitService.cs b/src/NTP.Application/Grains/Permits/PermitService.cs new file mode 100644 index 0000000..8579b2a --- /dev/null +++ b/src/NTP.Application/Grains/Permits/PermitService.cs @@ -0,0 +1,648 @@ +using System.Globalization; +using System.Text.Json; +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Permits; + +namespace NTP.Application.Grains.Permits; + +public interface IPermitService +{ + Task> SearchAsync(PermitSearchQuery query, PageRequest page, CancellationToken ct = default); + Task> SearchGateListAsync(GatePermitQuery query, PageRequest page, CancellationToken ct = default); + Task GetAsync(long id, CancellationToken ct = default); + Task> GetEventsAsync(long id, CancellationToken ct = default); + + Task GetTruckInfoAsync(string tn, bool validate, CancellationToken ct = default); + Task GetTrailerInfoAsync(string trn, CancellationToken ct = default); + Task GetDriverInfoAsync(string nnpn, CancellationToken ct = default); + + Task SubmitAsync(long id, SubmitOrderRequest request, CancellationToken ct = default); + Task UpdateAsync(long id, UpdateOrderRequest request, CancellationToken ct = default); + Task AcceptAsync(long id, CancellationToken ct = default); + Task RevokeAsync(long id, CancellationToken ct = default); + Task RevokeAcceptedAsync(long id, CancellationToken ct = default); + Task ConvertToResdAsync(long id, CancellationToken ct = default); + Task CancelOrderAsync(long id, ReasonRequest request, CancellationToken ct = default); + Task RevokePermitAsync(long id, ReasonRequest request, CancellationToken ct = default); + Task ReactivateAsync(long id, CancellationToken ct = default); + + /// GrainsFactory.cancelGrainsPermit: a released permit goes back to ACCPT (used by integrations). + Task CancelGrainsPermitAsync(long id, CancellationToken ct = default); + Task CloseManualAsync(ClosePermitRequest request, CancellationToken ct = default); + + Task PhoneAcceptAsync(long id, PhoneAcceptRequest request, CancellationToken ct = default); + Task PhoneRejectAsync(long id, PhoneRejectRequest request, CancellationToken ct = default); + + /// Phone accept performed by an actor other than the signed-in user (auto dialer callback = SYSTEM). + Task PhoneAcceptCoreAsync(long permitId, string? remarks, string doneBy, CancellationToken ct); + + /// Phone reject performed by an actor other than the signed-in user (auto dialer callback = SYSTEM). + Task PhoneRejectCoreAsync(long permitId, string reason, int expiryDays, string doneBy, CancellationToken ct, + string category = "PHONEDECLINE"); + + Task ValidateReferencesAsync(string tn, string trn, string nnpn, long scac, CancellationToken ct = default); + + Task SaveWeightsAsync(SaveWeightsRequest request, CancellationToken ct = default); + Task LookupWeightsAsync(string pn, CancellationToken ct = default); + + AbsenceFeatureDto GetAbsenceFeature(); + Task ToggleAbsenceFeatureAsync(CancellationToken ct = default); +} + +/// +/// Order lifecycle of grain permits (legacy grains.cfc: getGNPermits, getGNList, getPermitInfo, submitOrder, updateOrder, +/// Accept, revoke, RevokeAcceptedOrder, convertToResd, deleteGnOrder, RevokeGnPermit, activateGNOrder, closePermit, +/// addPhoneAcceptEvent, addPhoneRejectEvent, saveGrainsWeights, permitAutoComplete, ActiveInActiveGNAbsenceFeature). +/// +public sealed class PermitService( + IPermitRepository repo, + IPhoneEventRepository phoneRepo, + IDestinationRepository destinations, + IQueueService queue, + IMobileNotificationGatewayService notifications, + IEventLogger events, + IUnitOfWork uow, + ICurrentUser user, + IGrainsPermitsSettingsService settings) : IPermitService +{ + private GrainsPermitsOptions options => settings.Value; + + private const string Entity = "Permit"; + + // ------------------------------------------------------------------------------------------------ lists + + public async Task> SearchAsync(PermitSearchQuery q, PageRequest page, CancellationToken ct = default) + { + // Legacy returned an empty grid until at least one filter was given ("يجب البحث اولا لتظهر لك الأرساليات"). + if (!q.HasFilter) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + + var company = q.CompanyCode; + if (user.IsCompany(options)) company = user.CompanyCodeNo() ?? -1; // session.stkid = 62 -> own permits only + + var criteria = new PermitSearchCriteria( + Trim(q.Tn), Trim(q.Pn), Trim(q.Status), q.DestAddressId, ParseTenderOrder(q.TenderOrder), Trim(q.ShipmentMode), + PermitDates.ParseLegacy(q.CreationDate), company); + + var result = await repo.SearchAsync(criteria, page, ct); + foreach (var row in result.Items) + row.Actions = ActionsFor(row.ShipmentStatusCode, row.CompanyCode); + return result; + } + + public Task> SearchGateListAsync(GatePermitQuery q, PageRequest page, CancellationToken ct = default) + { + // getGNList: gate roles see every company, everybody else only its own company code. + var restrict = !user.IsInAnyRole("GATEIN", "GATEOUT", "THRU"); + return repo.SearchGateListAsync(q with { Tn = Trim(q.Tn), Trn = Trim(q.Trn), Pn = Trim(q.Pn) }, user.Domain, user.CompanyCodeNo(), + restrict, page, ct); + } + + public async Task GetAsync(long id, CancellationToken ct = default) + { + var info = await repo.GetInfoAsync(id, ct) ?? throw new NotFoundException(Entity, id); + EnsureCompanyAccess(info.CompanyCode); + + var truck = string.IsNullOrWhiteSpace(info.Tn) ? null : await repo.GetTruckInfoAsync(info.Tn, null, ct); + var trailer = string.IsNullOrWhiteSpace(info.Trn) ? null : await repo.GetTrailerInfoAsync(info.Trn, null, ct); + var driver = string.IsNullOrWhiteSpace(info.Nnpn) ? null : await repo.GetDriverInfoAsync(info.Nnpn, ct); + var evs = await repo.GetEventsAsync(id, ct); + + return new PermitDetailDto + { + Id = id, + Pn = info.Pn, + StatusCode = info.ShipmentStatusCode, + StatusCaption = info.StatusCaption, + CompanyCode = info.CompanyCode, + CompanyName = info.CompanyName, + QueueNo = info.QueueNo, + Shift = OrderLabels.ShiftShort(info.MobileShift), + CargoType = info.CargoTypeName, + OperationTypeCode = info.InbondTypeCode, + OperationType = OrderLabels.OperationType(info.InbondTypeCode), + Truck = truck is null ? (info.Tn is null ? null : new TruckInfoDto(info.Tn, null, null, null)) : ToDto(truck), + Trailer = trailer is null ? (info.Trn is null ? null : new TruckInfoDto(info.Trn, null, null, null)) : ToDto(trailer), + Driver = driver is null ? null : new DriverInfoDto(driver.Nnpn ?? string.Empty, driver.Name, driver.Dln, PermitDates.Display(driver.Dled)), + Actions = ActionsFor(info.ShipmentStatusCode, info.CompanyCode), + // createGnOrder.cfm hides the "performed by" column from company users; the API keeps the field and the UI hides it. + Events = evs + }; + } + + public async Task> GetEventsAsync(long id, CancellationToken ct = default) + { + var p = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); + EnsureCompanyAccess(p.CompanyCode); + return await repo.GetEventsAsync(id, ct); + } + + // ------------------------------------------------------------------------------------------------ lookups + + public async Task GetTruckInfoAsync(string tn, bool validate, CancellationToken ct = default) + { + tn = tn.Trim(); + var companyNo = user.CompanyCodeNo(); + if (validate) + { + if (companyNo is null) throw new BusinessException("TN_COMPANY_REQUIRED", "القاطرة غير موجودة "); + await ValidateMotAsync(tn, companyNo.Value, ct); + } + + var row = await repo.GetTruckInfoAsync(tn, user.IsCompany(options) ? companyNo : null, ct); + return row is null ? null : ToDto(row); + } + + public async Task GetTrailerInfoAsync(string trn, CancellationToken ct = default) + { + trn = trn.Trim(); + if (user.IsCompany(options)) + { + var scac = await repo.GetTrailerScacAsync(trn, ct); + if (scac != user.CompanyCodeNo()) + throw new BusinessException("TRAILER_NOT_IN_FLEET", PermitAssignmentRules.TrailerNotInFleet); + } + var row = await repo.GetTrailerInfoAsync(trn, user.IsCompany(options) ? user.CompanyCodeNo() : null, ct); + return row is null ? null : new TrailerInfoDto(trn, row.ChasesNumber, row.Axials, PermitDates.Display(row.RegDate)); + } + + public async Task GetDriverInfoAsync(string nnpn, CancellationToken ct = default) + { + var r = await repo.GetDriverInfoAsync(nnpn.Trim(), ct); + return r is null ? null : new DriverInfoDto(r.Nnpn ?? nnpn, r.Name, r.Dln, PermitDates.Display(r.Dled)); + } + + private async Task ValidateMotAsync(string tn, long companyNo, CancellationToken ct) + { + // register.cfc validateOwnerTN + validateTNMOT (trucktype.general.cargo). + var rows = await repo.GetMotTruckAsync(companyNo, tn, ct); + if (rows.Count == 0) + throw new BusinessException("MOT_NOT_REGISTERED", "خطأ في تسجيل السيارة/ السيارة غير مؤتلفة"); + + var ownership = rows[0].OwnershipCode; + if (companyNo == options.BadiyaScac) + { + if (options.BadiyaOwnershipCodes.Length > 0 && !options.BadiyaOwnershipCodes.Contains(ownership ?? string.Empty)) + throw new BusinessException("MOT_OWNERSHIP", "لا يجوز اضافة سيارات الاهالي على الشركات"); + } + else if (options.OtherOwnershipCodes.Length > 0 && !options.OtherOwnershipCodes.Contains(ownership ?? string.Empty)) + { + throw new BusinessException("MOT_OWNERSHIP", "لا يجوز اضافة سيارات الاهالي على الشركات"); + } + + if (!rows.Any(r => r.TruckTypeCode is "trucktype.general.cargo" or "trucktype.all")) + throw new BusinessException("MOT_WRONG_TYPE", "النمط غير صحيح"); + } + + // ------------------------------------------------------------------------------------------------ submit / update + + public async Task SubmitAsync(long id, SubmitOrderRequest r, CancellationToken ct = default) + { + new SubmitOrderValidator().ValidateAndThrow(r); + var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); + EnsureCompanyAccess(permit.CompanyCode); + + // 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); + + var dled = PermitDates.ParseLegacy(r.Dled); + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SubmitAsync(id, r, dled, user.UserId, token); + var remarks = r.OpType == "IMPT" ? "محمل" : "فارغ"; + await events.LogAsync(user, id, PermitStatus.Requested, PermitStatus.Planned, PermitEventType.SaveOperationType, remarks, ct: token); + await events.LogAsync(user, id, PermitStatus.Requested, PermitStatus.Planned, PermitEventType.Override, ct: token); + return true; + }, ct); + + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + public async Task UpdateAsync(long id, UpdateOrderRequest r, CancellationToken ct = default) + { + new UpdateOrderValidator().ValidateAndThrow(r); + var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); + EnsureCompanyAccess(permit.CompanyCode); + + // Deviation: legacy did not check the status; the UI only offers "edit" for REQST / PLND, so the API enforces it. + if (permit.ShipmentStatusCode is not (PermitStatus.Requested or PermitStatus.Planned)) + throw new BusinessException("PERMIT_BAD_STATE", PermitAssignmentRules.BadStatus); + + await ValidateAssignmentAsync(permit, r.Tn, r.Trn, r.Nnpn, isSubmit: false, ct); + + var dled = PermitDates.ParseLegacy(r.Dled); + await uow.ExecuteInTransactionAsync(async token => + { + await repo.UpdateOrderAsync(id, r, dled, user.UserId, token); + await events.LogAsync(user, id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.Modify, ct: token); + return true; + }, ct); + + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + /// Ownership / fleet rules shared by submitOrder and updateOrder (messages kept verbatim). + private async Task ValidateAssignmentAsync(PermitRow permit, string tn, string trn, string nnpn, bool isSubmit, CancellationToken ct) + { + var isCompany = user.IsCompany(options); + var companyNo = user.CompanyCodeNo(); + + var truck = await repo.GetTruckRegistrationAsync(tn, ct); + if (truck?.TcsCac != companyNo && isCompany) + throw new BusinessException("TRUCK_NOT_IN_FLEET", PermitAssignmentRules.TruckNotInFleet); + if (truck?.TcsCac == companyNo && isCompany && permit.CompanyCode != companyNo) + throw new BusinessException("TRUCK_ON_FOREIGN_PERMIT", PermitAssignmentRules.TruckOnForeignPermit); + + var trailerScac = await repo.GetTrailerScacAsync(trn, ct); + if (trailerScac != companyNo && isCompany) + throw new BusinessException("TRAILER_NOT_IN_FLEET", PermitAssignmentRules.TrailerNotInFleet); + if (trailerScac == companyNo && isCompany && permit.CompanyCode != companyNo) + throw new BusinessException("TRAILER_ON_FOREIGN_PERMIT", PermitAssignmentRules.TrailerOnForeignPermit); + + if (isSubmit) + { + if (permit.CompanyCode != trailerScac) + throw new BusinessException("TRAILER_NOT_IN_FLEET", PermitAssignmentRules.TrailerNotInFleet); + if (!await repo.DriverIsRegisteredAsync(nnpn, ct)) + throw new BusinessException("DRIVER_NOT_REGISTERED", PermitAssignmentRules.DriverNotRegistered); + } + + var dup = await repo.FindActiveConflictAsync("TN", tn, permit.Id, ct); + if (dup is not null) + throw new BusinessException("TRUCK_HAS_ACTIVE_PERMIT", $"يوجد ارسالية فعالة للشاحنة, رقم الارسالية الفعالة {dup.Pn}"); + dup = await repo.FindActiveConflictAsync("TRN", trn, permit.Id, ct); + if (dup is not null) + throw new BusinessException("TRAILER_HAS_ACTIVE_PERMIT", $"يوجد ارسالية فعالة للمقطورة, رقم الارسالية الفعالة {dup.Pn}"); + dup = await repo.FindActiveConflictAsync("NNPN", nnpn, permit.Id, ct); + if (dup is not null) + throw new BusinessException("DRIVER_HAS_ACTIVE_PERMIT", $"يوجد ارسالية فعالة للسائق, رقم الارسالية الفعالة {dup.Pn}"); + + // A gallab order needs a tripper head. (submitOrder applies it to owner trailers only, updateOrder always.) + if (!isSubmit || trailerScac == options.BadiyaScac) + { + var order = await repo.GetPermitOrderAsync(permit.Id, ct); + if (order is not null && PermitAssignmentRules.IsGallabOrder(order.Ct) && !string.Equals(truck?.HeadType, "Tripper", StringComparison.Ordinal)) + throw new BusinessException("GALLAB_NEEDS_TRIPPER", PermitAssignmentRules.GallabNeedsTripper); + } + } + + // ------------------------------------------------------------------------------------------------ accept / revoke + + public async Task AcceptAsync(long id, CancellationToken ct = default) + { + var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); + EnsureCompanyAccess(permit.CompanyCode); + if (permit.ShipmentStatusCode != PermitStatus.Planned) + throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); + + var invalid = await ValidateReferencesAsync(permit.Tn ?? string.Empty, permit.Trn ?? string.Empty, permit.Nnpn ?? string.Empty, + permit.CompanyCode ?? 0, ct); + if (invalid.Length > 0) throw new BusinessException("PERMIT_REFERENCES_INVALID", invalid); + + await uow.ExecuteInTransactionAsync(async token => + { + // AddToQueue(TN, TT, COMPANYCODE, TRN, 'false'): opens the truck's next turn; its message is ignored by legacy. + await queue.AddToQueueInternalAsync(permit.Tn ?? string.Empty, permit.Tt ?? string.Empty, user.UserId, false, token); + await repo.SetStatusAsync(id, PermitStatus.Accepted, user.UserId, token); + await events.LogAsync(user, id, PermitStatus.Planned, PermitStatus.Accepted, PermitEventType.Override, ct: token); + return true; + }, ct); + + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + /// validatePermitReferences: returns an Arabic error text or empty when everything is registered and in an allowed status. + public async Task ValidateReferencesAsync(string tn, string trn, string nnpn, long scac, CancellationToken ct = default) + { + var allowed = options.AllowedStatuses; + var truck = await repo.GetTruckStatusAsync(scac, tn, ct); + if (truck is null) return "السيارة غير مسجلة"; + if (!allowed.Contains(truck)) return "حالة السيارة غير صحيحة"; + var trailer = await repo.GetTrailerStatusAsync(trn, ct); + if (trailer is null || !allowed.Contains(trailer)) return "حالة المقطورة غير صحيحة"; + var driver = await repo.GetDriverStatusAsync(nnpn, ct); + if (driver is null || !allowed.Contains(driver)) return "حالة السائق غير صحيحة"; + return string.Empty; + } + + public async Task RevokeAsync(long id, CancellationToken ct = default) + { + var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); + EnsureCompanyAccess(permit.CompanyCode); + if (permit.ShipmentStatusCode != PermitStatus.Planned) + throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); + + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetStatusAsync(id, PermitStatus.Requested, user.UserId, token); + await repo.ResetTruckValidationAsync(permit.Tn ?? string.Empty, user.UserId, token); + await events.LogAsync(user, id, PermitStatus.Planned, PermitStatus.Requested, PermitEventType.Override, ct: token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + public async Task RevokeAcceptedAsync(long id, CancellationToken ct = default) + { + 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)) + throw new BusinessException("PERMIT_BAD_STATE", + "حالة الإرسالية غير صحيحة ، يجب ان تكون الإرسالية جاهز للتسريب لتتمكن من الغاء تثبيتها"); + + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetStatusAsync(id, PermitStatus.Planned, user.UserId, token); + await events.LogAsync(user, id, permit.ShipmentStatusCode, PermitStatus.Planned, PermitEventType.Cancel, ct: token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + public async Task ConvertToResdAsync(long id, CancellationToken ct = default) + { + if (!user.IsInAnyRole(GrainsRoles.ConvertToResd.Split(','))) + throw new ForbiddenException("FORBIDDEN", "غير مصرح لك بهذه العملية"); + var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); + // Deviation: legacy converted by PN with no status check; the UI shows the button for ACCPT only. + if (permit.ShipmentStatusCode != PermitStatus.Accepted) + throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); + + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetStatusAsync(id, PermitStatus.Released, user.UserId, token); + await events.LogAsync(user, id, permit.ShipmentStatusCode, PermitStatus.Released, PermitEventType.ConvertToResd, ct: token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + public async Task CancelOrderAsync(long id, ReasonRequest r, CancellationToken ct = default) + { + 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. + if (permit.ShipmentStatusCode != PermitStatus.Released) + throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); + + await uow.ExecuteInTransactionAsync(async token => + { + await repo.ResetToOpenAsync(id, user.UserId, token); + // legacy logs the target status as RVKD although the permit goes back to OPEN + await events.LogAsync(user, id, permit.ShipmentStatusCode, PermitStatus.Revoked, PermitEventType.Override, r.Reason, ct: token); + await repo.RevokeNextOpenPermitsAsync(id, user.UserId, token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + public async Task RevokePermitAsync(long id, ReasonRequest r, CancellationToken ct = default) + { + 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. + if (permit.ShipmentStatusCode != PermitStatus.Open) + throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); + + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetStatusAsync(id, PermitStatus.Revoked, user.UserId, token); + await events.LogAsync(user, id, permit.ShipmentStatusCode, PermitStatus.Revoked, PermitEventType.Revoked, r.Reason, ct: token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + public async Task ReactivateAsync(long id, CancellationToken ct = default) + { + var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); + if (permit.ShipmentStatusCode != PermitStatus.Revoked) + throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); + + var conflict = await repo.FindOpenConflictForReactivationAsync(permit, ct); + if (conflict is not null) + throw new BusinessException("PERMIT_REACTIVATE_CONFLICT", + $"لا يمكن اعادة الارسالية الى على الدور القاطرة لديها ارسالية رقم {conflict.Pn}"); + + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetStatusAsync(id, PermitStatus.Open, user.UserId, token); + await events.LogAsync(user, id, PermitStatus.Revoked, PermitStatus.Open, PermitEventType.Override, ct: token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + public async Task CancelGrainsPermitAsync(long id, CancellationToken ct = default) + { + var permit = await repo.GetAsync(id, ct) ?? throw new NotFoundException(Entity, id); + if (permit.ShipmentStatusCode != PermitStatus.Released) + throw new BusinessException("PERMIT_BAD_STATE", "حالة الإرسالية غير صحيحة"); + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetStatusAsync(id, PermitStatus.Accepted, user.UserId, token); + await events.LogAsAsync(user.UserId, null, id, PermitStatus.Released, PermitStatus.Accepted, PermitEventType.Override, + "cancelGrainsPermit(GrainsFactory)", ct: token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, id); + } + + public async Task CloseManualAsync(ClosePermitRequest r, CancellationToken ct = default) + { + new ClosePermitValidator().ValidateAndThrow(r); + var permit = await repo.FindClosablePermitAsync(r.Pn, ct) + ?? throw new BusinessException("PN_INVALID", "رقم التصريح المدخل غير صحيح"); + + await uow.ExecuteInTransactionAsync(async token => + { + await repo.SetStatusAsync(permit.Id, PermitStatus.Closed, user.UserId, token); + await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, PermitStatus.Closed, PermitEventType.Override, + "اغلاق تصريح يدوي", withLocation: false, ct: token); + return true; + }, ct); + return PermitOperationResult.Ok("تم اغلاق التصريح بنجاح", permit.Id); + } + + // ------------------------------------------------------------------------------------------------ phone events + + public Task PhoneAcceptAsync(long id, PhoneAcceptRequest r, CancellationToken ct = default) => + PhoneAcceptCoreAsync(id, r.Remarks, user.UserId, ct); + + public Task PhoneRejectAsync(long id, PhoneRejectRequest r, CancellationToken ct = default) + { + new PhoneRejectValidator().ValidateAndThrow(r); + return PhoneRejectCoreAsync(id, r.Reason.Trim(), r.ExpiryDays, user.UserId, ct); + } + + /// addPhoneAcceptEvent. Also used by the dialer callback (autoCall) with doneBy = SYSTEM. + public async Task PhoneAcceptCoreAsync(long permitId, string? remarks, string doneBy, CancellationToken ct) + { + var permit = await repo.GetAsync(permitId, ct) ?? throw new NotFoundException(Entity, permitId); + var orderDetails = permit.Scrn is long o ? await destinations.GetOrderDetailsAsync(o, ct) : null; + + if (permit.Scrn is long order && await phoneRepo.HasClosedDistributionAsync(permitId, order, ct)) + throw new BusinessException("ALREADY_APPROVED_MOBILE", "تمت الموافقة مسبقا من مستخدم تطبيق نافذ"); + + var text = string.IsNullOrWhiteSpace(remarks) + ? " تمت الموافقة هاتفيا ، تم تحديد الوجهة " + $"{orderDetails?.CargoType} - {orderDetails?.Location}" + : remarks!; + + await uow.ExecuteInTransactionAsync(async token => + { + // legacy logs REQST -> REQST regardless of the actual status + await events.LogAsAsync(doneBy, null, permitId, PermitStatus.Requested, PermitStatus.Requested, PermitEventType.PhoneAccept, text, ct: token); + if (permit.Scrn is long ord) await phoneRepo.CloseDistributionAsync(permitId, ord, text, token); + return true; + }, ct); + + var phone = await phoneRepo.GetTruckPhoneAsync(permit.Tn ?? string.Empty, ct); + await notifications.SendAsync("CONFIRM_PN", new Dictionary + { + ["TN"] = permit.Tn, ["MOBILE"] = phone ?? string.Empty, ["PN"] = permit.Pn, + ["ORDERDATE"] = orderDetails?.OrderDate, ["TT"] = orderDetails?.CtCaption + }, ct); + + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, permitId); + } + + /// addPhoneRejectEvent (+ BL_addToBlacklist). Also used by the dialer callback with doneBy = SYSTEM. + public async Task PhoneRejectCoreAsync(long permitId, string reason, int expiryDays, string doneBy, + CancellationToken ct, string category = "PHONEDECLINE") + { + var permit = await repo.GetAsync(permitId, ct) ?? throw new NotFoundException(Entity, permitId); + var order = permit.Scrn is long o ? await destinations.GetOrderAsync(o, ct) : null; + var shift = order?.Shift ?? 1; + var sh = options.DistributionShift(shift); + var expiry = PhoneRejectRules.BlacklistExpiry(DateTime.Now, sh[0], sh[1], expiryDays); + var isAbsence = PhoneRejectRules.IsAbsence(reason); + + long blacklistId = 0; + await uow.ExecuteInTransactionAsync(async token => + { + blacklistId = await phoneRepo.InsertBlacklistAsync(new NewBlacklistEntry + { + Category = category, + EntityId = permitId, + CreatedBy = doneBy, + ExpiryDate = expiry, + Remarks = reason + "، سيتم فك الانتظار بشكل تلقائي بتاريخ " + + expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture) + }, doneBy, token); + + if (permit.Scrn is long ord && await phoneRepo.GetOrderDateDiffDaysAsync(ord, token) < 0 && permit.TrackingNo is long queueId) + { + // The order is for a future date: give the queue turn back. + await phoneRepo.DecrementQueueCounterAsync(queueId, token); + if (permit.CompanyCode != options.BadiyaScac && permit.CompanyCode is long scac) + { + var (code, _) = await phoneRepo.GetQueueInfoAsync(queueId, token); + if (code == "GALLAB") await phoneRepo.DecrementCompanyBulkQueueAsync(scac, token); + } + } + + await repo.ResetToOpenAsync(permitId, doneBy, token); + await repo.RevokeNextOpenPermitsAsync(permitId, doneBy, token); + return true; + }, ct); + + // Notification (after the transaction, as in legacy). + var phone = await phoneRepo.GetTruckPhoneAsync(permit.Tn ?? string.Empty, ct); + await notifications.SendAsync(isAbsence ? "PHONE_REJECT" : "DELAY_PN", new Dictionary + { + ["MOBILE"] = phone ?? string.Empty, ["NUMOFEXPIRYDAY"] = expiryDays, + ["EXPIRYDATE"] = DateTime.Now.AddDays(expiryDays).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), + ["PN"] = permit.Pn, ["TN"] = permit.Tn, ["TT"] = OrderLabels.OrderType(order?.Ct) + }, ct); + + await events.LogAsAsync(doneBy, null, permitId, PermitStatus.Requested, PermitStatus.Open, PermitEventType.PhoneReject, reason, ct: ct); + + // TRUCK_DISTRIBUTION_LOG bookkeeping + if (permit.Scrn is long ordId) + { + var closed = await phoneRepo.GetClosedDistributionAsync(permitId, ordId, ct); + if (closed is not null) + { + if (!isAbsence) + await phoneRepo.PostponeApprovedDistributionAsync(closed, permitId, ordId, blacklistId, + "تم تاجيل الارسالية من خلال نظام نافذ للعملاء علما بان هذه الارسالية تم الموافقة عليها من تطبيق نافذ مسبقا", ct); + else + await phoneRepo.MarkDistributionRevokedAsync(closed.Id, blacklistId, $"الإضافة على قائمة المنع بسبب {reason}", ct); + return PermitOperationResult.Ok("تمت العملية بنجاح.اضيفت الارسالية الى قائمة المنع", permitId, Data(blacklistId, expiry)); + } + } + if (!isAbsence) + await phoneRepo.MarkPendingDistributionAsync(permitId, blacklistId, reason, false, ct); + else + await phoneRepo.MarkPendingDistributionAsync(permitId, blacklistId, $"الإضافة على قائمة المنع بسبب {reason}", true, ct); + + return PermitOperationResult.Ok("تمت العملية بنجاح.اضيفت الارسالية الى قائمة المنع", permitId, Data(blacklistId, expiry)); + } + + private static IReadOnlyDictionary Data(long blId, DateTime expiry) => + new Dictionary { ["blacklistId"] = blId, ["expiryDate"] = expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture) }; + + // ------------------------------------------------------------------------------------------------ weights / feature flag + + public async Task SaveWeightsAsync(SaveWeightsRequest r, CancellationToken ct = default) + { + new SaveWeightsValidator().ValidateAndThrow(r); + var weightMsg = WeighbridgeRules.ValidateStoredWeights(r.EmptyWeight, r.GrossWeight); + if (weightMsg is not null) throw new BusinessException("WEIGHT_LENGTH", weightMsg); + + var permit = await repo.GetByPnAsync(r.Pn, ct) ?? throw new BusinessException("PN_INVALID", "رقم الارسالية غير موجود"); + await uow.ExecuteInTransactionAsync(async token => + { + var existing = await repo.GetStoredWeightsIdAsync(permit.Id, token); + await repo.UpsertStoredWeightsAsync(permit.Id, existing, r, user.UserId, token); + await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.AddWeights, + $"الوزن القائم: {r.GrossWeight} الوزن الفارغ: {r.EmptyWeight}", withLocation: false, ct: token); + return true; + }, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, permit.Id); + } + + public async Task LookupWeightsAsync(string pn, CancellationToken ct = default) => + await repo.GetStoredWeightsAsync(pn.Trim(), options.BadiyaScac, ct) + ?? throw new BusinessException("PN_INVALID", "الرجاء التأكد من رقم الارسالية"); + + public AbsenceFeatureDto GetAbsenceFeature() => new(AbsenceFeatureState.IsEnabled(options.AbsenceFeatureEnabled)); + + public async Task ToggleAbsenceFeatureAsync(CancellationToken ct = default) + { + var enabled = AbsenceFeatureState.Toggle(options.AbsenceFeatureEnabled); + var json = JsonSerializer.Serialize(new { ONOROFF = enabled, userid = user.UserId, userrolecode = user.RoleCode }); + await repo.LogActivationAsync("GN_ABSENCE_FEATURE", user.UserId, user.RoleCode, json, ct); + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, null, + new Dictionary { ["enabled"] = enabled }); + } + + // ------------------------------------------------------------------------------------------------ helpers + + private IReadOnlyList 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"), options.BadiyaScac); + + private void EnsureCompanyAccess(long? permitCompany) + { + if (user.IsCompany(options) && permitCompany != user.CompanyCodeNo()) + throw new ForbiddenException("PERMIT_FOREIGN_COMPANY", "لا تملك صلاحية على هذه الإرسالية"); + } + + private static string? Trim(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); + + private static TruckInfoDto ToDto(TruckInfoRow r) => new(r.Tn ?? string.Empty, r.ChasesNumber, r.Axials, PermitDates.Display(r.RegDate)); + + /// TENDERORDER filter = "dd/MM/yyyy,shift". + internal static DateTime? ParseTenderOrder(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + var first = value.Split(',')[0].Trim(); + return DateTime.TryParseExact(first, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var d) + ? d.Date : PermitDates.ParseLegacy(first); + } +} diff --git a/src/NTP.Application/Grains/Permits/PermitSupport.cs b/src/NTP.Application/Grains/Permits/PermitSupport.cs new file mode 100644 index 0000000..16842d5 --- /dev/null +++ b/src/NTP.Application/Grains/Permits/PermitSupport.cs @@ -0,0 +1,150 @@ +using NTP.Application.Abstractions; +using NTP.Domain.Grains.Permits; + +namespace NTP.Application.Grains.Permits; + +/// +/// Legacy role codes (session.userrolecode) that gate Grains permit operations. Legacy used per-action permissions +/// (application.objAuth.isActAuthorized(id, session.lstGID)); those ids are not in the repository, so the actions are +/// grouped by the role codes legacy code mentions (SU, GPO, GNSU, GNCO, GTO, GATEIN, GATEOUT, THRU). UNVERIFIED mapping. +/// +public static class GrainsRoles +{ + /// Back-office operators: distribution, phone confirmation, manual operations, queue creation. + public const string Operators = "SU,GPO,GNSU,GNCO,GTO"; + + /// Weighbridge / gate users plus operators. + public const string Weighbridge = "SU,GPO,GNSU,GNCO,GTO,GATEIN,GATEOUT,THRU"; + + /// ConvertToResd button: legacy checks role SU or GPO only. + public const string ConvertToResd = "SU,GPO"; + + /// Supervisors: configuration of destinations, activation of orders, absence feature. + public const string Supervisors = "SU,GPO,GNSU,GTO"; +} + +/// Helpers that replace legacy session.* lookups. +public static class PermitUserContext +{ + /// session.stkid = 62: a trucking company user (sees and changes only its own permits). + public static bool IsCompany(this ICurrentUser user, GrainsPermitsOptions options) => + user.StkId == options.CompanyStakeholderId; + + /// session.companyCodeNO = mid(CompanyCode, 4, 6) * 1; null when the user has no company code. + public static long? CompanyCodeNo(this ICurrentUser user) => ParseCompanyCodeNo(user.CompanyCode); + + public static long? ParseCompanyCodeNo(string? companyCode) + { + if (string.IsNullOrWhiteSpace(companyCode) || companyCode.Length < 4) return null; + var len = Math.Min(6, companyCode.Length - 3); + return long.TryParse(companyCode.AsSpan(3, len), out var v) ? v : null; + } + + /// session.locationid as a nullable string for EVENTS.LOCATIONID. + public static string? LocationText(this ICurrentUser user) => user.LocationId?.ToString(); +} + +/// Which action buttons the caller may use on a permit (createGnOrder.cfm / GNPermits grid rules). +public static class PermitActionRules +{ + public const string Submit = "submit"; + public const string Edit = "edit"; + public const string Accept = "accept"; + public const string Reject = "reject"; + public const string RevokeAccepted = "revokeAccepted"; + public const string ConvertToResd = "convertToResd"; + public const string PhoneAccept = "phoneAccept"; + public const string PhoneReject = "phoneReject"; + public const string CancelOrder = "cancelOrder"; + public const string RevokePermit = "revokePermit"; + public const string Reactivate = "reactivate"; + public const string Print = "print"; + public const string View = "view"; + + public static IReadOnlyList For(string? status, long? companyCode, bool isCompany, bool isOperator, bool isConvertRole, + bool isReactivator, long badiyaScac) + { + var a = new List { View }; + switch (status) + { + case PermitStatus.Requested: + a.Add(Submit); a.Add(Edit); + break; + case PermitStatus.Planned: + a.Add(Accept); a.Add(Reject); a.Add(Edit); + break; + case PermitStatus.Accepted: + case PermitStatus.Released: + a.Add(RevokeAccepted); a.Add(Print); + if (status == PermitStatus.Accepted && isConvertRole) a.Add(ConvertToResd); + break; + case PermitStatus.Closed: + a.Add(Print); + break; + } + + if (isOperator && status is PermitStatus.Requested or PermitStatus.Planned or PermitStatus.Accepted or PermitStatus.Released) + { + a.Add(PhoneAccept); a.Add(PhoneReject); + } + if (isOperator && status == PermitStatus.Released) a.Add(CancelOrder); + if (isOperator && status == PermitStatus.Open) a.Add(RevokePermit); + if (status == PermitStatus.Revoked && isReactivator && companyCode == badiyaScac) a.Add(Reactivate); + + if (isCompany) + { + // 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; + } +} + +/// Process-wide switch of the "absence" feature (legacy application.GNABSENCEFEATURE, in-memory). +public static class AbsenceFeatureState +{ + private static int _state = -1; + + public static bool IsEnabled(bool initial) => (Volatile.Read(ref _state) is var s && s >= 0) ? s == 1 : initial; + + public static bool Toggle(bool initial) + { + var next = !IsEnabled(initial); + Volatile.Write(ref _state, next ? 1 : 0); + return next; + } +} + +// --------------------------------------------------------------------------------------------------------------- +// Outbound integration gateways (configurable URLs; implementations live in Infrastructure) +// --------------------------------------------------------------------------------------------------------------- + +/// TCS petroleum permit web service (legacy application.PetWS): createPermit / getFopDetail. +public interface ITcsPermitGatewayService +{ + Task CreatePermitAsync(TcsPermitRequest request, CancellationToken ct = default); + Task GetFopDetailAsync(string fop, CancellationToken ct = default); +} + +/// Mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage). +public interface IMobileNotificationGatewayService +{ + Task SendAsync(string template, IReadOnlyDictionary payload, CancellationToken ct = default); +} + +/// Auto dialer / IVR (GrainsFactoryWeb.autoCallService2 / autoCallService). +public interface IAutoCallGatewayService +{ + /// POSTs {"TYPE":"TEST","FILE":base64} to the configured dialer URL; false when not reachable / not 200. + Task SendCallFileAsync(byte[] csv, CancellationToken ct = default); + + /// Calls the IVR web service (callAPI). + Task TriggerIvrAsync(CancellationToken ct = default); +} + +/// Reads new rows from the external weighbridge database (legacy datasource GrainsWeighbridge). +public interface IWeighbridgeSourceService +{ + bool IsConfigured { get; } + Task> ReadNewAsync(long locationId, DateTime? after, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Grains/Permits/PermitValidators.cs b/src/NTP.Application/Grains/Permits/PermitValidators.cs new file mode 100644 index 0000000..04e1e33 --- /dev/null +++ b/src/NTP.Application/Grains/Permits/PermitValidators.cs @@ -0,0 +1,210 @@ +using FluentValidation; +using NTP.Domain.Grains.Permits; + +namespace NTP.Application.Grains.Permits; + +/// Request validators ported from the Required/Float/Integer checks of the legacy pages (validateFields). +public sealed class SubmitOrderValidator : AbstractValidator +{ + public SubmitOrderValidator() + { + RuleFor(x => x.Tn).NotEmpty().MaximumLength(20).WithErrorCode("TN_REQUIRED"); + RuleFor(x => x.Trn).NotEmpty().Matches("^[0-9]+$").WithErrorCode("TRN_REQUIRED"); + RuleFor(x => x.Nnpn).NotEmpty().Matches("^[0-9]+$").WithErrorCode("NNPN_REQUIRED"); + RuleFor(x => x.Dln).NotEmpty().Matches("^[0-9]+$").WithErrorCode("DLN_REQUIRED"); + RuleFor(x => x.Name).NotEmpty().MaximumLength(150).WithErrorCode("NAME_REQUIRED"); + RuleFor(x => x.OpType).Must(o => o is "EXPT" or "IMPT").WithMessage("نوع العملية يجب أن يكون فارغ أو محمل") + .WithErrorCode("OPTYPE_INVALID"); + } +} + +public sealed class UpdateOrderValidator : AbstractValidator +{ + public UpdateOrderValidator() + { + RuleFor(x => x.Tn).NotEmpty().MaximumLength(20).WithErrorCode("TN_REQUIRED"); + RuleFor(x => x.Trn).NotEmpty().Matches("^[0-9]+$").WithErrorCode("TRN_REQUIRED"); + RuleFor(x => x.Nnpn).NotEmpty().Matches("^[0-9]+$").WithErrorCode("NNPN_REQUIRED"); + RuleFor(x => x.Dln).NotEmpty().Matches("^[0-9]+$").WithErrorCode("DLN_REQUIRED"); + RuleFor(x => x.Name).NotEmpty().MaximumLength(150).WithErrorCode("NAME_REQUIRED"); + } +} + +public sealed class ReasonValidator : AbstractValidator +{ + public ReasonValidator() + { + RuleFor(x => x.Reason).NotEmpty().MaximumLength(500).WithErrorCode("REASON_REQUIRED"); + } +} + +public sealed class PhoneRejectValidator : AbstractValidator +{ + public PhoneRejectValidator() + { + RuleFor(x => x.Reason).NotEmpty().Must(r => PhoneRejectRules.AllowedReasons.Contains(r.Trim())) + .WithMessage("سبب الرفض غير صحيح").WithErrorCode("REASON_INVALID"); + RuleFor(x => x.ExpiryDays).Must(d => PhoneRejectRules.AllowedExpiryDays.Contains(d)) + .WithMessage("عدد أيام التأجيل غير صحيح").WithErrorCode("EXPIRY_INVALID"); + } +} + +public sealed class ClosePermitValidator : AbstractValidator +{ + public ClosePermitValidator() + { + RuleFor(x => x.Pn).NotEmpty().Matches("^[0-9]{1,12}$").WithErrorCode("PN_INVALID"); + } +} + +public sealed class SaveWeightsValidator : AbstractValidator +{ + public SaveWeightsValidator() + { + RuleFor(x => x.Pn).NotEmpty().Matches("^[0-9]{1,12}$").WithErrorCode("PN_INVALID"); + RuleFor(x => x.EmptyWeight).NotEmpty().Matches("^[0-9]+$"); + RuleFor(x => x.GrossWeight).NotEmpty().Matches("^[0-9]+$"); + RuleFor(x => x.DocumentNumber).NotEmpty().Matches("^[0-9]{1,12}$"); + } +} + +public sealed class AddToQueueValidator : AbstractValidator +{ + public AddToQueueValidator() + { + RuleFor(x => x.Tn).NotEmpty().Matches("^[0-9]+$").WithMessage("رقم السيارة يجب أن يكون رقماً").WithErrorCode("TN_INVALID"); + RuleFor(x => x.Tt).Must(t => t is GrainsCargo.Bulk or GrainsCargo.Packed).WithErrorCode("TT_INVALID"); + } +} + +public sealed class ManualInputValidator : AbstractValidator +{ + public ManualInputValidator() + { + RuleFor(x => x.Pn).NotEmpty().Matches("^[0-9]{1,12}$").WithErrorCode("PN_INVALID"); + RuleFor(x => x.OrderId).GreaterThan(0); + RuleFor(x => x.OrderDate).NotEmpty(); + RuleFor(x => x.Ltw).GreaterThanOrEqualTo(0); + RuleFor(x => x.Lgw).GreaterThanOrEqualTo(0); + } +} + +public sealed class AssignByPnValidator : AbstractValidator +{ + public AssignByPnValidator() + { + RuleFor(x => x.Pn).NotEmpty().Matches("^[0-9]{1,10}$").WithErrorCode("PN_INVALID"); + RuleFor(x => x.DestId).GreaterThan(0); + RuleFor(x => x.ShipmentMode).GreaterThan(0); + } +} + +public sealed class WeighbridgeReadingValidator : AbstractValidator +{ + public WeighbridgeReadingValidator() + { + RuleFor(x => x.Tn).NotEmpty().Matches("^[0-9]+$").WithErrorCode("TN_INVALID"); + RuleFor(x => x.Weight).GreaterThan(0).WithErrorCode("WEIGHT_INVALID"); + } +} + +public sealed class WeighbridgeWeightsValidator : AbstractValidator +{ + public WeighbridgeWeightsValidator() + { + RuleFor(x => x.Tn).NotEmpty().Matches("^[0-9]+$").WithErrorCode("TN_INVALID"); + RuleFor(x => x.GrossWeight).GreaterThan(0); + RuleFor(x => x.TareWeight).GreaterThan(0); + } +} + +public sealed class ManualWeighbridgeValidator : AbstractValidator +{ + public ManualWeighbridgeValidator() + { + RuleFor(x => x.Tn).NotEmpty().Matches("^[0-9]+$").WithErrorCode("TN_INVALID"); + RuleFor(x => x.LocationId).GreaterThan(0); + RuleFor(x => x.WeightIn).GreaterThan(0); + RuleFor(x => x.WeightOut).GreaterThan(0); + } +} + +public sealed class WeighbridgeEventValidator : AbstractValidator +{ + public WeighbridgeEventValidator() + { + RuleFor(x => x.Tn).NotEmpty().Matches("^[0-9]+$"); + RuleFor(x => x.Weight).GreaterThan(0); + RuleFor(x => x.LocationId).GreaterThan(0); + RuleFor(x => x.TrxType).Must(t => t is WeighbridgeRules.Entry or WeighbridgeRules.Exit); + RuleFor(x => x.EventDate).NotEmpty().Matches(@"^\d{8} ?\d{6}$").WithMessage("EventDate must be yyyyMMdd HHmmss"); + } +} + +public sealed class DistributeValidator : AbstractValidator +{ + public DistributeValidator() + { + RuleFor(x => x.Category).Must(c => DistributionCategory.Parse(c) is not null) + .WithMessage("نوع التوزيع غير صحيح").WithErrorCode("CATEGORY_INVALID"); + } +} + +public sealed class OpenPermitWithDestinationValidator : AbstractValidator +{ + public OpenPermitWithDestinationValidator() + { + RuleFor(x => x.Pn).NotEmpty().Matches("^[0-9]{1,10}$").WithErrorCode("PN_INVALID"); + RuleFor(x => x.Locations).GreaterThan(0); + RuleFor(x => x.OrderDate).NotEmpty(); + } +} + +public sealed class CompanyOpenPermitsValidator : AbstractValidator +{ + public CompanyOpenPermitsValidator() + { + RuleFor(x => x.Count).InclusiveBetween(1, 5000); + } +} + +public sealed class CreateTcsPermitValidator : AbstractValidator +{ + public CreateTcsPermitValidator() + { + RuleFor(x => x.Tn).NotEmpty().Matches("^[0-9]{1,8}$"); + RuleFor(x => x.TrnAt).NotEmpty(); + RuleFor(x => x.Trn).NotEmpty().Matches("^[0-9]{1,7}$"); + RuleFor(x => x.Tt).NotEmpty(); + RuleFor(x => x.Nnpn).NotEmpty().Matches("^[0-9]{1,12}$"); + RuleFor(x => x.Drvr).NotEmpty().MaximumLength(150); + RuleFor(x => x.Dln).NotEmpty().Matches("^[0-9]{1,8}$"); + RuleFor(x => x.Cat).NotEmpty().Matches("^[0-9]$"); + RuleFor(x => x.Nat).NotEmpty(); + RuleFor(x => x.ShipmentMode).NotEmpty(); + RuleFor(x => x.InbondTypeCode).NotEmpty(); + RuleFor(x => x.Firms).NotEmpty(); + RuleFor(x => x.OriginAddressId).GreaterThan(0); + RuleFor(x => x.DestinationAddressId).GreaterThan(0); + RuleFor(x => x.RoutingTemplateId).GreaterThan(0); + RuleFor(x => x.Asrn).NotEmpty().Matches("^[0-9]{1,12}$"); + RuleFor(x => x.Can).Matches("^[0-9]{1,2}$").When(x => !string.IsNullOrEmpty(x.Can)); + RuleFor(x => x.Fop).NotEmpty().When(x => x.Routing == -1).WithMessage("يجب إدخال رقم تصريح التفريغ"); + } +} + +/// Date helpers: legacy screens send dates as yyyy/mm/dd, dd/mm/yyyy or dd\mm\yyyy. +public static class PermitDates +{ + private static readonly string[] Formats = + ["yyyy-MM-dd", "yyyy/MM/dd", "dd/MM/yyyy", "dd\\MM\\yyyy", "yyyyMMdd", "yyyy-MM-ddTHH:mm:ss"]; + + public static DateTime? ParseLegacy(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + return DateTime.TryParseExact(value.Trim().Replace('\\', '/'), Formats, System.Globalization.CultureInfo.InvariantCulture, + System.Globalization.DateTimeStyles.None, out var d) ? d.Date : null; + } + + public static string? Display(DateTime? d) => d?.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); +} diff --git a/src/NTP.Application/Grains/Permits/QueueService.cs b/src/NTP.Application/Grains/Permits/QueueService.cs new file mode 100644 index 0000000..fdc894c --- /dev/null +++ b/src/NTP.Application/Grains/Permits/QueueService.cs @@ -0,0 +1,288 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Permits; + +namespace NTP.Application.Grains.Permits; + +public interface IQueueService +{ + Task> ListAsync(QueueSearchQuery query, PageRequest page, CancellationToken ct = default); + Task AddToQueueAsync(AddToQueueRequest request, CancellationToken ct = default); + + /// AddToQueue called from Accept (inside the caller's transaction); returns the legacy message. + Task AddToQueueInternalAsync(string tn, string tt, string actor, bool checkStatuses, CancellationToken ct = default); + + /// ws.cfc createPermitRecord: creates an OPEN (or other initial status) permit record / turn. + Task CreatePermitRecordAsync(string? tn, long? scac, string nextStatus, string tt, bool checkStatuses, + string actor, CancellationToken ct = default); + + Task GetTrailerNumberAsync(string tn, CancellationToken ct = default); + Task CheckTrucksAsync(long tn, long scac, CancellationToken ct = default); + Task SeedPermitsAsync(SeedPermitsRequest request, CancellationToken ct = default); + + /// jobs/parseGrainsPermits.cfm: tops every company's OPEN permits up to its queue share. Returns created count. + Task FillCompanySharesAsync(CancellationToken ct = default); + + // ---- TCS permit (createPermit.cfm) + Task GetTcsFormDataAsync(long permitId, CancellationToken ct = default); + Task> GetRoutingTemplatesAsync(long origin, long destination, string shipmentMode, string firms, + CancellationToken ct = default); + Task> GetOriginAddressesAsync(long routing, CancellationToken ct = default); + Task> GetPhRoutesAsync(CancellationToken ct = default); + Task GetClearingAgentNameAsync(long can, CancellationToken ct = default); + Task GetFopDetailAsync(string fop, CancellationToken ct = default); + Task CreateTcsPermitAsync(long permitId, CreateTcsPermitRequest request, CancellationToken ct = default); +} + +public sealed class QueueService( + IQueueRepository repo, + IPermitRepository permits, + ITcsPermitGatewayService tcs, + IEventLogger events, + IUnitOfWork uow, + ICurrentUser user, + IGrainsPermitsSettingsService settings) : IQueueService +{ + private GrainsPermitsOptions options => settings.Value; + + public Task> ListAsync(QueueSearchQuery q, PageRequest page, CancellationToken ct = default) => + repo.ListAsync(new QueueSearchQuery(Trim(q.Tn), Trim(q.Pn)), page, ct); + + // ------------------------------------------------------------------------------------------------ AddToQueue / createPermitRecord + + public async Task AddToQueueAsync(AddToQueueRequest r, CancellationToken ct = default) + { + new AddToQueueValidator().ValidateAndThrow(r); + var message = await uow.ExecuteInTransactionAsync(token => + AddToQueueCoreAsync(r.Tn.Trim(), r.Tt, user.UserId, r.CheckStatuses, token), ct); + return message.Success + ? PermitOperationResult.Ok(message.Message, message.PermitId) + : PermitOperationResult.Fail(message.Code ?? "QUEUE_FAILED", message.Message); + } + + public async Task AddToQueueInternalAsync(string tn, string tt, string actor, bool checkStatuses, CancellationToken ct = default) => + (await AddToQueueCoreAsync(tn.Trim(), tt, actor, checkStatuses, ct)).Message; + + private async Task AddToQueueCoreAsync(string tn, string tt, string actor, bool checkStatuses, CancellationToken ct) + { + var scac = await repo.GetActiveTruckScacAsync(tn, ct); + if (checkStatuses) + { + // legacy creates both a BULK and a PCKD turn and reports the last result + await CreatePermitRecordAsync(tn, scac, PermitStatus.Open, GrainsCargo.Bulk, true, actor, ct); + return await CreatePermitRecordAsync(tn, scac, PermitStatus.Open, GrainsCargo.Packed, true, actor, ct); + } + return await CreatePermitRecordAsync(tn, scac, PermitStatus.Open, tt, false, actor, ct); + } + + public async Task CreatePermitRecordAsync(string? tn, long? scac, string nextStatus, string tt, bool checkStatuses, + string actor, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(nextStatus)) nextStatus = PermitStatus.Open; + if (string.IsNullOrWhiteSpace(tn) && scac is null) + return PermitOperationResult.Fail("INVALID_ARGUMENTS", "Invalid arguments, TN or SCAC is required"); + + if (!string.IsNullOrWhiteSpace(tn)) + { + var truckScac = await repo.GetActiveTruckScacAsync(tn, ct); + if (truckScac is null) + return PermitOperationResult.Fail("TRUCK_NOT_REGISTERED", $"القاطرة رقم: {tn} غير مسجلة "); + if (await repo.HasActivePermitAsync(tn, tt, checkStatuses, ct)) + return PermitOperationResult.Fail("TRUCK_HAS_TURN", $"القاطره رقم: {tn} ، لها دور فعّال "); + } + + var company = scac ?? 0; + var owner = company == options.BadiyaScac; + var seq = await repo.NextTrackingSequenceAsync(owner, ct); + long? tripCounter = owner ? await repo.NextTripCounterAsync(tt, options.BadiyaScac, ct) : null; + var tenderCount = await repo.GetTenderCountAsync(ct); + var pn = PermitNumberGenerator.Generate(tt, seq, company, options.BadiyaScac, tenderCount); + + var id = await repo.InsertPermitAsync(pn, string.IsNullOrWhiteSpace(tn) ? null : tn.Trim(), company, nextStatus, tt, tripCounter, ct); + await events.LogAsAsync("SYSTEM", null, id, "", nextStatus, PermitEventType.Override, ct: ct); + return PermitOperationResult.Ok("تمت العملية بنجاح ورقم الإرسالية هو : " + pn, id, + new Dictionary { ["pn"] = pn }); + } + + public Task GetTrailerNumberAsync(string tn, CancellationToken ct = default) => + repo.GetTrailerNumberAsync(tn.Trim(), options.AllowedStatuses, ct); + + public async Task CheckTrucksAsync(long tn, long scac, CancellationToken ct = default) + { + // checkTrucks: every truck of the fleet must be used once before any can be registered again. + var fleet = await repo.CountFleetAsync(scac, ct); + var turns = await repo.CountActiveValidationsAsync(scac, ct) + 1; + if (fleet >= turns) + { + if (await repo.ValidationExistsAsync(scac, tn, ct)) + return PermitOperationResult.Fail("TRUCK_DUPLICATE", "هذه الشاحنة مكررة، لا تستطيع تسجيلها مرتين"); + await uow.ExecuteInTransactionAsync(async token => + { + await repo.InsertValidationAsync(scac, tn, user.UserId, token); + if (fleet == turns) await repo.ClearValidationsAsync(scac, token); + return true; + }, ct); + return PermitOperationResult.Ok("done"); + } + return PermitOperationResult.Ok(PermitOperationResult.DefaultOk); + } + + public async Task SeedPermitsAsync(SeedPermitsRequest request, CancellationToken ct = default) + { + if (request.Items.Count == 0) throw new ValidationException("لا توجد بيانات"); + var created = 0; + foreach (var item in request.Items) + { + if (item.Count is < 1 or > 1000) throw new ValidationException("العدد يجب أن يكون بين 1 و 1000"); + if (item.Tt is not (GrainsCargo.Bulk or GrainsCargo.Packed)) throw new ValidationException("نمط الحمولة غير صحيح"); + for (var i = 0; i < item.Count; i++) + { + var res = await uow.ExecuteInTransactionAsync(token => + CreatePermitRecordAsync(null, item.Scac, item.NextStatus, item.Tt, false, "SYSTEM", token), ct); + if (res.Success) created++; + } + } + return PermitOperationResult.Ok($"تم إنشاء {created} إرسالية"); + } + + public async Task FillCompanySharesAsync(CancellationToken ct = default) + { + var created = 0; + foreach (var tt in new[] { GrainsCargo.Packed, GrainsCargo.Bulk }) + { + var shares = await repo.GetCompanyQueueSharesAsync(tt, options.BadiyaScac, ct); + foreach (var s in shares) + { + var open = await repo.CountOpenPermitsAsync(s.Scac, tt, ct); + for (var i = 0; i < s.CompanyShare - open; i++) + { + var res = await uow.ExecuteInTransactionAsync(token => + CreatePermitRecordAsync(null, s.Scac, PermitStatus.Open, tt, false, "SYSTEM", token), ct); + if (res.Success) created++; + } + } + } + return created; + } + + // ------------------------------------------------------------------------------------------------ TCS permit + + public Task GetTcsFormDataAsync(long permitId, CancellationToken ct = default) => + repo.GetFormDataAsync(permitId, user.Domain, ct); + + public Task> GetRoutingTemplatesAsync(long origin, long destination, string shipmentMode, string firms, + CancellationToken ct = default) => + repo.GetRoutingTemplatesAsync(origin, destination, shipmentMode, firms, user.Domain, ct); + + public Task> GetOriginAddressesAsync(long routing, CancellationToken ct = default) => + repo.GetOriginAddressesAsync(routing, user.Domain, ct); + + public Task> GetPhRoutesAsync(CancellationToken ct = default) => repo.GetPhRoutesAsync(ct); + + public Task GetClearingAgentNameAsync(long can, CancellationToken ct = default) => repo.GetClearingAgentNameAsync(can, ct); + + public Task GetFopDetailAsync(string fop, CancellationToken ct = default) => tcs.GetFopDetailAsync(fop.Trim(), ct); + + public async Task CreateTcsPermitAsync(long permitId, CreateTcsPermitRequest r, CancellationToken ct = default) + { + new CreateTcsPermitValidator().ValidateAndThrow(r); + var permit = await permits.GetAsync(permitId, ct) ?? throw new NotFoundException("Permit", permitId); + if (permit.ShipmentStatusCode != PermitStatus.Queued) + throw new BusinessException("PERMIT_BAD_STATE", PermitAssignmentRules.BadStatus); + + var dest = await repo.PickRandomQuotaDestinationAsync(ct); + if (dest is null || dest.DestId == 0) + return PermitOperationResult.Fail("NO_DESTINATION", "لا يوجد مواقع متوفر للتحميل"); + + var canName = string.IsNullOrWhiteSpace(r.Can) ? string.Empty + : await repo.GetClearingAgentNameAsync(long.Parse(r.Can), ct) ?? string.Empty; + + TcsPermitResult result; + if (r.Routing == 0) + { + result = await tcs.CreatePermitAsync(ToTcs(r, r.Firms, r.InbondTypeCode, r.RoutingTemplateId, r.ShipmentMode, r.OriginAddressId, + r.DestinationAddressId, r.Asrn, null, null, null, canName, r.Can, r.TrnAt), ct); + } + else if (r.Routing == -1) + { + result = await tcs.CreatePermitAsync(ToTcs(r, r.Firms, r.InbondTypeCode, r.RoutingTemplateId, r.ShipmentMode, r.OriginAddressId, + r.DestinationAddressId, r.Asrn, r.Fop, null, null, canName, r.Can, r.TrnAt), ct); + } + else + { + // Two-move permit: first create the petroleum/PH leg (shipment mode PHPT, exporter, seal 1, TST 1)... + var route = await repo.GetPhRouteAsync(r.Routing, ct) ?? throw new NotFoundException("Routing", r.Routing); + var first = await tcs.CreatePermitAsync(ToTcs(r, route.DefaultLane ?? string.Empty, "EXPT", r.Routing, "PHPT", + route.OrgAddressId ?? 0, route.DestAddressId ?? 0, string.Empty, null, "1", "1", "المصرح", "1", r.TrnAt), ct); + if (!first.Success) + return PermitOperationResult.Fail("TCS_FIRST_LEG_FAILED", first.Error); + var fop = first.PermitNumber; + // ...then the second permit referencing the first (FOP). + result = await tcs.CreatePermitAsync(ToTcs(r, r.Firms, r.InbondTypeCode, r.RoutingTemplateId, r.ShipmentMode, r.OriginAddressId, + r.DestinationAddressId, r.Asrn, fop, null, null, canName, r.Can, r.TrnAt), ct); + if (!result.Success) + return PermitOperationResult.Fail("TCS_SECOND_LEG_FAILED", + $"خطأ في إنشاء تصريح الحركة الثانية - {result.Error} - تم إنشاء تصريح حركة أولى رقم {fop}"); + } + + if (!result.Success) + return PermitOperationResult.Fail("TCS_FAILED", result.Error); + + var company = permit.CompanyCode ?? user.CompanyCodeNo() ?? 0; + await uow.ExecuteInTransactionAsync(async token => + { + await repo.UpdateTcsPermitAsync(permitId, new TcsPermitUpdate + { + Pn = result.PermitNumber ?? string.Empty, + StatusCode = result.StatusCode ?? string.Empty, + FinalDestination = dest.DestId, + CompanyCode = company, + UserId = user.UserId, + Domain = user.Domain, + Form = r + }, token); + + // legacy passes the signed-in user's role code as the event type here (kept as is) + await events.LogAsync(user, permitId, PermitStatus.Queued, result.StatusCode, user.RoleCode, ct: token); + + var created = await repo.GetPermitCreationDateAsync(permitId, token); + await InsertPermitStopsAsync(permitId, r.RoutingTemplateId, created, user.Domain, token); + await repo.IncrementDoneQuotaAsync(dest.DestId, token); + return true; + }, ct); + + return PermitOperationResult.Ok( + $"تمت العملية بنجاح - رقم الإرسالية: {result.PermitNumber} - الوجهة: {dest.DestName}", permitId, + new Dictionary { ["pn"] = result.PermitNumber, ["destination"] = dest.DestName }); + } + + /// insertPermitStop: one PERMITSTOPS row per leg of the routing template. + private async Task InsertPermitStopsAsync(long permitId, long routeId, DateTime? departDate, string domain, CancellationToken ct) + { + var legs = (await repo.GetRoutingLegsAsync(routeId, ct)).OrderBy(l => l.SortOrder).ToList(); + long NextLeg(long sort) => legs.FirstOrDefault(l => l.SortOrder == sort + 1)?.LocationId ?? 0; + + foreach (var leg in legs) + { + var next = NextLeg(leg.SortOrder); + if (leg.SortOrder == 1) + { + await repo.InsertPermitStopAsync(permitId, domain, null, leg.LocationId, leg.SortOrder, departDate, ct); + await repo.InsertPermitStopAsync(permitId, domain, leg.LocationId, next, leg.SortOrder + 1, null, ct); + } + else if (next != 0) + { + await repo.InsertPermitStopAsync(permitId, domain, leg.LocationId, next, leg.SortOrder + 1, null, ct); + } + else break; + } + } + + private TcsPermitRequest ToTcs(CreateTcsPermitRequest r, string firms, string inbond, long routingTemplateId, string mode, long origin, + long dest, string asrn, string? fop, string? sealN, string? tst, string canName, string? can, string trnAt) => + new(firms, inbond, routingTemplateId, mode, origin, dest, asrn, fop, sealN, tst, canName, can, r.Tn, r.Trn, trnAt, r.Tt, r.Nnpn, r.Nat, + r.Cat, r.Dln, r.Drvr, user.UserId, user.CompanyName); + + private static string? Trim(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); +} diff --git a/src/NTP.Application/Grains/Permits/WeighbridgeService.cs b/src/NTP.Application/Grains/Permits/WeighbridgeService.cs new file mode 100644 index 0000000..e7e24d8 --- /dev/null +++ b/src/NTP.Application/Grains/Permits/WeighbridgeService.cs @@ -0,0 +1,309 @@ +using System.Globalization; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Application.Grains.Reports; +using NTP.Domain.Grains.Permits; + +namespace NTP.Application.Grains.Permits; + +public interface IPrintRepository +{ + Task GetAcceptPrintAsync(long permitId, CancellationToken ct = default); + Task GetPrintHeaderAsync(long permitId, bool withLocations, CancellationToken ct = default); + Task> GetLatestWeightEventsAsync(long permitId, CancellationToken ct = default); + Task GetLatestEventWithLocationAsync(long permitId, string eventType, CancellationToken ct = default); + Task GetDetailsAsync(long permitId, CancellationToken ct = default); + Task GetCompanyCodeAsync(long permitId, CancellationToken ct = default); +} + +public interface IWeighbridgeService +{ + /// EN_WeightBridge: first weighing at the entry booth (LNW 0, LTW, LGW) followed by an automatic destination assignment. + Task EnterAsync(WeighbridgeReadingRequest request, CancellationToken ct = default); + + /// EX_WeightBridge: second weighing (DNW = weight - last LTW, DTW, DGW). + Task ExitAsync(WeighbridgeReadingRequest request, CancellationToken ct = default); + + /// WeightBridge.cfm / grains.addWeightBridgeEvent: manual entry of both weights through the integration rules (EN then EX). + Task ManualAsync(ManualWeighbridgeRequest request, CancellationToken ct = default); + + /// loadingWeightBridge.cfm (ws.addLoadingWeightEvent) / dischargeWeightBridge.cfm (ws.addDischargeWeightEvent). + Task LoadingWeightsAsync(WeighbridgeWeightsRequest request, CancellationToken ct = default); + Task DischargeWeightsAsync(WeighbridgeWeightsRequest request, CancellationToken ct = default); + + Task GetTruckPermitAsync(string tn, string status, CancellationToken ct = default); + Task GetTruckWaybridgeEventAsync(string tn, CancellationToken ct = default); + Task> GetLocationTruckCountsAsync(CancellationToken ct = default); + + /// jobs/getWeighbridgeEvents.cfm (aqaba=false) and getAqabaWeighbridgeEvents.cfm (aqaba=true). Returns processed raw rows. + Task SyncAsync(bool aqaba, CancellationToken ct = default); + + // printing + Task GetAcceptPrintAsync(long permitId, CancellationToken ct = default); + Task GetPrintInAsync(long permitId, CancellationToken ct = default); + Task GetPrintOutAsync(long permitId, CancellationToken ct = default); + Task GetPermitDetailsAsync(long permitId, CancellationToken ct = default); +} + +/// Weighbridge operations, print data and the weighbridge-sync jobs of the Grains permits slice. +public sealed class WeighbridgeService( + IWeighbridgeRepository repo, + IPrintRepository printRepo, + IPermitRepository permits, + IDestinationRepository destinationRepo, + IDestinationService destinations, + IWsService ws, + IWeighbridgeSourceService source, + IEventLogger events, + IUnitOfWork uow, + ICurrentUser user, + IGrainsPermitsSettingsService settings) : IWeighbridgeService +{ + private GrainsPermitsOptions options => settings.Value; + + private static readonly long[] MainLocations = [215, 220, 225]; + private const long AqabaLocation = 205; + + // ------------------------------------------------------------------------------------------------ EN / EX + + public async Task EnterAsync(WeighbridgeReadingRequest r, CancellationToken ct = default) + { + var permit = await repo.GetPermitByTruckAndStatusAsync(r.Tn.Trim(), PermitStatus.Released, ct) + ?? throw new BusinessException("WRONG_STATUS", WeighbridgeDecision.WrongStatus); + + await uow.ExecuteInTransactionAsync(async token => + { + var w = r.Weight.ToString(CultureInfo.InvariantCulture); + await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.LoadingNet, weight: "0", ct: token); + await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.LoadingTare, weight: w, ct: token); + await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.LoadingGross, weight: w, ct: token); + return true; + }, ct); + + var assigned = await destinations.AssignDestinationAsync(r.Tn.Trim(), user.LocationId ?? 0, user.UserId, ct); + return new WeighbridgeResult + { + Success = assigned.Success, ErrorCode = assigned.Success ? "0" : "1", Message = assigned.Message, PermitId = permit.Id + }; + } + + public async Task ExitAsync(WeighbridgeReadingRequest r, CancellationToken ct = default) + { + var permit = await repo.GetPermitByTruckAndStatusAsync(r.Tn.Trim(), PermitStatus.Released, ct) + ?? throw new BusinessException("WRONG_STATUS", WeighbridgeDecision.WrongStatus); + var tare = await repo.GetLatestLoadingTareAsync(permit.Id, ct); + if (tare is null) + return new WeighbridgeResult { Success = false, ErrorCode = "1", Message = "يجب توزين الفارغ قبل التحميل", PermitId = permit.Id }; + + await uow.ExecuteInTransactionAsync(async token => + { + var diff = r.Weight - tare.Value; + await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.DischargeNet, + weight: diff.ToString(CultureInfo.InvariantCulture), ct: token); + await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.DischargeTare, + weight: r.Weight.ToString(CultureInfo.InvariantCulture), ct: token); + await events.LogAsync(user, permit.Id, permit.ShipmentStatusCode, permit.ShipmentStatusCode, PermitEventType.DischargeGross, + weight: tare.Value.ToString(CultureInfo.InvariantCulture), ct: token); + return true; + }, ct); + return new WeighbridgeResult { Success = true, ErrorCode = "0", Message = PermitOperationResult.DefaultOk, PermitId = permit.Id }; + } + + public async Task ManualAsync(ManualWeighbridgeRequest r, CancellationToken ct = default) + { + var msg = WeighbridgeRules.ValidateManualWeights(r.WeightIn, r.WeightOut); + if (msg is not null) throw new BusinessException("WEIGHT_RANGE", msg); + + var stamp = DateTime.Now.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture); + var userId = "W" + r.LocationId.ToString(CultureInfo.InvariantCulture); + var tn = r.Tn.Trim(); + var en = await ws.AddWeightBridgeEventAsync(new Reports.WeighbridgeEventRequest(tn, r.WeightIn.ToString(CultureInfo.InvariantCulture), r.LocationId, stamp, "EN", userId), ct); + var ex = await ws.AddWeightBridgeEventAsync(new Reports.WeighbridgeEventRequest(tn, r.WeightOut.ToString(CultureInfo.InvariantCulture), r.LocationId, stamp, "EX", userId), ct); + var ok = en.ErrorCode == WbCodes.Ok && ex.ErrorCode == WbCodes.Ok; + var text = $"الوزن الأول: {en.Msg} الوزن الثاني {ex.Msg}"; + return ok + ? PermitOperationResult.Ok(text, null, new Dictionary { ["en"] = en.Msg, ["ex"] = ex.Msg }) + : PermitOperationResult.Fail("WEIGHBRIDGE_REJECTED", text); + } + + public Task LoadingWeightsAsync(WeighbridgeWeightsRequest r, CancellationToken ct = default) => + WeightsAsync(r, PermitStatus.Released, loading: true, ct); + + public Task DischargeWeightsAsync(WeighbridgeWeightsRequest r, CancellationToken ct = default) => + WeightsAsync(r, PermitStatus.ArrivedControl, loading: false, ct); + + private async Task WeightsAsync(WeighbridgeWeightsRequest r, string status, bool loading, CancellationToken ct) + { + var msg = WeighbridgeRules.ValidateGrossTare(r.GrossWeight, r.TareWeight); + if (msg is not null) throw new BusinessException("WEIGHT_GROSS_LT_TARE", msg); + var permit = await repo.GetPermitByTruckAndStatusAsync(r.Tn.Trim(), status, ct) + ?? throw new BusinessException("WRONG_STATUS", WeighbridgeDecision.WrongStatus); + + var req = new LoadingWeightRequest(permit.Id, user.UserId, user.LocationText() ?? string.Empty, + r.TareWeight.ToString(CultureInfo.InvariantCulture), r.GrossWeight.ToString(CultureInfo.InvariantCulture), + (r.GrossWeight - r.TareWeight).ToString(CultureInfo.InvariantCulture)); + var res = loading ? await ws.AddLoadingWeightEventAsync(req, user.UserId, ct) : await ws.AddDischargeWeightEventAsync(req, user.UserId, ct); + return res.Success ? PermitOperationResult.Ok(res.Message, permit.Id) : PermitOperationResult.Fail(res.Code, res.Message, permit.Id); + } + + public Task GetTruckPermitAsync(string tn, string status, CancellationToken ct = default) => + repo.GetPermitByTruckAndStatusAsync(tn.Trim(), status, ct); + + public async Task GetTruckWaybridgeEventAsync(string tn, CancellationToken ct = default) + { + var type = user.LocationId is long loc ? await repo.GetLocationTypeAsync(loc, user.Domain, ct) : null; + return await repo.GetWaybridgeEventAsync(tn.Trim(), type, ct); + } + + public Task> GetLocationTruckCountsAsync(CancellationToken ct = default) => + repo.GetLocationTruckCountsAsync(ct); + + // ------------------------------------------------------------------------------------------------ job + + public async Task SyncAsync(bool aqaba, CancellationToken ct = default) + { + if (source.IsConfigured) + { + long[] locations = aqaba ? [AqabaLocation] : MainLocations; + var last = await repo.GetLastRawTimesAsync(locations, ct); + foreach (var loc in locations) + { + last.TryGetValue(loc, out var after); + var rows = await source.ReadNewAsync(loc, after, ct); + foreach (var row in rows) + { + var digits = new string((row.CargoTruckNo ?? string.Empty).Where(char.IsDigit).ToArray()); + if (digits.Length == 0) continue; + if (long.TryParse(digits, out var n) && n <= 99999) digits = "60" + digits; + if (!aqaba && row.CargoWeightNet > 99999) continue; + row.LocationId = loc; + await repo.InsertRawRowAsync(row, digits, ct); + } + } + } + + var processed = 0; + foreach (var raw in await repo.GetUnprocessedRawRowsAsync(aqaba, ct)) + { + try + { + var ok = await uow.ExecuteInTransactionAsync(token => ProcessRawAsync(raw, aqaba, token), ct); + if (ok) processed++; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // legacy logged and continued with the next raw row + } + } + return processed; + } + + private async Task ProcessRawAsync(WeighbridgeRawRow raw, bool aqaba, CancellationToken ct) + { + var tn = raw.CargoTruckNo ?? string.Empty; + string[] statuses = aqaba ? [PermitStatus.ArrivedControl, PermitStatus.Released] + : [PermitStatus.ArrivedControl, PermitStatus.ClearedPreliminary, "ACTWT"]; + var permit = await repo.FindPermitForRawAsync(tn, statuses, ct); + if (permit is null) + { + string[] excluded = ["DGW", "DTW"]; + permit = await repo.FindPermitByAssignedDestinationAsync(tn, raw.GinTime, GrainsCargo.Bulk, excluded, ct); + if (permit is null && aqaba) + permit = await repo.FindPermitByAssignedDestinationAsync(tn, raw.GinTime, GrainsCargo.Packed, excluded, ct); + } + if (permit is null) + { + await repo.MarkRawRowAsync(raw.RowId, 0, ct); + return false; + } + + await repo.MarkRawRowAsync(raw.RowId, permit.Id, ct); + var doneBy = "W" + raw.LocationId.ToString(CultureInfo.InvariantCulture); + var status = permit.ShipmentStatusCode; + DateTime Stamp(string s) => DateTime.ParseExact(s, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); + + WeighbridgeEventInsert Ev(string type, string when, string? curr, decimal weight) => new() + { + PermitId = permit.Id, EventDate = Stamp(when), EventType = type, PrevStatus = status, CurrentStatus = curr, DoneBy = doneBy, + LocationId = raw.LocationId, UpdatedType = "WINT", Weight = weight + }; + + if (aqaba) + { + await repo.InsertEventAsync(Ev(PermitEventType.LoadingGross, raw.GoutTime, status, raw.CargoWeightOut), ct); + await repo.InsertEventAsync(Ev(PermitEventType.LoadingTare, raw.GinTime, PermitStatus.ArrivedControl, raw.CargoWeightIn), ct); + if (status != PermitStatus.Closed) await repo.SetPermitStatusAsync(permit.Id, PermitStatus.ArrivedControl, ct); + } + else + { + await repo.InsertEventAsync(Ev(PermitEventType.DischargeGross, raw.GinTime, status, raw.CargoWeightIn), ct); + await repo.InsertEventAsync(Ev(PermitEventType.DischargeTare, raw.GoutTime, PermitStatus.Closed, raw.CargoWeightOut), ct); + await repo.SetPermitStatusAsync(permit.Id, PermitStatus.Closed, ct); + } + return true; + } + + // ------------------------------------------------------------------------------------------------ printing + + private async Task EnsureAccessAsync(long permitId, CancellationToken ct) + { + var company = await printRepo.GetCompanyCodeAsync(permitId, ct) ?? throw new NotFoundException("Permit", permitId); + if (user.IsCompany(options) && company != user.CompanyCodeNo()) + throw new ForbiddenException("PERMIT_FOREIGN_COMPANY", "لا تملك صلاحية على هذه الإرسالية"); + } + + public async Task GetAcceptPrintAsync(long permitId, CancellationToken ct = default) + { + await EnsureAccessAsync(permitId, ct); + var dto = await printRepo.GetAcceptPrintAsync(permitId, ct) ?? throw new NotFoundException("Permit", permitId); + if (dto.Scrn is long scrn) + { + var d = await destinationRepo.GetOrderDetailsAsync(scrn, ct); + dto.Location = d?.Location; + // legacy prints a bare id for locations it has no caption for; show the LOCATIONS name instead + if (!string.IsNullOrEmpty(dto.Location) && dto.Location.All(char.IsDigit)) + dto.Location = await destinationRepo.GetGrainsLocationNameAsync(dto.Location, ct) ?? dto.Location; + } + dto.PrintedAt = DateTime.Now.ToString("dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture); + await events.LogAsync(user, permitId, dto.ShipmentStatusCode, dto.ShipmentStatusCode, PermitEventType.Print, withLocation: false, ct: ct); + return dto; + } + + public async Task GetPrintInAsync(long permitId, CancellationToken ct = default) + { + await EnsureAccessAsync(permitId, ct); + var header = await printRepo.GetPrintHeaderAsync(permitId, true, ct) ?? throw new NotFoundException("Permit", permitId); + var evs = await printRepo.GetLatestWeightEventsAsync(permitId, ct); + decimal W(string t) => evs.FirstOrDefault(e => e.EventType == t)?.Weight ?? 0; + var b = WeightBreakdown.Compute(W("LTW"), W("LGW"), W("DTW"), W("DGW")); + return new PrintInDto + { + Header = header, LoadingTare = W("LTW"), LoadingGross = W("LGW"), DischargeTare = W("DTW"), DischargeGross = W("DGW"), + Loading = new WeightFigures { Net = b.LoadingNet, Ton = b.LoadingTon, Kilo = b.LoadingKilo }, + Discharge = new WeightFigures { Net = b.DischargeNet, Ton = b.DischargeTon, Kilo = b.DischargeKilo }, + TonDifference = b.TonDifference, KiloDifference = b.KiloDifference, Sign = b.Sign, + LoadingLocation = evs.FirstOrDefault(e => e.EventType == "LTW")?.LocationName, + DischargeLocation = evs.FirstOrDefault(e => e.EventType == "DGW")?.LocationName, + DoneBy = evs.FirstOrDefault(e => e.EventType == "DGW")?.DoneBy ?? evs.FirstOrDefault()?.DoneBy + }; + } + + public async Task GetPrintOutAsync(long permitId, CancellationToken ct = default) + { + await EnsureAccessAsync(permitId, ct); + var header = await printRepo.GetPrintHeaderAsync(permitId, false, ct) ?? throw new NotFoundException("Permit", permitId); + var tare = await printRepo.GetLatestEventWithLocationAsync(permitId, "LTW", ct); + var gross = await printRepo.GetLatestEventWithLocationAsync(permitId, "LGW", ct); + var net = (gross?.Weight ?? 0) - (tare?.Weight ?? 0); + var (ton, kilo) = WeightBreakdown.Split(net); + return new PrintOutDto { Header = header, NetWeight = (long)net, Ton = ton, Kilo = kilo, Location = tare?.LocationName, DoneBy = gross?.DoneBy }; + } + + public async Task GetPermitDetailsAsync(long permitId, CancellationToken ct = default) + { + await EnsureAccessAsync(permitId, ct); + var dto = await printRepo.GetDetailsAsync(permitId, ct) ?? throw new NotFoundException("Permit", permitId); + dto.Events = await permits.GetEventsAsync(permitId, ct); + return dto; + } +} diff --git a/src/NTP.Application/Grains/Registry/BlacklistService.cs b/src/NTP.Application/Grains/Registry/BlacklistService.cs new file mode 100644 index 0000000..8676d50 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/BlacklistService.cs @@ -0,0 +1,93 @@ +using System.Globalization; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +public interface IBlacklistService +{ + Task> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct); + Task AddAsync(AddBlacklistRequest request, CancellationToken ct); + Task CancelAsync(long id, CancelBlacklistRequest request, CancellationToken ct); + /// jobs\changeBlacklistStatus.cfm: expires OPEN entries whose expiry date has passed. + Task ExpireDueAsync(CancellationToken ct); +} + +/// Port of grains.cfc getBlackListGrid / BL_addToBlacklist / deleteFromBlackList and the expiry job. +public sealed class BlacklistService( + IBlacklistRepository repository, + IRegistrySettingsService settings, + IUnitOfWork unitOfWork, + ICurrentUser user) : IBlacklistService +{ + private static readonly string[] CancelRoles = ["GNSU", "GNCO", "GTO"]; + + public async Task> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct) + { + var result = await repository.SearchAsync(query, page, ct); + foreach (var r in result.Items) + { + r.CategoryCaption = RegistryRules.BlacklistCategoryCaption(r.Category); + r.EntityTypeCaption = RegistryRules.BlacklistEntityCaption(r.EntityType); + r.StatusCaption = RegistryRules.BlacklistStatusCaption(r.StatusCode); + } + return result; + } + + public async Task AddAsync(AddBlacklistRequest request, CancellationToken ct) + { + RegistryValidation.ThrowIfAny(RegistryValidation.ValidateBlacklist(request)); + + var entityType = string.IsNullOrWhiteSpace(request.EntityType) ? BlacklistValues.EntityPermit : request.EntityType.Trim().ToUpperInvariant(); + var number = request.EntityNum!.Trim(); + + // The legacy function stores the permit id as ENTITYID: the number typed is a PN (looked up) unless ISID is set. + var entityId = number; + var shift = 1; + if (entityType == BlacklistValues.EntityPermit) + { + long permitId; + if (request.IsId) + permitId = long.Parse(number, CultureInfo.InvariantCulture); + else + permitId = await repository.FindPermitIdByNumberAsync(number, ct) + ?? throw new BusinessException(RegistryErrors.PermitNotFound, RegistryMessages.PermitNotFound(number)); + entityId = permitId.ToString(CultureInfo.InvariantCulture); + // shift of the tender order of the permit (default 1) + shift = await repository.GetPermitShiftAsync(permitId, ct) ?? 1; + } + + var (start, end) = settings.ShiftHours(shift); + var expiry = RegistryRules.BlacklistExpiry(DateTime.Now, request.ExpiryDays, start, end); + var remarks = RegistryRules.BlacklistRemarks(request.Remarks?.Trim(), expiry); + + var id = await repository.InsertAsync(request.Category!, entityType, entityId, user.UserId, expiry, remarks, ct); + return new BlacklistAddedDto(RegistryMessages.BlacklistAdded, id, expiry); + } + + public async Task CancelAsync(long id, CancelBlacklistRequest request, CancellationToken ct) + { + // the cancel icon of the grid is only offered to GNSU, GNCO, GTO + if (!user.IsInAnyRole(CancelRoles)) + throw new ForbiddenException(RegistryErrors.Forbidden, RegistryMessages.Forbidden); + RegistryValidation.ThrowIfAny(RegistryValidation.ValidateCancelBlacklist(request)); + + var entry = await repository.GetAsync(id, ct) ?? throw new NotFoundException("Blacklist entry", id); + // ...and only for OPEN entries + if (!string.Equals(entry.StatusCode, BlacklistValues.Open, StringComparison.OrdinalIgnoreCase)) + throw new BusinessException(RegistryErrors.BlacklistNotOpen, RegistryMessages.BlacklistNotOpen); + + var remarks = request.Remarks!.Trim(); + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.CancelAsync(id, user.UserId, remarks, token); + await repository.DeleteDistributionLogAsync(id, remarks, token); + return true; + }, ct); + + return new RegistryResult(RegistryMessages.Done, id); + } + + public Task ExpireDueAsync(CancellationToken ct) => repository.ExpireDueAsync(ct); +} diff --git a/src/NTP.Application/Grains/Registry/DriverRegistryService.cs b/src/NTP.Application/Grains/Registry/DriverRegistryService.cs new file mode 100644 index 0000000..2fe599c --- /dev/null +++ b/src/NTP.Application/Grains/Registry/DriverRegistryService.cs @@ -0,0 +1,110 @@ +using NTP.Application.Access; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +public interface IDriverRegistryService +{ + Task> SearchAsync(DriverListQuery query, PageRequest page, CancellationToken ct); + Task GetAsync(long id, CancellationToken ct); + Task CreateAsync(SaveDriverRequest request, CancellationToken ct); + Task AcceptAsync(long id, CancellationToken ct); + Task RevokeAsync(long id, CancellationToken ct); +} + +/// Port of register.cfc saveDriverDetails / getDriverInfo / getDriverGrid / revokeDriver / acceptDriver. +public sealed class DriverRegistryService( + IRegistryRepository repository, + IRegistryAccessService access, + IRegistryAttachmentService attachments, + IUnitOfWork unitOfWork, + ICurrentUser user) : IDriverRegistryService +{ + public async Task> SearchAsync(DriverListQuery query, PageRequest page, CancellationToken ct) + { + var result = await repository.SearchDriversAsync(access.Scope, query, page, ct); + foreach (var r in result.Items) r.StatusCaption = RegistryRules.StatusCaption(r.StatusCode, r.StatusCaption); + return result; + } + + public async Task GetAsync(long id, CancellationToken ct) + { + var driver = await repository.GetDriverDetailAsync(id, ct) ?? throw new NotFoundException("Driver", id); + access.EnsureCompanyAccess(driver.Tcscac); + driver.StatusCaption = RegistryRules.StatusCaption(driver.StatusCode, driver.StatusCaption); + driver.Attachments = await attachments.ListAsync(RegistryAttachmentService.KindDriver, id, ct); + return driver; + } + + public async Task CreateAsync(SaveDriverRequest request, CancellationToken ct) + { + await access.RequireAuthorityAsync(PermissionKeys.RegistryDriversCreate, ct); + RegistryValidation.ThrowIfAny(RegistryValidation.ValidateDriver(request)); + + var nnpn = request.Nnpn!.Trim(); + // validateUniqueNNPN + if (await repository.ActiveDriverExistsAsync(nnpn, null, ct)) + throw new BusinessException(RegistryErrors.DriverDuplicate, RegistryMessages.DriverDuplicate); + + var tempIds = await attachments.EnsureTempFilesAsync(request.AttachmentIds, ct); + // the legacy page refuses a save with fewer than 2 attached files (identity + license) + if (!RegistryRules.HasEnoughAttachments(tempIds.Count, 0)) + throw new BusinessException(RegistryErrors.AttachmentsIncomplete, RegistryMessages.AttachmentsIncomplete); + + var id = await unitOfWork.ExecuteInTransactionAsync(async token => + { + var driver = new NtpDriver + { + Nnpn = nnpn, + Name = request.Name!.Trim(), + Dln = request.Dln!.Trim(), + Dled = request.Dled!.Value.Date, + // legacy: TCSCAC = session.companycodeno (empty for staff users -> NULL) + Tcscac = access.CompanyCodeNo, + StatusCode = RegistryStatus.Open, + CreateUserId = user.UserId, + Nat = request.Nat!.Trim(), + Cat = request.Cat!.Trim(), + Mobile1 = request.Mobile1!.Trim(), + Mobile2 = string.IsNullOrWhiteSpace(request.Mobile2) ? null : request.Mobile2.Trim() + }; + var newId = await repository.InsertDriverAsync(driver, token); + await attachments.AttachAsync(RegistryAttachmentService.KindDriver, newId, tempIds, token); + return newId; + }, ct); + + return new RegistryResult(RegistryMessages.Done, id); + } + + public async Task AcceptAsync(long id, CancellationToken ct) + { + await access.RequireActionAsync(RegistryActions.AcceptDriver, false, ct); + var driver = await repository.GetDriverAsync(id, ct) ?? throw new NotFoundException("Driver", id); + access.EnsureCompanyAccess(driver.Tcscac); + if (!RegistryRules.CanAccept(driver.StatusCode)) + throw new BusinessException(RegistryErrors.InvalidState, RegistryMessages.NotAcceptable); + + // acceptDriver: "السائق مفعل مسبقا" when validateUniqueNNPN finds an active driver with the same number. + // The legacy check also matched the driver being accepted (its own OPEN row), which made accepting impossible; + // here the record itself is excluded so only another active record with the same number blocks. + if (await repository.ActiveDriverExistsAsync(driver.Nnpn, driver.Id, ct)) + throw new BusinessException(RegistryErrors.DriverAlreadyActive, RegistryMessages.DriverAlreadyActive); + + await repository.AcceptDriverAsync(id, user.UserId, ct); + return new RegistryResult(RegistryMessages.Accepted, id); + } + + public async Task RevokeAsync(long id, CancellationToken ct) + { + await access.RequireActionAsync(RegistryActions.RevokeDriver, false, ct); + var driver = await repository.GetDriverAsync(id, ct) ?? throw new NotFoundException("Driver", id); + access.EnsureCompanyAccess(driver.Tcscac); + if (!RegistryRules.CanRevoke(driver.StatusCode)) + throw new BusinessException(RegistryErrors.InvalidState, RegistryMessages.AlreadyRevoked); + + await repository.RevokeDriverAsync(id, user.UserId, ct); + return new RegistryResult(RegistryMessages.Revoked, id); + } +} diff --git a/src/NTP.Application/Grains/Registry/RegistryAbstractions.cs b/src/NTP.Application/Grains/Registry/RegistryAbstractions.cs new file mode 100644 index 0000000..d631651 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/RegistryAbstractions.cs @@ -0,0 +1,170 @@ +using NTP.Application.Common; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +/// +/// Registry settings that legacy kept in ColdFusion application variables which are NOT in the repo +/// (application.GN_BadiyaSCAC, GN_ALLOWEDSTATUSES, GN_BadyahOwnership, GN_OthersOwnership, grnsdtrbutnshft_N, +/// tempuploadedfiles / uploadedfiles). Implemented over configuration section Grains:Registry with safe defaults. +/// +public interface IRegistrySettingsService +{ + long BadiyaScac { get; } + /// GN_ALLOWEDSTATUSES (default OPEN,ACCPT). + IReadOnlyList AllowedTruckStatuses { get; } + IReadOnlyList BadiyaOwnershipCodes { get; } + IReadOnlyList OthersOwnershipCodes { get; } + /// "start,end" hours of distribution shift (default 0,24). + (int Start, int End) ShiftHours(int shift); + string TempUploadPath { get; } + string UploadedFilesPath { get; } + long MaxUploadBytes { get; } + IReadOnlyList AllowedUploadExtensions { get; } +} + +/// File system part of the attachments (temp upload, promotion to the permanent folder, reading). +public interface IRegistryFileStoreService +{ + /// Saves an uploaded file in the temp folder; returns the temp id. + Task SaveTempAsync(Stream content, string originalName, CancellationToken ct = default); + + /// Original name recorded for a temp id, or null when the temp file does not exist. + Task GetTempNameAsync(string tempId, CancellationToken ct = default); + + /// Moves a temp file into under (legacy cffile rename). + Task PromoteAsync(string tempId, string folder, string storedName, CancellationToken ct = default); + + Task OpenAsync(string folder, string storedName, CancellationToken ct = default); +} + +public interface IRegistryRepository +{ + // ----- authorization (legacy application.objAuth.isActAuthorized(actionId, session.lstGID)) + Task HasActionAsync(string roleCode, int actionId, CancellationToken ct = default); + + // ----- lookups + Task> GetTenderCompaniesAsync(CancellationToken ct = default); + Task> GetTruckKindsAsync(IReadOnlyList kinds, CancellationToken ct = default); + Task> GetDestinationLocationsAsync(string gnType, CancellationToken ct = default); + Task> GetDriverNationalitiesAsync(CancellationToken ct = default); + Task> GetLocationsByIdsAsync(IReadOnlyList ids, CancellationToken ct = default); + + // ----- grids + Task> SearchTrucksAsync(RegistryScope scope, TruckListQuery query, PageRequest page, CancellationToken ct = default); + Task> SearchTrailersAsync(RegistryScope scope, TrailerListQuery query, PageRequest page, CancellationToken ct = default); + Task> SearchDriversAsync(RegistryScope scope, DriverListQuery query, PageRequest page, CancellationToken ct = default); + /// getAllTrnOnthisTn: trailers connected to a truck (or just the given trailer). + Task> ListTrailersOfTruckAsync(RegistryScope scope, long? truckId, long? trailerId, CancellationToken ct = default); + + // ----- trucks + Task GetTruckDetailAsync(long id, CancellationToken ct = default); + Task GetTruckAsync(long id, CancellationToken ct = default); + Task GetLatestTrailerOfTruckAsync(long truckId, CancellationToken ct = default); + /// validateUniqueTN: an active (REGREQST/OPEN/ACCPT) truck with the number exists. + Task ActiveTruckExistsAsync(string tn, CancellationToken ct = default); + Task InsertTruckAsync(NtpTruck truck, CancellationToken ct = default); + Task UpdateTruckAsync(long id, NtpTruck values, bool updatePhone, string? newStatus, string userId, CancellationToken ct = default); + Task SetTruckStatusAsync(long id, string status, string userId, CancellationToken ct = default); + Task AcceptTruckAsync(long id, string userId, CancellationToken ct = default); + Task RevokeTruckAsync(long id, string userId, CancellationToken ct = default); + Task RevokeTrailersOfTruckAsync(long truckId, string userId, CancellationToken ct = default); + Task DeactivateDestinationsAsync(string tn, string userId, CancellationToken ct = default); + Task RevokeOpenPermitsOfTruckAsync(string tn, string userId, CancellationToken ct = default); + Task TruckHasGnPermitAsync(string tn, CancellationToken ct = default); + + // ----- destinations (NTP_COMPANY_DISTINATION) + Task> GetActiveDestinationIdsAsync(string tn, CancellationToken ct = default); + Task GetPendingDestinationAsync(string tn, CancellationToken ct = default); + Task InsertDestinationAsync(string tn, long destination, string userId, CancellationToken ct = default); + + // ----- trailers + Task GetTrailerDetailAsync(long id, CancellationToken ct = default); + Task GetTrailerAsync(long id, CancellationToken ct = default); + Task ActiveTrailerExistsAsync(string tn, CancellationToken ct = default); + Task TruckHasNonRevokedTrailerAsync(long truckId, CancellationToken ct = default); + Task InsertTrailerAsync(NtpTrailer trailer, CancellationToken ct = default); + Task UpdateTrailerAsync(long id, NtpTrailer values, bool updatePhone, string userId, CancellationToken ct = default); + Task AcceptTrailerAsync(long id, string userId, CancellationToken ct = default); + Task RevokeTrailerAsync(long id, string userId, CancellationToken ct = default); + + // ----- drivers + Task GetDriverDetailAsync(long id, CancellationToken ct = default); + Task GetDriverAsync(long id, CancellationToken ct = default); + /// validateUniqueNNPN: a driver with this NNPN in an active status exists (optionally ignoring one id). + Task ActiveDriverExistsAsync(string nnpn, long? excludeId, CancellationToken ct = default); + Task InsertDriverAsync(NtpDriver driver, CancellationToken ct = default); + Task AcceptDriverAsync(long id, string userId, CancellationToken ct = default); + Task RevokeDriverAsync(long id, string userId, CancellationToken ct = default); + + // ----- attachments (GRAINS_FILES) + Task InsertFileAsync(string attachmentType, long entityId, string originalName, string fileName, CancellationToken ct = default); + Task> GetFilesAsync(long entityId, string attachmentType, CancellationToken ct = default); + Task FindFileAsync(string attachmentType, string fileName, CancellationToken ct = default); +} + +public interface IBlacklistRepository +{ + Task> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct = default); + /// shift of the tender order connected to the permit (grainstenderorder.shift), null when there is none. + Task GetPermitShiftAsync(long permitId, CancellationToken ct = default); + /// permits.id for a permit number (PN), null when unknown. + Task FindPermitIdByNumberAsync(string pn, CancellationToken ct = default); + Task InsertAsync(string category, string entityType, string entityId, string createdBy, DateTime expiry, string remarks, CancellationToken ct = default); + Task GetAsync(long id, CancellationToken ct = default); + Task CancelAsync(long id, string user, string remarks, CancellationToken ct = default); + /// TRUCK_DISTRIBUTION_LOG rows of a cancelled entry (PENDING / RVKD) -> DELETED. + Task DeleteDistributionLogAsync(long blacklistId, string remarks, CancellationToken ct = default); + /// Job: OPEN entries whose EXPIRYDATE has passed -> EXPIRED (by SYSTEM). Returns the count. + Task ExpireDueAsync(CancellationToken ct = default); +} + +/// Weighbridge exceptions, grains weights, fleet turns, location counts and the permit-screen lookups of grains.cfc. +public interface IRegistryOpsRepository +{ + Task FindOpenOrAcceptedTruckIdAsync(string tn, CancellationToken ct = default); + Task InsertWeighbridgeControlAsync(long truckId, long locationId, string? notes, string createdBy, DateTime expiryDate, CancellationToken ct = default); + + Task<(long Id, string? Status)?> FindPermitByNumberAsync(string pn, CancellationToken ct = default); + Task FindWeightRowAsync(long permitId, CancellationToken ct = default); + Task UpdateWeightsAsync(long weightRowId, string empty, string gross, string document, string user, CancellationToken ct = default); + Task InsertWeightsAsync(string empty, string gross, string document, long permitId, string user, CancellationToken ct = default); + + Task CountActiveFleetAsync(long scac, CancellationToken ct = default); + Task CountActiveTurnRowsAsync(long scac, CancellationToken ct = default); + Task TruckInTurnAsync(long scac, long tn, CancellationToken ct = default); + Task InsertTurnRowAsync(long scac, long tn, string user, CancellationToken ct = default); + Task ResetTurnRowsAsync(long scac, CancellationToken ct = default); + + Task IsValidBadiyaTruckAsync(string tn, long badiyaScac, CancellationToken ct = default); + Task> GetLocationTruckCountsAsync(CancellationToken ct = default); + + // permit-screen lookups (grains.cfc) + Task GetDriverFromPermitsAsync(string nnpn, string domain, CancellationToken ct = default); + Task GetTruckFromPermitsAsync(string tn, string domain, CancellationToken ct = default); + Task> GetTrailerInUseAsync(string trn, long? exceptPermitId, string domain, CancellationToken ct = default); + Task GetPermitByTruckAsync(string tn, string status, CancellationToken ct = default); + Task GetTrailerNumberOfTruckAsync(string tn, IReadOnlyList allowedStatuses, CancellationToken ct = default); + + Task<(string? ChasesNumber, string? Axials, DateTime? RegDate)?> GetTruckInfoAsync(string tn, RegistryScope scope, CancellationToken ct = default); + Task GetActiveTrailerScacAsync(string trn, CancellationToken ct = default); + Task<(string? ChasesNumber, string? Axials, DateTime? RegDate)?> GetTrailerInfoAsync(string trn, RegistryScope scope, CancellationToken ct = default); + Task<(string? Name, string? Dln, DateTime? Dled)?> GetDriverInfoAsync(string nnpn, CancellationToken ct = default); + + // MOT + Task GetMotOwnershipCodeAsync(string tn, long scac, CancellationToken ct = default); + Task> GetMotTruckTypesAsync(string tn, long scac, CancellationToken ct = default); + Task CountMotTrailerRowsAsync(string trn, long scac, CancellationToken ct = default); +} + +/// Port of ws.cfc createPermitRecord and the job that registers the queue for new 327 trucks. +public interface IRegistryQueuePermitRepository +{ + Task IsOpenOrAcceptedGnTruckAsync(string tn, CancellationToken ct = default); + Task HasActivePermitAsync(string tn, string tt, bool checkAllStatuses, CancellationToken ct = default); + Task NextTrackingNumberAsync(bool badiya, CancellationToken ct = default); + Task NextTripCounterAsync(string tt, long badiyaScac, CancellationToken ct = default); + Task GetMaxTenderIdAsync(CancellationToken ct = default); + Task InsertPermitAsync(string pn, string tn, long scac, string status, string tt, long? tripCounter, CancellationToken ct = default); + Task> GetBadiyaTrucksWithoutPermitsAsync(long badiyaScac, CancellationToken ct = default); +} diff --git a/src/NTP.Application/Grains/Registry/RegistryAccessService.cs b/src/NTP.Application/Grains/Registry/RegistryAccessService.cs new file mode 100644 index 0000000..5d1900a --- /dev/null +++ b/src/NTP.Application/Grains/Registry/RegistryAccessService.cs @@ -0,0 +1,95 @@ +using System.Globalization; +using NTP.Application.Abstractions; +using NTP.Application.Access; +using NTP.Application.Common; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +public interface IRegistryAccessService +{ + /// Legacy session.companyCodeNO: numeric part of the user's company code (mid(code,4,6)), null when not numeric. + long? CompanyCodeNo { get; } + bool IsBadiyaCompany { get; } + /// Company users (session.stkid eq 62) only see / touch their own company's records. + bool IsCompanyUser { get; } + RegistryScope Scope { get; } + Task HasActionAsync(int actionId, CancellationToken ct = default); + /// Throws unless the user has the action (or and the user belongs to 327). + Task RequireActionAsync(int actionId, bool orBadiya = false, CancellationToken ct = default); + /// Adding / editing a truck, trailer or driver is decided by the permission table only (GRAINS_SCREEN_PERMISSIONS); throws Forbidden otherwise. + Task RequireAuthorityAsync(string permissionKey, CancellationToken ct = default); + /// Company users may only access records of their own company. + void EnsureCompanyAccess(long? recordTcscac); + Task GetPermissionsAsync(CancellationToken ct = default); +} + +public sealed class RegistryAccessService( + ICurrentUser user, IRegistryRepository repository, IRegistrySettingsService settings, IPermissionService permissions) : IRegistryAccessService +{ + public long? CompanyCodeNo => ParseCompanyCodeNo(user.CompanyCode); + + public bool IsBadiyaCompany => CompanyCodeNo == settings.BadiyaScac; + + public bool IsCompanyUser => user.StkId == RegistryConstants.CompanyStakeholderId; + + public RegistryScope Scope => new(IsCompanyUser, CompanyCodeNo, user.IsInRole("GOO")); + + /// ColdFusion: isnumeric(mid(code,4,6)) then mid(code,4,6)*1. + public static long? ParseCompanyCodeNo(string? companyCode) + { + if (string.IsNullOrEmpty(companyCode) || companyCode.Length < 4) return null; + var part = companyCode.Substring(3, Math.Min(6, companyCode.Length - 3)); + return long.TryParse(part, NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? n : null; + } + + public Task HasActionAsync(int actionId, CancellationToken ct = default) => + repository.HasActionAsync(user.RoleCode, actionId, ct); + + public async Task RequireActionAsync(int actionId, bool orBadiya = false, CancellationToken ct = default) + { + if (orBadiya && IsBadiyaCompany) return; + if (!await HasActionAsync(actionId, ct)) + throw new ForbiddenException(RegistryErrors.Forbidden, RegistryMessages.Forbidden); + } + + public async Task RequireAuthorityAsync(string permissionKey, CancellationToken ct = default) + { + if (!await permissions.IsAllowedAsync(permissionKey, ct)) + throw new ForbiddenException(RegistryErrors.Forbidden, RegistryMessages.Forbidden); + } + + public void EnsureCompanyAccess(long? recordTcscac) + { + if (IsCompanyUser && recordTcscac != CompanyCodeNo) + throw new NotFoundException("Registry record", "-"); + } + + public async Task GetPermissionsAsync(CancellationToken ct = default) + { + var badiya = IsBadiyaCompany; + return new RegistryPermissionsDto + { + IsBadiyaCompany = badiya, + IsCompanyUser = IsCompanyUser, + CompanyCodeNo = CompanyCodeNo, + // database only (GRAINS_SCREEN_PERMISSIONS): no legacy action lookup and no hard-coded company exception + CanAddTruck = await permissions.IsAllowedAsync(PermissionKeys.RegistryTrucksCreate, ct), + CanAddTrailer = await permissions.IsAllowedAsync(PermissionKeys.RegistryTrailersCreate, ct), + CanAddDriver = await permissions.IsAllowedAsync(PermissionKeys.RegistryDriversCreate, ct), + CanEditTruck = await permissions.IsAllowedAsync(PermissionKeys.RegistryTrucksEdit, ct), + CanEditTrailer = await permissions.IsAllowedAsync(PermissionKeys.RegistryTrailersEdit, ct), + // legacy: revoke truck / trailer buttons are hidden for company 327 + CanRevokeTruck = !badiya && await HasActionAsync(RegistryActions.RevokeTruck, ct), + CanRevokeTrailer = !badiya && await HasActionAsync(RegistryActions.RevokeTrailer, ct), + CanRevokeDriver = await HasActionAsync(RegistryActions.RevokeDriver, ct), + CanAcceptTruck = await HasActionAsync(RegistryActions.AcceptTruck, ct), + CanAcceptTrailer = await HasActionAsync(RegistryActions.AcceptTrailer, ct), + CanAcceptDriver = await HasActionAsync(RegistryActions.AcceptDriver, ct), + CanManageDestinations = await HasActionAsync(RegistryActions.Destinations, ct), + CanExportTruckReport = user.IsInAnyRole("GTO", "GOO", "GNAC"), + CanExportDriverReport = user.IsInAnyRole("GTO", "GOO"), + CanCancelBlacklist = user.IsInAnyRole("GNSU", "GNCO", "GTO") + }; + } +} diff --git a/src/NTP.Application/Grains/Registry/RegistryAttachmentService.cs b/src/NTP.Application/Grains/Registry/RegistryAttachmentService.cs new file mode 100644 index 0000000..4b81e37 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/RegistryAttachmentService.cs @@ -0,0 +1,95 @@ +using NTP.Application.Common; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +public interface IRegistryAttachmentService +{ + Task UploadTempAsync(Stream content, string fileName, long length, CancellationToken ct = default); + /// Verifies every temp id exists (so a save fails before anything is written). Returns the distinct ids. + Task> EnsureTempFilesAsync(IEnumerable? tempIds, CancellationToken ct = default); + /// Saves GRAINS_FILES rows and moves the temp files to the permanent folder (legacy genFileName + cffile rename). + Task AttachAsync(string kind, long entityId, IReadOnlyList tempIds, CancellationToken ct = default); + Task> ListAsync(string kind, long entityId, CancellationToken ct = default); + Task OpenAsync(string kind, string fileName, CancellationToken ct = default); +} + +public sealed class RegistryAttachmentService( + IRegistryRepository repository, IRegistryFileStoreService store, IRegistrySettingsService settings) : IRegistryAttachmentService +{ + public const string KindTruck = "truck"; + public const string KindTrailer = "trailer"; + public const string KindDriver = "driver"; + + private static (string Type, string Folder) Map(string kind) => kind.ToLowerInvariant() switch + { + KindTruck => (RegistryAttachmentTypes.TruckLicense, RegistryAttachmentTypes.TruckFolder), + KindTrailer => (RegistryAttachmentTypes.TrailerLicense, RegistryAttachmentTypes.TrailerFolder), + KindDriver => (RegistryAttachmentTypes.DriverLicense, RegistryAttachmentTypes.DriverFolder), + _ => throw new NotFoundException("Attachment kind", kind) + }; + + public async Task UploadTempAsync(Stream content, string fileName, long length, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(fileName) || length <= 0) + throw new BusinessException(RegistryErrors.InvalidInput, RegistryMessages.RequiredFields); + if (length > settings.MaxUploadBytes) + throw new BusinessException(RegistryErrors.InvalidInput, "حجم الملف كبير جدا"); + var ext = Path.GetExtension(fileName).TrimStart('.').ToLowerInvariant(); + if (!settings.AllowedUploadExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase)) + throw new BusinessException(RegistryErrors.InvalidInput, "نوع الملف غير مسموح"); + return await store.SaveTempAsync(content, Path.GetFileName(fileName), ct); + } + + public async Task> EnsureTempFilesAsync(IEnumerable? tempIds, CancellationToken ct = default) + { + var ids = (tempIds ?? []).Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct().ToList(); + foreach (var id in ids) + if (await store.GetTempNameAsync(id, ct) is null) + throw new BusinessException(RegistryErrors.AttachmentMissing, RegistryMessages.AttachmentsIncomplete); + return ids; + } + + public async Task AttachAsync(string kind, long entityId, IReadOnlyList tempIds, CancellationToken ct = default) + { + var (type, folder) = Map(kind); + foreach (var id in tempIds) + { + var original = await store.GetTempNameAsync(id, ct) + ?? throw new BusinessException(RegistryErrors.AttachmentMissing, RegistryMessages.AttachmentsIncomplete); + var ext = Path.GetExtension(original); + var stored = $"{Guid.NewGuid():N}{ext.ToLowerInvariant()}"; + await repository.InsertFileAsync(type, entityId, original, stored, ct); + await store.PromoteAsync(id, folder, stored, ct); + } + } + + public async Task> ListAsync(string kind, long entityId, CancellationToken ct = default) + { + var (type, _) = Map(kind); + var files = await repository.GetFilesAsync(entityId, type, ct); + return files.Select(f => new RegistryAttachmentDto { FileName = f.FileName, OriginalName = f.OriginalName, Kind = kind.ToLowerInvariant() }).ToList(); + } + + public async Task OpenAsync(string kind, string fileName, CancellationToken ct = default) + { + 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); + 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); + } + + private static string ContentTypeOf(string name) => Path.GetExtension(name).ToLowerInvariant() switch + { + ".pdf" => "application/pdf", + ".png" => "image/png", + ".jpg" or ".jpeg" => "image/jpeg", + ".gif" => "image/gif", + ".tif" or ".tiff" => "image/tiff", + ".bmp" => "image/bmp", + ".doc" => "application/msword", + ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + _ => "application/octet-stream" + }; +} diff --git a/src/NTP.Application/Grains/Registry/RegistryContracts.cs b/src/NTP.Application/Grains/Registry/RegistryContracts.cs new file mode 100644 index 0000000..fcad5b2 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/RegistryContracts.cs @@ -0,0 +1,433 @@ +using System.Text.Json.Serialization; + +namespace NTP.Application.Grains.Registry; + +// ------------------------------------------------------------------ shared / lookups + +/// Who the caller is, as far as the registry rules care (legacy session.stkid / companycodeno / userrolecode). +public sealed record RegistryScope(bool CompanyOnly, long? CompanyCodeNo, bool IsGoo); + +public sealed class RegistryPermissionsDto +{ + public bool IsBadiyaCompany { get; set; } + public bool IsCompanyUser { get; set; } + public long? CompanyCodeNo { get; set; } + public bool CanAddTruck { get; set; } + public bool CanAddTrailer { get; set; } + public bool CanAddDriver { get; set; } + public bool CanEditTruck { get; set; } + public bool CanEditTrailer { get; set; } + public bool CanRevokeTruck { get; set; } + public bool CanRevokeTrailer { get; set; } + public bool CanRevokeDriver { get; set; } + public bool CanAcceptTruck { get; set; } + public bool CanAcceptTrailer { get; set; } + public bool CanAcceptDriver { get; set; } + /// Action 107: pick / see destinations (truck form, company 327 only). + public bool CanManageDestinations { get; set; } + /// Roles GTO, GOO, GNAC may export the truck report (legacy report icon). + public bool CanExportTruckReport { get; set; } + public bool CanExportDriverReport { get; set; } + public bool CanCancelBlacklist { get; set; } +} + +public sealed class RegistryOptionDto +{ + public string Value { get; set; } = string.Empty; + public string Label { get; set; } = string.Empty; +} + +public sealed class TenderCompanyDto +{ + public long Scac { get; set; } + public string? Name { get; set; } +} + +public sealed class TruckKindDto +{ + /// TRUCKKINDS.TRUCKKINDCODE: S (single), T (tractor head), HTR (half trailer), TR (trailer). + public string Kind { get; set; } = string.Empty; + /// TRUCKKINDS.ID: stored in AXIALS. + public long Id { get; set; } + public string? Name { get; set; } +} + +public sealed class RegistryLocationDto +{ + public long Id { get; set; } + public string? Name { get; set; } +} + +public sealed class RegistryNationalityDto +{ + public string Code { get; set; } = string.Empty; + public string? Name { get; set; } +} + +public sealed class RegistryDestinationOptionsDto +{ + /// gn_type PCKD (legacy "مشول"). + public IReadOnlyList Packed { get; set; } = []; + /// gn_type BULK (legacy "سائب"). + public IReadOnlyList Bulk { get; set; } = []; + /// gn_type BULK_GALLAB (legacy "سائب - قلابات"). + public IReadOnlyList BulkGallab { get; set; } = []; +} + +public sealed class RegistryAttachmentDto +{ + public string FileName { get; set; } = string.Empty; + public string OriginalName { get; set; } = string.Empty; + /// truck | trailer | driver (route segment of the download endpoint). + public string Kind { get; set; } = string.Empty; +} + +public sealed record RegistryTempFileDto(string Id, string Name, long Size); + +public sealed record RegistryDownload(Stream Content, string ContentType, string FileName); + +/// Result of a write: message is shown verbatim by the front end (legacy Arabic MSG). +public sealed record RegistryResult(string Message, long? Id = null); + +// ------------------------------------------------------------------ list queries + +public sealed record TruckListQuery(string? SearchType, string? Tn, string? ChasesNumber, string? StatusCode, string? HeadType, long? Tcscac); +public sealed record TrailerListQuery(string? Tn, string? ChasesNumber, string? StatusCode, long? Tcscac); +public sealed record DriverListQuery(string? Nnpn, string? Name, string? StatusCode); +public sealed record BlacklistQuery(string? EntityId, string? Category, string? StatusCode); + +public sealed class TruckGridRowDto +{ + public long Id { get; set; } + public string Tn { get; set; } = string.Empty; + /// TN (truck) or TRN (trailer) - what the row represents. + public string EntityType { get; set; } = "TN"; + public string? ChasesNumber { get; set; } + public DateTime? CreateTimestamp { get; set; } + public DateTime? RegDate { get; set; } + public string? CreateUserId { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? StatusCaption { get; set; } + public string? CompName { get; set; } + /// For trailer rows: the connected truck id (NTP_TRAILERS.TN_ID). + public long? TnId { get; set; } +} + +public sealed class TrailerGridRowDto +{ + public long Id { get; set; } + public string Tn { get; set; } = string.Empty; + public string? ChasesNumber { get; set; } + public DateTime? CreateTimestamp { get; set; } + public DateTime? RegDate { get; set; } + public string? CreateUserId { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? StatusCaption { get; set; } + public string? CompName { get; set; } + public string? OwnerName { get; set; } + public string? OwnerNnpn { get; set; } +} + +public sealed class DriverGridRowDto +{ + public long Id { get; set; } + public string Nnpn { get; set; } = string.Empty; + public string? Name { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } + public DateTime? CreateTimestamp { get; set; } + public string? CreateUserId { get; set; } + public string? CompName { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? StatusCaption { get; set; } +} + +public sealed class BlacklistGridRowDto +{ + public long Id { get; set; } + public string? Category { get; set; } + public string? CategoryCaption { get; set; } + public string? EntityType { get; set; } + public string? EntityTypeCaption { get; set; } + /// Permit number for PERMIT entries, the raw number for driver/truck/trailer entries. + public string? EntityNumber { get; set; } + public DateTime? CreationDate { get; set; } + public string? CreatedBy { get; set; } + public DateTime? LastUpdateDate { get; set; } + public string? LastUpdateUser { get; set; } + public DateTime? ExpiryDate { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? StatusCaption { get; set; } + public string? Remarks { get; set; } +} + +// ------------------------------------------------------------------ details + +public sealed class PendingDestinationDto +{ + public string? User { get; set; } + public string? Time { get; set; } +} + +public sealed class TruckDetailDto +{ + public long Id { get; set; } + public string Tn { get; set; } = string.Empty; + public string? ChasesNumber { get; set; } + public DateTime? RegDate { get; set; } + public long? Axials { get; set; } + /// S when AXIALS < 7, otherwise T (legacy form radio). + public string? AxialsKind { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? StatusCaption { get; set; } + public string? OwnerName { get; set; } + public string? OwnerNnpn { get; set; } + public string? Color { get; set; } + public string? Model { get; set; } + public string? ManifactureYear { get; set; } + public string? PhoneNumber { get; set; } + public string? HeadType { get; set; } + public long? Tcscac { get; set; } + public string? CompName { get; set; } + public string? LastUpdateUserId { get; set; } + public DateTime? LastUpdateTimestamp { get; set; } + public long? TrailerId { get; set; } + public string? TrailerTn { get; set; } + /// Active destination location ids (only for users who may see destinations: action 107 or role GOO). + public IReadOnlyList? DestinationIds { get; set; } + public PendingDestinationDto? PendingDestination { get; set; } + public IReadOnlyList Attachments { get; set; } = []; +} + +public sealed class TrailerDetailDto +{ + public long Id { get; set; } + public string Tn { get; set; } = string.Empty; + public string? ChasesNumber { get; set; } + public DateTime? RegDate { get; set; } + public long? Axials { get; set; } + /// TR when AXIALS < 12, otherwise HTR (legacy form radio). + public string? AxialsKind { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? StatusCaption { get; set; } + public string? OwnerName { get; set; } + public string? OwnerNnpn { get; set; } + public string? PhoneNumber { get; set; } + public long? TruckId { get; set; } + public long? Tcscac { get; set; } + public string? CompName { get; set; } + public IReadOnlyList Attachments { get; set; } = []; +} + +public sealed class DriverDetailDto +{ + public long Id { get; set; } + public string Nnpn { get; set; } = string.Empty; + public string? Name { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? StatusCaption { get; set; } + public string? Nat { get; set; } + public string? Cat { get; set; } + public string? Mobile1 { get; set; } + public string? Mobile2 { get; set; } + /// Owning company (used for the company-user scope check only). + [JsonIgnore] + public long? Tcscac { get; set; } + public IReadOnlyList Attachments { get; set; } = []; +} + +// ------------------------------------------------------------------ requests + +/// Destinations picked on the truck form (location ids per group). +public sealed class TruckDestinationsRequest +{ + public List Packed { get; set; } = []; + public List Bulk { get; set; } = []; + public List BulkGallab { get; set; } = []; + + public IReadOnlyList All() => [.. Packed, .. Bulk, .. BulkGallab]; +} + +[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] +public sealed class SaveTruckRequest +{ + public string? Tn { get; set; } + public string? ChasesNumber { get; set; } + public long? Axials { get; set; } + public DateTime? RegDate { get; set; } + public string? OwnerName { get; set; } + public string? OwnerNnpn { get; set; } + public string? Color { get; set; } + public string? Model { get; set; } + public string? ManifactureYear { get; set; } + public string? PhoneNumber { get; set; } + public string? HeadType { get; set; } + public long? Tcscac { get; set; } + /// Temp ids returned by POST files/temp. + public List? AttachmentIds { get; set; } + /// Only honoured for users with action 107. On update: null = leave destinations untouched. + public TruckDestinationsRequest? Destinations { get; set; } +} + +[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] +public sealed class SaveTrailerRequest +{ + public string? Tn { get; set; } + public string? ChasesNumber { get; set; } + public long? Axials { get; set; } + public DateTime? RegDate { get; set; } + public string? OwnerName { get; set; } + public string? OwnerNnpn { get; set; } + public string? PhoneNumber { get; set; } + public long? Tcscac { get; set; } + /// The truck to connect the trailer to (legacy TNID). Optional. + public long? TruckId { get; set; } + public List? AttachmentIds { get; set; } +} + +[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] +public sealed class SaveDriverRequest +{ + public string? Nnpn { get; set; } + public string? Name { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } + public string? Nat { get; set; } + public string? Cat { get; set; } + public string? Mobile1 { get; set; } + public string? Mobile2 { get; set; } + public List? AttachmentIds { get; set; } +} + +[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] +public sealed class AddBlacklistRequest +{ + /// PERMIT (default, the only value the legacy page sends), DRIVERNUMBER, TRUCKNUMBER, TRAILERNUMBER. + public string? EntityType { get; set; } + /// Permit number (PN), or the permit id when ; the number for the other entity types. + public string? EntityNum { get; set; } + public bool IsId { get; set; } + public string? Category { get; set; } + /// Number of days (legacy EXPIRYDATE select: 1,2,3,4,5,10,14,30). + public int ExpiryDays { get; set; } + public string? Remarks { get; set; } +} + +public sealed class CancelBlacklistRequest +{ + public string? Remarks { get; set; } +} + +public sealed record BlacklistAddedDto(string Message, long BlacklistId, DateTime ExpiryDate); + +[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] +public sealed class SaveWeighbridgeControlRequest +{ + public string? Tn { get; set; } + public long? LocationId { get; set; } + public string? Notes { get; set; } + public DateTime? ExpiryDate { get; set; } +} + +public sealed class SaveGrainsWeightsRequest +{ + public string? Pn { get; set; } + public string? EmptyWeight { get; set; } + public string? GrossWeight { get; set; } + public string? DocumentNumber { get; set; } +} + +[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] +public sealed class FleetCheckRequest +{ + public long Tn { get; set; } + public long Scac { get; set; } +} + +public sealed record FleetCheckResult(bool Allowed, string? Message, int TotalFleet, int Turn); + +// ------------------------------------------------------------------ permit-screen lookups (grains.cfc) + +public sealed class LocationTruckCountDto +{ + public string? Loc { get; set; } + public long Cnt { get; set; } +} + +public sealed class DriverFromPermitDto +{ + public string? Drvr { get; set; } + public string? Cat { get; set; } + public DateTime? Dled { get; set; } + public string? Dln { get; set; } + public string? Nat { get; set; } +} + +public sealed class TruckFromPermitDto +{ + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Trnat { get; set; } + public string? Tt { get; set; } + public string? Drvr { get; set; } + public string? Cat { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } + public string? Nat { get; set; } + public string? Nnpn { get; set; } + public long? RoutingTemplateId { get; set; } + public long? OriginAddressId { get; set; } + public long? DestinationAddressId { get; set; } + public string? Firms { get; set; } + public string? Asrn { get; set; } + public string? Can { get; set; } + public string? CanName { get; set; } +} + +public sealed class TrailerInUseDto +{ + public string? Pn { get; set; } + public string? CreationDate { get; set; } +} + +public sealed class PermitByTruckDto +{ + public long Id { get; set; } + public string? Drvr { get; set; } + public string? Tn { get; set; } + public string? Pn { get; set; } + public string? ShipmentStatusCode { get; set; } +} + +public sealed class TruckInfoForPermitDto +{ + public string? Message { get; set; } + public bool CloseModal { get; set; } + public string? Tn { get; set; } + public string? ChasesNumber { get; set; } + public string? Axials { get; set; } + public DateTime? RegDate { get; set; } +} + +public sealed class TrailerInfoForPermitDto +{ + public string? Message { get; set; } + public string? ChasesNumber { get; set; } + public string? Axials { get; set; } + public DateTime? RegDate { get; set; } +} + +public sealed class DriverInfoForPermitDto +{ + public string? Name { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } +} + +public sealed class TrailerOfTruckDto +{ + public long TrailerId { get; set; } + public string? TrailerNumber { get; set; } +} diff --git a/src/NTP.Application/Grains/Registry/RegistryLookupService.cs b/src/NTP.Application/Grains/Registry/RegistryLookupService.cs new file mode 100644 index 0000000..c7c4019 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/RegistryLookupService.cs @@ -0,0 +1,142 @@ +using NTP.Application.Abstractions; +using NTP.Application.Common; + +namespace NTP.Application.Grains.Registry; + +public interface IRegistryLookupService +{ + Task PermissionsAsync(CancellationToken ct); + Task> CompaniesAsync(CancellationToken ct); + Task> TruckKindsAsync(IReadOnlyList kinds, CancellationToken ct); + Task DestinationsAsync(CancellationToken ct); + Task> DriverNationalitiesAsync(CancellationToken ct); + Task> WeighbridgeLocationsAsync(CancellationToken ct); + + // grains.cfc permit-screen lookups + Task DriverFromPermitsAsync(string nnpn, CancellationToken ct); + Task TruckFromPermitsAsync(string tn, CancellationToken ct); + Task> TrailerInUseAsync(string trn, long? exceptPermitId, CancellationToken ct); + Task PermitByTruckAsync(string tn, string status, CancellationToken ct); + Task TrailerNumberOfTruckAsync(string tn, CancellationToken ct); + Task TruckInfoAsync(string tn, bool validate, CancellationToken ct); + Task TrailerInfoAsync(string trn, CancellationToken ct); + Task DriverInfoAsync(string nnpn, CancellationToken ct); + + // MOT (register.cfc validateTNMOT / validateTRNMOT / validateOwnerTN) + Task ValidateTruckMotAsync(string tn, long scac, string? truckType, CancellationToken ct); + Task ValidateTrailerMotAsync(string trn, long scac, CancellationToken ct); + Task ValidateOwnerAsync(long companyScac, string tn, CancellationToken ct); +} + +public sealed class RegistryLookupService( + IRegistryRepository repository, + IRegistryOpsRepository ops, + IRegistryAccessService access, + IRegistrySettingsService settings, + ICurrentUser user) : IRegistryLookupService +{ + public Task PermissionsAsync(CancellationToken ct) => access.GetPermissionsAsync(ct); + + public Task> CompaniesAsync(CancellationToken ct) => repository.GetTenderCompaniesAsync(ct); + + public Task> TruckKindsAsync(IReadOnlyList kinds, CancellationToken ct) => + repository.GetTruckKindsAsync(kinds.Select(k => k.Trim()).Where(k => k.Length > 0).Distinct().Take(10).ToList(), ct); + + public async Task DestinationsAsync(CancellationToken ct) => new() + { + Packed = await repository.GetDestinationLocationsAsync("PCKD", ct), + Bulk = await repository.GetDestinationLocationsAsync("BULK", ct), + BulkGallab = await repository.GetDestinationLocationsAsync("BULK_GALLAB", ct) + }; + + public Task> DriverNationalitiesAsync(CancellationToken ct) => repository.GetDriverNationalitiesAsync(ct); + + public Task> WeighbridgeLocationsAsync(CancellationToken ct) => + repository.GetLocationsByIdsAsync(RegistryOpsService.WeighbridgeLocationIds, ct); + + public Task DriverFromPermitsAsync(string nnpn, CancellationToken ct) => + ops.GetDriverFromPermitsAsync(nnpn.Trim(), user.Domain, ct); + + public Task TruckFromPermitsAsync(string tn, CancellationToken ct) => + string.IsNullOrWhiteSpace(tn) ? Task.FromResult(null) : ops.GetTruckFromPermitsAsync(tn.Trim(), user.Domain, ct); + + public Task> TrailerInUseAsync(string trn, long? exceptPermitId, CancellationToken ct) => + ops.GetTrailerInUseAsync(trn.Trim(), exceptPermitId is > 0 ? exceptPermitId : null, user.Domain, ct); + + public Task PermitByTruckAsync(string tn, string status, CancellationToken ct) => + ops.GetPermitByTruckAsync(tn.Trim(), status.Trim(), ct); + + public async Task TrailerNumberOfTruckAsync(string tn, CancellationToken ct) => + new() { TrailerNumber = await ops.GetTrailerNumberOfTruckAsync(tn.Trim(), settings.AllowedTruckStatuses, ct) }; + + // ------------------------------------------------------------------ getTNinfo + + public async Task TruckInfoAsync(string tn, bool validate, CancellationToken ct) + { + tn = tn.Trim(); + var scac = access.CompanyCodeNo; + if (validate) + { + var owner = scac is null ? RegistryMessages.TruckNotFound : await ValidateOwnerAsync(scac.Value, tn, ct); + if (owner.Length > 0) return new TruckInfoForPermitDto { Message = owner }; + + var mot = scac is null ? RegistryRules.MotNotRegistered : await ValidateTruckMotAsync(tn, scac.Value, null, ct); + if (mot == RegistryRules.MotNotRegistered) + return new TruckInfoForPermitDto { Message = RegistryMessages.TruckNotInMot, CloseModal = true }; + if (mot == RegistryRules.MotWrongType) + return new TruckInfoForPermitDto { Message = RegistryMessages.WrongType }; + } + + var info = await ops.GetTruckInfoAsync(tn, access.Scope, ct); + return info is null + ? new TruckInfoForPermitDto { Tn = string.Empty, ChasesNumber = string.Empty, Axials = string.Empty } + : new TruckInfoForPermitDto { Tn = tn, ChasesNumber = info.Value.ChasesNumber, Axials = info.Value.Axials, RegDate = info.Value.RegDate }; + } + + // ------------------------------------------------------------------ getTRNinfo + + public async Task TrailerInfoAsync(string trn, CancellationToken ct) + { + trn = trn.Trim(); + // a company user may only use trailers of its own company + var scac = await ops.GetActiveTrailerScacAsync(trn, ct); + if (access.IsCompanyUser && scac != access.CompanyCodeNo) + return new TrailerInfoForPermitDto { Message = RegistryMessages.TrailerNotInCompany }; + + var info = await ops.GetTrailerInfoAsync(trn, access.Scope, ct); + return new TrailerInfoForPermitDto + { + Message = string.Empty, + ChasesNumber = info?.ChasesNumber, + Axials = info?.Axials, + RegDate = info?.RegDate + }; + } + + // ------------------------------------------------------------------ getDRVRinfo + + public async Task DriverInfoAsync(string nnpn, CancellationToken ct) + { + var info = await ops.GetDriverInfoAsync(nnpn.Trim(), ct); + return info is null + ? new DriverInfoForPermitDto() + : new DriverInfoForPermitDto { Name = info.Value.Name, Dln = info.Value.Dln, Dled = info.Value.Dled }; + } + + // ------------------------------------------------------------------ MOT + + public async Task ValidateTruckMotAsync(string tn, long scac, string? truckType, CancellationToken ct) + { + var types = await ops.GetMotTruckTypesAsync(tn.Trim(), scac, ct); + return RegistryRules.MotTruckValidation(types, string.IsNullOrWhiteSpace(truckType) ? RegistryRules.DefaultTruckType : truckType.Trim()); + } + + public async Task ValidateTrailerMotAsync(string trn, long scac, CancellationToken ct) => + RegistryRules.MotTrailerValidation(await ops.CountMotTrailerRowsAsync(trn.Trim(), scac, ct)); + + public async Task ValidateOwnerAsync(long companyScac, string tn, CancellationToken ct) + { + var code = await ops.GetMotOwnershipCodeAsync(tn.Trim(), companyScac, ct); + return RegistryRules.ValidateOwnership(code, companyScac, settings.BadiyaScac, settings.BadiyaOwnershipCodes, settings.OthersOwnershipCodes); + } +} diff --git a/src/NTP.Application/Grains/Registry/RegistryOpsService.cs b/src/NTP.Application/Grains/Registry/RegistryOpsService.cs new file mode 100644 index 0000000..bdd6317 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/RegistryOpsService.cs @@ -0,0 +1,109 @@ +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +public interface IRegistryOpsService +{ + Task SaveWeighbridgeControlAsync(SaveWeighbridgeControlRequest request, CancellationToken ct); + Task SaveGrainsWeightsAsync(SaveGrainsWeightsRequest request, CancellationToken ct); + Task CheckTrucksAsync(FleetCheckRequest request, CancellationToken ct); + Task ValidateNtpTruckAsync(string tn, CancellationToken ct); + Task> LocationTruckCountsAsync(CancellationToken ct); +} + +/// +/// Port of register.cfc saveWeighbridgesControlInfo and grains.cfc saveGrainsWeights / checkTrucks / validateNtpTrucks / getlocTruckNum. +/// +public sealed class RegistryOpsService( + IRegistryOpsRepository repository, + IEventLogger events, + IRegistrySettingsService settings, + IUnitOfWork unitOfWork, + ICurrentUser user) : IRegistryOpsService +{ + /// The weighbridge exception screen only offers these locations (WeighbridgesControl.cfm: ID in(215,220,225)). + public static readonly long[] WeighbridgeLocationIds = [215, 220, 225]; + + public async Task SaveWeighbridgeControlAsync(SaveWeighbridgeControlRequest request, CancellationToken ct) + { + RegistryValidation.ThrowIfAny(RegistryValidation.ValidateWeighbridge(request)); + if (!WeighbridgeLocationIds.Contains(request.LocationId!.Value)) + throw new BusinessException(RegistryErrors.InvalidInput, RegistryMessages.RequiredFields); + + var truckId = await repository.FindOpenOrAcceptedTruckIdAsync(request.Tn!.Trim(), ct) + ?? throw new BusinessException(RegistryErrors.WeighbridgeTruckWrong, RegistryMessages.WeighbridgeTruckWrong); + + await repository.InsertWeighbridgeControlAsync(truckId, request.LocationId.Value, request.Notes?.Trim(), user.UserId, request.ExpiryDate!.Value.Date, ct); + return new RegistryResult(RegistryMessages.Done, truckId); + } + + public async Task SaveGrainsWeightsAsync(SaveGrainsWeightsRequest request, CancellationToken ct) + { + var pn = request.Pn?.Trim(); + if (string.IsNullOrEmpty(pn) || string.IsNullOrWhiteSpace(request.EmptyWeight) || string.IsNullOrWhiteSpace(request.GrossWeight)) + throw new BusinessException(RegistryErrors.InvalidInput, RegistryMessages.RequiredFields); + // legacy: (the second operand repeats EMPTY_WEIGHT) + if (request.EmptyWeight.Trim().Length < 5) + throw new BusinessException(RegistryErrors.WeightLength, RegistryMessages.WeightLength); + + var empty = request.EmptyWeight.Trim(); + var gross = request.GrossWeight.Trim(); + var document = request.DocumentNumber?.Trim() ?? string.Empty; + + var permit = await repository.FindPermitByNumberAsync(pn, ct) + ?? throw new BusinessException(RegistryErrors.PermitNotFound, RegistryMessages.PermitNotFound(pn)); + + await unitOfWork.ExecuteInTransactionAsync(async token => + { + var existing = await repository.FindWeightRowAsync(permit.Id, token); + if (existing is not null) + await repository.UpdateWeightsAsync(existing.Value, empty, gross, document, user.UserId, token); + else + await repository.InsertWeightsAsync(empty, gross, document, permit.Id, user.UserId, token); + + // EVENTS: ADD_WEIGHTS with the weights in REMARKS (status unchanged) + var remarks = $"الوزن القائم: {gross} الوزن الفارغ: {empty}"; + await events.AddAsync(new EventEntry("PERMITID", permit.Id, permit.Status, permit.Status, user.UserId, "ADD_WEIGHTS", + RegistryConstants.Domain, string.Empty, "NTP", null, + new Dictionary { ["REMARKS"] = remarks }), token); + return true; + }, ct); + + return new RegistryResult(RegistryMessages.Done, permit.Id); + } + + public async Task CheckTrucksAsync(FleetCheckRequest request, CancellationToken ct) + { + var fleet = await repository.CountActiveFleetAsync(request.Scac, ct); + var turns = await repository.CountActiveTurnRowsAsync(request.Scac, ct) + 1; + var inTurn = fleet >= turns && await repository.TruckInTurnAsync(request.Scac, request.Tn, ct); + + var decision = RegistryRules.FleetDecision(fleet, turns, inTurn); + switch (decision) + { + case RegistryRules.FleetAction.Duplicate: + return new FleetCheckResult(false, RegistryMessages.DuplicateTruckInFleet, fleet, turns); + case RegistryRules.FleetAction.RecordTurn: + case RegistryRules.FleetAction.RecordTurnAndReset: + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.InsertTurnRowAsync(request.Scac, request.Tn, user.UserId, token); + // last truck of the fleet: close the turn so a new one can start + if (decision == RegistryRules.FleetAction.RecordTurnAndReset) + await repository.ResetTurnRowsAsync(request.Scac, token); + return true; + }, ct); + return new FleetCheckResult(true, "done", fleet, turns); + default: + return new FleetCheckResult(true, null, fleet, turns); + } + } + + public Task ValidateNtpTruckAsync(string tn, CancellationToken ct) => + repository.IsValidBadiyaTruckAsync(tn.Trim(), settings.BadiyaScac, ct); + + public Task> LocationTruckCountsAsync(CancellationToken ct) => + repository.GetLocationTruckCountsAsync(ct); +} diff --git a/src/NTP.Application/Grains/Registry/RegistryQueuePermitService.cs b/src/NTP.Application/Grains/Registry/RegistryQueuePermitService.cs new file mode 100644 index 0000000..efa2728 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/RegistryQueuePermitService.cs @@ -0,0 +1,66 @@ +using NTP.Application.Abstractions; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +public interface IRegistryQueuePermitService +{ + /// + /// Port of ws.cfc createPermitRecord (OPEN queue permit of a registered truck). Like the legacy function it answers with a + /// message string (the callers ignore it) instead of throwing for "truck not registered" / "already queued". + /// + Task CreatePermitRecordAsync(string tn, long scac, string nextStatus, string tt, bool checkStatuses, CancellationToken ct = default); + + /// jobs\RegisterGrainsQueueForNewTrucks.cfm: PCKD + BULK queue permits for 327 trucks that have none. Returns the truck count. + Task RegisterQueueForNewTrucksAsync(CancellationToken ct = default); +} + +public sealed class RegistryQueuePermitService( + IRegistryQueuePermitRepository repository, + IEventLogger events, + IUnitOfWork unitOfWork, + IRegistrySettingsService settings) : IRegistryQueuePermitService +{ + public async Task CreatePermitRecordAsync(string tn, long scac, string nextStatus, string tt, bool checkStatuses, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(nextStatus)) nextStatus = RegistryStatus.Open; + + if (!string.IsNullOrWhiteSpace(tn)) + { + if (!await repository.IsOpenOrAcceptedGnTruckAsync(tn, ct)) + return $"القاطرة رقم: {tn} غير مسجلة "; + if (await repository.HasActivePermitAsync(tn, tt, checkStatuses, ct)) + return $"القاطره رقم: {tn} ، لها دور فعّال "; + } + + var badiya = scac == settings.BadiyaScac; + var seq = await repository.NextTrackingNumberAsync(badiya, ct); + long? tripCounter = badiya ? await repository.NextTripCounterAsync(tt, settings.BadiyaScac, ct) : null; + + var tenderCount = await repository.GetMaxTenderIdAsync(ct); + var pn = RegistryRules.GeneratePermitNumber(tt, seq, scac, tenderCount, settings.BadiyaScac); + + var permitId = await repository.InsertPermitAsync(pn, tn, scac, nextStatus, tt, tripCounter, ct); + + // legacy: addEvent('PERMITID', id, '', NEXTSTATUS, 'SYSTEM', 'OVRD', 'GN', '', 'NTP') + await events.AddAsync(new EventEntry("PERMITID", permitId, string.Empty, nextStatus, "SYSTEM", "OVRD", RegistryConstants.Domain, string.Empty, "NTP"), ct); + + return "تمت العملية بنجاح ورقم الإرسالية هو : " + pn; + } + + public async Task RegisterQueueForNewTrucksAsync(CancellationToken ct = default) + { + var trucks = await repository.GetBadiyaTrucksWithoutPermitsAsync(settings.BadiyaScac, ct); + foreach (var tn in trucks) + { + var truck = tn.Trim(); + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await CreatePermitRecordAsync(truck, settings.BadiyaScac, RegistryStatus.Open, "PCKD", true, token); + await CreatePermitRecordAsync(truck, settings.BadiyaScac, RegistryStatus.Open, "BULK", true, token); + return true; + }, ct); + } + return trucks.Count; + } +} diff --git a/src/NTP.Application/Grains/Registry/RegistryRules.cs b/src/NTP.Application/Grains/Registry/RegistryRules.cs new file mode 100644 index 0000000..c683939 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/RegistryRules.cs @@ -0,0 +1,266 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +/// Stable error codes of the registry slice (ProblemDetails extension "code"). +public static class RegistryErrors +{ + public const string TruckDuplicate = "REGISTRY_TRUCK_DUPLICATE"; + public const string TrailerDuplicate = "REGISTRY_TRAILER_DUPLICATE"; + public const string DriverDuplicate = "REGISTRY_DRIVER_DUPLICATE"; + public const string DriverAlreadyActive = "REGISTRY_DRIVER_ALREADY_ACTIVE"; + public const string TruckHasTrailer = "REGISTRY_TRUCK_HAS_TRAILER"; + public const string NotFound = "REGISTRY_NOT_FOUND"; + public const string InvalidState = "REGISTRY_INVALID_STATE"; + public const string Forbidden = "REGISTRY_FORBIDDEN"; + public const string AttachmentsIncomplete = "REGISTRY_ATTACHMENTS_INCOMPLETE"; + public const string AttachmentMissing = "REGISTRY_ATTACHMENT_MISSING"; + public const string InvalidInput = "REGISTRY_INVALID_INPUT"; + public const string WeighbridgeTruckWrong = "REGISTRY_WEIGHBRIDGE_TRUCK_WRONG"; + public const string WeightLength = "REGISTRY_WEIGHT_LENGTH"; + public const string PermitNotFound = "REGISTRY_PERMIT_NOT_FOUND"; + public const string BlacklistNotOpen = "REGISTRY_BLACKLIST_NOT_OPEN"; + public const string TruckOwnership = "REGISTRY_TRUCK_OWNERSHIP"; + public const string TruckNotInMot = "REGISTRY_TRUCK_NOT_IN_MOT"; + public const string TruckWrongType = "REGISTRY_TRUCK_WRONG_TYPE"; + public const string TrailerNotInCompany = "REGISTRY_TRAILER_NOT_IN_COMPANY"; +} + +/// Legacy Arabic user messages (register.cfc / grains.cfc), kept verbatim. +public static class RegistryMessages +{ + public const string TruckDuplicate = "رقم القاطرة مضاف مسبقا"; + public const string TrailerDuplicate = "رقم المقطورة مضاف مسبقا"; + public const string DriverDuplicate = "رقم السائق مضاف مسبقا"; + public const string DriverAlreadyActive = "السائق مفعل مسبقا"; + public const string TruckHasTrailer = "ثمة مقطورة أخرى مرتبطة بالقاطرة، لا تستطيع إضافة مقطورة جديدة "; + public const string TruckAddedAwaitingTrailer = "تمت اضافة قاطرة بحالة بانتظار التسجيل يجب اضافة مقطورة"; + public const string Done = "تمت العملية بنجاح"; + public const string Revoked = "تمت عملية الإلغاء بنجاح"; + public const string Accepted = "تمت عملية التفعيل بنجاح"; + public const string AttachmentsIncomplete = "الملفات المرفقة غير مكتملة"; + public const string RequiredFields = "الرجاء إدخال المعلومات المطلوبة"; + public const string InvalidDate = "الرجاء إدخال التاريخ بالشكل الصحيح"; + public const string SpecialChars = "لا يجوز ادخال حروف خاصة"; + public const string InvalidNumber = "الرجاء إدخال الرقم بالشكل الصحيح"; + public const string WeighbridgeTruckWrong = "رقم القاطرة خاطئ"; + public const string WeightLength = "يجب ان يكون الوزن من 5 خانات"; + public const string BlacklistAdded = "تمت الاضافة بنجاح"; + public const string TruckNotFound = "القاطرة غير موجودة "; + public const string OwnershipNotAllowed = "لا يجوز اضافة سيارات الاهالي على الشركات"; + public const string TruckNotInMot = "خطأ في تسجيل السيارة/ السيارة غير مؤتلفة"; + public const string WrongType = "النمط غير صحيح"; + public const string TrailerNotInCompany = "هذه المقطورة ليست ضمن مقطورات الشركة"; + public const string DuplicateTruckInFleet = "هذه الشاحنة مكررة، لا تستطيع تسجيلها مرتين"; + public const string Forbidden = "غير مصرح لك بتنفيذ هذه العملية"; + public const string NotFound = "السجل غير موجود"; + public const string OnlyRevokedNotEditable = "لا يمكن تعديل سجل ملغي"; + public const string NotAcceptable = "لا يمكن تفعيل السجل بحالته الحالية"; + public const string AlreadyRevoked = "السجل ملغي مسبقا"; + public const string BlacklistNotOpen = "الحظر غير فعّال"; + + public static string YearRange(int currentYear) => $"سنة الصنع يجب ان تكون بين 1960 - {currentYear + 1}"; + public static string PermitNotFound(string pn) => $"الإرسالية {pn} غير موجودة"; +} + +/// Legacy status captions (register.cfc OPEN_caption ...). +public static class RegistryRules +{ + public const int FirstManufactureYear = 1960; + + public static string? StatusCaption(string? statusCode, string? fallback = null) => statusCode switch + { + RegistryStatus.Open => "جديد", + RegistryStatus.Accpt => "مرخص", + RegistryStatus.Rvkd => "ملغي", + RegistryStatus.RegReqst => "بانتظار التسجيل", + RegistryStatus.Incomp => "غير مكتمل", + _ => fallback ?? statusCode + }; + + public static string? BlacklistStatusCaption(string? code) => code switch + { + BlacklistValues.Open => "فعال", + BlacklistValues.Deleted => "ملغي", + BlacklistValues.Expired => "منتهي", + _ => null + }; + + public static string? BlacklistCategoryCaption(string? code) => code switch + { + BlacklistValues.CategoryPhoneDecline => "منع", + BlacklistValues.CategoryWaitingList => "انتظار", + _ => null + }; + + public static string? BlacklistEntityCaption(string? code) => code switch + { + BlacklistValues.EntityDriver => "السائق", + BlacklistValues.EntityTruck => "القاطرة", + BlacklistValues.EntityTrailer => "المقطورة", + BlacklistValues.EntityPermit => "الارسالية", + _ => null + }; + + // ---------------------------------------------------------------- status transitions + + /// The accept button is hidden for ACCPT and RVKD records (registerGrains*.cfm, regesterDriver.cfm). + public static bool CanAccept(string? status) => + !string.Equals(status, RegistryStatus.Accpt, StringComparison.OrdinalIgnoreCase) && + !string.Equals(status, RegistryStatus.Rvkd, StringComparison.OrdinalIgnoreCase); + + /// The revoke button is hidden for RVKD records. + public static bool CanRevoke(string? status) => + !string.Equals(status, RegistryStatus.Rvkd, StringComparison.OrdinalIgnoreCase); + + /// The edit button is hidden for RVKD records. + public static bool CanEdit(string? status) => + !string.Equals(status, RegistryStatus.Rvkd, StringComparison.OrdinalIgnoreCase); + + /// + /// Status written by editTrucksDetails: company 327 keeps REGREQST (and otherwise leaves the status alone, + /// returns null), every other company is set to OPEN. + /// + public static string? StatusAfterTruckEdit(long? tcscac, string currentStatus, long badiyaScac) + { + if (tcscac == badiyaScac) + return string.Equals(currentStatus, RegistryStatus.RegReqst, StringComparison.OrdinalIgnoreCase) + ? RegistryStatus.RegReqst + : null; + return RegistryStatus.Open; + } + + // ---------------------------------------------------------------- field rules + + // The legacy validateSpecialChars character class (formchek.js). + private static readonly Regex SpecialCharsRegex = new("""[!,@#$%+\-*^&<>{}:";'\\/_)(=|~.`\[\]?]""", RegexOptions.Compiled); + + /// formchek.js validateSpecialChars: true when the text contains a forbidden special character. + public static bool HasSpecialChars(string? text) => !string.IsNullOrEmpty(text) && SpecialCharsRegex.IsMatch(text); + + /// Manufacture year 1960 .. current year + 1 (isyearWithinRange). + public static bool IsYearWithinRange(string? year, int currentYear) => + int.TryParse(year?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var y) + && y >= FirstManufactureYear && y <= currentYear + 1; + + public static bool IsDigits(string? s, int maxLength) => + !string.IsNullOrEmpty(s) && s.Length <= maxLength && s.All(char.IsAsciiDigit); + + /// Truck kind radio of the legacy truck form: AXIALS < 7 -> S (single) else T (tractor head). + public static string? TruckKindOfAxials(long? axials) => axials is null ? null : axials < 7 ? "S" : "T"; + + /// Trailer kind radio of the legacy trailer form: AXIALS < 12 -> TR else HTR (half trailer). + public static string? TrailerKindOfAxials(long? axials) => axials is null ? null : axials < 12 ? "TR" : "HTR"; + + /// numberFormat(value, '000..') of ColdFusion: left pad with zeros, never truncates. + public static string PadNumber(long value, int width) => value.ToString(CultureInfo.InvariantCulture).PadLeft(width, '0'); + + // ---------------------------------------------------------------- attachments + + /// + /// Legacy pages refuse to save when fewer than 2 files are attached (license + identity): + /// trailer of company 327, every driver. counts files of the record already saved (edit). + /// + public static bool HasEnoughAttachments(int newFiles, int alreadyStored, int required = 2) => newFiles + alreadyStored >= required; + + // ---------------------------------------------------------------- blacklist + + public static readonly int[] BlacklistDays = [1, 2, 3, 4, 5, 10, 14, 30]; + + public static bool IsBlacklistCategory(string? c) => + c is BlacklistValues.CategoryPhoneDecline or BlacklistValues.CategoryWaitingList; + + public static bool IsBlacklistEntityType(string? t) => + t is BlacklistValues.EntityPermit or BlacklistValues.EntityDriver or BlacklistValues.EntityTruck or BlacklistValues.EntityTrailer; + + /// + /// BL_addToBlacklist expiry: trunc(sysdate - (24 + shiftStart)/24) + days + shiftEnd/24 + /// (shift hours come from application['grnsdtrbutnshft_N'] = "start,end"). + /// + public static DateTime BlacklistExpiry(DateTime now, int days, int shiftStartHour, int shiftEndHour) => + now.AddHours(-(24 + shiftStartHour)).Date.AddDays(days).AddHours(shiftEndHour); + + /// Remarks text stored with the entry (legacy appends the automatic release date, mm/dd/yyyy HH:mm). + public static string BlacklistRemarks(string? remarks, DateTime expiry) => + $"{remarks}، سيتم فك الانتظار بشكل تلقائي بتاريخ {expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)}"; + + /// Parses the legacy "start,end" application setting; falls back to the defaults. + public static (int Start, int End) ParseShiftHours(string? setting, int defaultStart = 0, int defaultEnd = 24) + { + var parts = (setting ?? string.Empty).Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); + if (parts.Length >= 2 + && int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var s) + && int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var e)) + return (s, e); + return (defaultStart, defaultEnd); + } + + // ---------------------------------------------------------------- MOT / ownership (register.cfc validateOwnerTN, validateTNMOT, validateTRNMOT) + + /// validateOwnerTN: empty string = ok, otherwise the legacy Arabic error. + public static string ValidateOwnership( + string? ownershipCode, long companyScac, long badiyaScac, + IReadOnlyCollection badiyaOwnership, IReadOnlyCollection othersOwnership) + { + if (ownershipCode is null) return RegistryMessages.TruckNotFound; + var codes = companyScac == badiyaScac ? badiyaOwnership : othersOwnership; + // The legacy lists live in application settings that are not in the repo: when none is configured the check is skipped. + if (codes.Count == 0) return string.Empty; + return codes.Contains(ownershipCode, StringComparer.OrdinalIgnoreCase) ? string.Empty : RegistryMessages.OwnershipNotAllowed; + } + + public const string MotNotRegistered = "not_registered"; + public const string MotWrongType = "wrongCT"; + public const string DefaultTruckType = "trucktype.general.cargo"; + + /// validateTNMOT result: '' ok, 'not_registered' (no MOT record), 'wrongCT' (type not general cargo / all). + public static string MotTruckValidation(IReadOnlyCollection truckTypeCodes, string requestedType = DefaultTruckType) + { + if (truckTypeCodes.Count == 0) return MotNotRegistered; + var ok = truckTypeCodes.Any(c => + string.Equals(c, requestedType, StringComparison.OrdinalIgnoreCase) || + string.Equals(c, "trucktype.all", StringComparison.OrdinalIgnoreCase)); + return ok ? string.Empty : MotWrongType; + } + + /// validateTRNMOT result: '' ok or 'not_registered'. + public static string MotTrailerValidation(int matchingRows) => matchingRows == 0 ? MotNotRegistered : string.Empty; + + // ---------------------------------------------------------------- fleet turns (grains.cfc checkTrucks) + + public enum FleetAction { Allow, Duplicate, RecordTurn, RecordTurnAndReset } + + /// + /// checkTrucks: every company must use all its trucks before reusing one. = active rows + 1. + /// fleet < turns -> allowed without recording; duplicate in this turn -> refused; otherwise record the truck and, if it + /// was the last truck of the fleet, reset the turn (all active rows -> status 0). + /// + public static FleetAction FleetDecision(int totalFleet, int turns, bool truckAlreadyInTurn) + { + if (totalFleet < turns) return FleetAction.Allow; + if (truckAlreadyInTurn) return FleetAction.Duplicate; + return totalFleet == turns ? FleetAction.RecordTurnAndReset : FleetAction.RecordTurn; + } + + // ---------------------------------------------------------------- permit number (grains.cfc generatePermitNumber) + + /// Port of generatePermitNumber (the permit created for a registered truck). Empty for unknown types. + public static string GeneratePermitNumber(string tt, long seq, long companyCode, long tenderCount, long badiyaScac) + { + var bulk = string.Equals(tt, "BULK", StringComparison.OrdinalIgnoreCase); + var pckd = string.Equals(tt, "PCKD", StringComparison.OrdinalIgnoreCase); + if (companyCode == badiyaScac) + { + if (bulk) return "30" + PadNumber(tenderCount, 2) + PadNumber(seq, 6); + if (pckd) return "3" + (41 + tenderCount).ToString(CultureInfo.InvariantCulture) + PadNumber(seq, 7); + } + else + { + if (bulk) return "1" + PadNumber(tenderCount, 2) + PadNumber(seq, 6); + if (pckd) return "1" + (41 + tenderCount).ToString(CultureInfo.InvariantCulture) + PadNumber(seq, 6); + } + return string.Empty; + } +} diff --git a/src/NTP.Application/Grains/Registry/RegistryValidation.cs b/src/NTP.Application/Grains/Registry/RegistryValidation.cs new file mode 100644 index 0000000..9b40607 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/RegistryValidation.cs @@ -0,0 +1,200 @@ +using FluentValidation; +using FluentValidation.Results; + +namespace NTP.Application.Grains.Registry; + +/// +/// Server-side port of the checks the legacy pages did in JavaScript before calling register.cfc +/// (validateFields Required / Date / SpecialChars, manufacture-year range, masks). Pure: returns the failures, +/// raises a FluentValidation (HTTP 400 with per-field errors). +/// +public static class RegistryValidation +{ + public static void ThrowIfAny(IReadOnlyList failures) + { + if (failures.Count > 0) throw new ValidationException(failures); + } + + private static void Required(List f, string field, object? value) + { + var empty = value switch + { + null => true, + string s => string.IsNullOrWhiteSpace(s), + _ => false + }; + if (empty) f.Add(new ValidationFailure(field, RegistryMessages.RequiredFields)); + } + + private static void MaxLen(List f, string field, string? value, int max) + { + if (value is not null && value.Trim().Length > max) + f.Add(new ValidationFailure(field, $"الحد الأقصى {max} خانة")); + } + + private static void NoSpecial(List f, string field, string? value) + { + if (RegistryRules.HasSpecialChars(value)) f.Add(new ValidationFailure(field, RegistryMessages.SpecialChars)); + } + + private static void Digits(List f, string field, string? value, int max) + { + if (!string.IsNullOrWhiteSpace(value) && !RegistryRules.IsDigits(value.Trim(), max)) + f.Add(new ValidationFailure(field, RegistryMessages.InvalidNumber)); + } + + // ------------------------------------------------------------------ truck (registerGrainsTruck.cfm saveTruck / editTruck) + + /// + /// = company of the truck (the form's company select; for an update the stored company). + /// Company 327 requires the full data set; every other company only the number (and axials on edit). + /// + public static IReadOnlyList ValidateTruck(SaveTruckRequest r, long? tcscac, bool isUpdate, long badiyaScac, int currentYear) + { + var f = new List(); + if (!isUpdate) + { + Required(f, nameof(r.Tn), r.Tn); + Digits(f, nameof(r.Tn), r.Tn, 12); + } + Required(f, nameof(r.Tcscac), tcscac); + + if (tcscac == badiyaScac) + { + Required(f, nameof(r.ChasesNumber), r.ChasesNumber); + Required(f, nameof(r.Axials), r.Axials); + Required(f, nameof(r.RegDate), r.RegDate); + Required(f, nameof(r.OwnerName), r.OwnerName); + Required(f, nameof(r.OwnerNnpn), r.OwnerNnpn); + Required(f, nameof(r.Color), r.Color); + Required(f, nameof(r.Model), r.Model); + Required(f, nameof(r.ManifactureYear), r.ManifactureYear); + Required(f, nameof(r.HeadType), r.HeadType); + NoSpecial(f, nameof(r.ChasesNumber), r.ChasesNumber); + NoSpecial(f, nameof(r.OwnerName), r.OwnerName); + NoSpecial(f, nameof(r.OwnerNnpn), r.OwnerNnpn); + if (!string.IsNullOrWhiteSpace(r.ManifactureYear) && !RegistryRules.IsYearWithinRange(r.ManifactureYear, currentYear)) + f.Add(new ValidationFailure(nameof(r.ManifactureYear), RegistryMessages.YearRange(currentYear))); + } + else + { + if (isUpdate) + { + // edit for the other companies: required '00,12,09' and the year must be in range (an empty year fails the legacy check) + Required(f, nameof(r.Axials), r.Axials); + if (!RegistryRules.IsYearWithinRange(r.ManifactureYear, currentYear)) + f.Add(new ValidationFailure(nameof(r.ManifactureYear), RegistryMessages.YearRange(currentYear))); + } + else if (!string.IsNullOrWhiteSpace(r.ManifactureYear) && !RegistryRules.IsYearWithinRange(r.ManifactureYear, currentYear)) + f.Add(new ValidationFailure(nameof(r.ManifactureYear), RegistryMessages.YearRange(currentYear))); + } + + 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, 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; + } + + // ------------------------------------------------------------------ trailer (registerGrainsTrailer.cfm saveTrailer / editTrailer) + + public static IReadOnlyList ValidateTrailer(SaveTrailerRequest r, long? tcscac, bool isUpdate, long badiyaScac) + { + var f = new List(); + if (!isUpdate) + { + Required(f, nameof(r.Tn), r.Tn); + Digits(f, nameof(r.Tn), r.Tn, 12); + } + Required(f, nameof(r.Tcscac), tcscac); + + // company 327 on create, every company on edit (editTrailer requires the full set) + if (isUpdate || tcscac == badiyaScac) + { + Required(f, nameof(r.ChasesNumber), r.ChasesNumber); + Required(f, nameof(r.RegDate), r.RegDate); + Required(f, nameof(r.Axials), r.Axials); + Required(f, nameof(r.OwnerName), r.OwnerName); + Required(f, nameof(r.OwnerNnpn), r.OwnerNnpn); + NoSpecial(f, nameof(r.ChasesNumber), r.ChasesNumber); + NoSpecial(f, nameof(r.OwnerName), r.OwnerName); + NoSpecial(f, nameof(r.OwnerNnpn), r.OwnerNnpn); + } + + 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.PhoneNumber), r.PhoneNumber, 10); + Digits(f, nameof(r.PhoneNumber), r.PhoneNumber, 10); + return f; + } + + // ------------------------------------------------------------------ driver (regesterDriver.cfm saveDriverDetails) + + public static IReadOnlyList ValidateDriver(SaveDriverRequest r) + { + var f = new List(); + Required(f, nameof(r.Nnpn), r.Nnpn); + Required(f, nameof(r.Name), r.Name); + Required(f, nameof(r.Dln), r.Dln); + Required(f, nameof(r.Dled), r.Dled); + Required(f, nameof(r.Nat), r.Nat); + Required(f, nameof(r.Cat), r.Cat); + Required(f, nameof(r.Mobile1), r.Mobile1); + NoSpecial(f, nameof(r.Name), r.Name); + NoSpecial(f, nameof(r.Nnpn), r.Nnpn); + MaxLen(f, nameof(r.Nnpn), r.Nnpn, 20); + MaxLen(f, nameof(r.Name), r.Name, 50); + Digits(f, nameof(r.Dln), r.Dln, 9); + Digits(f, nameof(r.Mobile1), r.Mobile1, 10); + Digits(f, nameof(r.Mobile2), r.Mobile2, 10); + if (!string.IsNullOrWhiteSpace(r.Cat) && !(r.Cat.Trim().Length == 1 && r.Cat.Trim()[0] is >= '1' and <= '6')) + f.Add(new ValidationFailure(nameof(r.Cat), RegistryMessages.InvalidNumber)); + return f; + } + + // ------------------------------------------------------------------ blacklist (createBlacklist.cfm, confirmDeleteBL.cfm) + + public static IReadOnlyList ValidateBlacklist(AddBlacklistRequest r) + { + var f = new List(); + var type = string.IsNullOrWhiteSpace(r.EntityType) ? NTP.Domain.Grains.Registry.BlacklistValues.EntityPermit : r.EntityType.Trim().ToUpperInvariant(); + Required(f, nameof(r.EntityNum), r.EntityNum); + if (!string.IsNullOrWhiteSpace(r.EntityNum) && !RegistryRules.IsDigits(r.EntityNum.Trim(), 18)) + f.Add(new ValidationFailure(nameof(r.EntityNum), RegistryMessages.InvalidNumber)); + if (!RegistryRules.IsBlacklistEntityType(type)) + f.Add(new ValidationFailure(nameof(r.EntityType), RegistryMessages.RequiredFields)); + if (!RegistryRules.IsBlacklistCategory(r.Category)) + f.Add(new ValidationFailure(nameof(r.Category), RegistryMessages.RequiredFields)); + if (!RegistryRules.BlacklistDays.Contains(r.ExpiryDays)) + f.Add(new ValidationFailure(nameof(r.ExpiryDays), RegistryMessages.RequiredFields)); + MaxLen(f, nameof(r.Remarks), r.Remarks, 400); + return f; + } + + public static IReadOnlyList ValidateCancelBlacklist(CancelBlacklistRequest r) + { + var f = new List(); + Required(f, nameof(r.Remarks), r.Remarks); + MaxLen(f, nameof(r.Remarks), r.Remarks, 400); + return f; + } + + // ------------------------------------------------------------------ weighbridge control (WeighbridgesControl.cfm) + + public static IReadOnlyList ValidateWeighbridge(SaveWeighbridgeControlRequest r) + { + var f = new List(); + Required(f, nameof(r.Tn), r.Tn); + Required(f, nameof(r.LocationId), r.LocationId); + Required(f, nameof(r.Notes), r.Notes); + Required(f, nameof(r.ExpiryDate), r.ExpiryDate); + MaxLen(f, nameof(r.Tn), r.Tn, 20); + MaxLen(f, nameof(r.Notes), r.Notes, 400); + return f; + } +} diff --git a/src/NTP.Application/Grains/Registry/TrailerRegistryService.cs b/src/NTP.Application/Grains/Registry/TrailerRegistryService.cs new file mode 100644 index 0000000..362825f --- /dev/null +++ b/src/NTP.Application/Grains/Registry/TrailerRegistryService.cs @@ -0,0 +1,200 @@ +using NTP.Application.Access; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +public interface ITrailerRegistryService +{ + Task> SearchAsync(TrailerListQuery query, PageRequest page, CancellationToken ct); + Task GetAsync(long id, CancellationToken ct); + Task CreateAsync(SaveTrailerRequest request, CancellationToken ct); + Task UpdateAsync(long id, SaveTrailerRequest request, CancellationToken ct); + Task AcceptAsync(long id, CancellationToken ct); + Task RevokeAsync(long id, CancellationToken ct); +} + +/// Port of register.cfc saveTrailerDetails / editTrailerDetails / getTrailerInfo / getTrailerGrid / revokeTrailer / acceptTrailer. +public sealed class TrailerRegistryService( + IRegistryRepository repository, + IRegistryAccessService access, + IRegistryAttachmentService attachments, + IRegistryQueuePermitService queuePermits, + IRegistrySettingsService settings, + IUnitOfWork unitOfWork, + ICurrentUser user) : ITrailerRegistryService +{ + public async Task> SearchAsync(TrailerListQuery query, PageRequest page, CancellationToken ct) + { + var scope = access.Scope; + var q = scope.CompanyOnly ? query with { Tcscac = null } : query; + var result = await repository.SearchTrailersAsync(scope, q, page, ct); + foreach (var r in result.Items) r.StatusCaption = RegistryRules.StatusCaption(r.StatusCode, r.StatusCaption); + return result; + } + + public async Task GetAsync(long id, CancellationToken ct) + { + var trailer = await repository.GetTrailerDetailAsync(id, ct) ?? throw new NotFoundException("Trailer", id); + access.EnsureCompanyAccess(trailer.Tcscac); + trailer.StatusCaption = RegistryRules.StatusCaption(trailer.StatusCode, trailer.StatusCaption); + trailer.AxialsKind = RegistryRules.TrailerKindOfAxials(trailer.Axials); + trailer.Attachments = await attachments.ListAsync(RegistryAttachmentService.KindTrailer, id, ct); + return trailer; + } + + public async Task CreateAsync(SaveTrailerRequest request, CancellationToken ct) + { + await access.RequireAuthorityAsync(PermissionKeys.RegistryTrailersCreate, ct); + + NtpTruck? truck = null; + long? tcscac; + if (request.TruckId is not null) + { + truck = await repository.GetTruckAsync(request.TruckId.Value, ct) ?? throw new NotFoundException("Truck", request.TruckId.Value); + access.EnsureCompanyAccess(truck.Tcscac); + if (!RegistryRules.CanEdit(truck.StatusCode)) + throw new BusinessException(RegistryErrors.InvalidState, RegistryMessages.OnlyRevokedNotEditable); + // the trailer form opened from a truck shows the truck's company (disabled select) + tcscac = truck.Tcscac; + } + else + { + tcscac = access.IsCompanyUser && access.CompanyCodeNo is not null ? access.CompanyCodeNo : request.Tcscac; + } + + RegistryValidation.ThrowIfAny(RegistryValidation.ValidateTrailer(request, tcscac, false, settings.BadiyaScac)); + var is327 = tcscac == settings.BadiyaScac; + var tn = request.Tn!.Trim(); + + // validateUniqueTRN + if (await repository.ActiveTrailerExistsAsync(tn, ct)) + throw new BusinessException(RegistryErrors.TrailerDuplicate, RegistryMessages.TrailerDuplicate); + + // one live trailer per truck + if (truck is not null && await repository.TruckHasNonRevokedTrailerAsync(truck.Id, ct)) + throw new BusinessException(RegistryErrors.TruckHasTrailer, RegistryMessages.TruckHasTrailer); + + var tempIds = await attachments.EnsureTempFilesAsync(request.AttachmentIds, ct); + // company 327: the legacy page refuses a save with fewer than 2 attached files (license + owner identity) + if (is327 && !RegistryRules.HasEnoughAttachments(tempIds.Count, 0)) + throw new BusinessException(RegistryErrors.AttachmentsIncomplete, RegistryMessages.AttachmentsIncomplete); + + var id = await unitOfWork.ExecuteInTransactionAsync(async token => + { + var trailer = new NtpTrailer + { + Tn = tn, + ChasesNumber = request.ChasesNumber?.Trim().ToUpperInvariant(), + RegDate = request.RegDate?.Date, + Axials = request.Axials, + StatusCode = RegistryStatus.Open, + OwnerName = Clean(request.OwnerName), + OwnerNnpn = Clean(request.OwnerNnpn), + PhoneNumber = Clean(request.PhoneNumber), + TnId = truck?.Id, + Tcscac = tcscac, + CreateUserId = user.UserId + }; + var newId = await repository.InsertTrailerAsync(trailer, token); + await attachments.AttachAsync(RegistryAttachmentService.KindTrailer, newId, tempIds, token); + + if (is327 && truck is not null) + { + // adding the trailer completes the truck: REGREQST -> OPEN, and the queue permits are created if it has none + var previousStatus = truck.StatusCode; + await repository.SetTruckStatusAsync(truck.Id, RegistryStatus.Open, user.UserId, token); + if (string.Equals(previousStatus, RegistryStatus.RegReqst, StringComparison.OrdinalIgnoreCase) + && !await repository.TruckHasGnPermitAsync(truck.Tn, token)) + { + await queuePermits.CreatePermitRecordAsync(truck.Tn, truck.Tcscac ?? settings.BadiyaScac, RegistryStatus.Open, "BULK", false, token); + await queuePermits.CreatePermitRecordAsync(truck.Tn, truck.Tcscac ?? settings.BadiyaScac, RegistryStatus.Open, "PCKD", false, token); + } + } + return newId; + }, ct); + + return new RegistryResult(RegistryMessages.Done, id); + } + + public async Task UpdateAsync(long id, SaveTrailerRequest request, CancellationToken ct) + { + await access.RequireAuthorityAsync(PermissionKeys.RegistryTrailersEdit, ct); + + var current = await repository.GetTrailerAsync(id, ct) ?? throw new NotFoundException("Trailer", id); + access.EnsureCompanyAccess(current.Tcscac); + if (!RegistryRules.CanEdit(current.StatusCode)) + throw new BusinessException(RegistryErrors.InvalidState, RegistryMessages.OnlyRevokedNotEditable); + + RegistryValidation.ThrowIfAny(RegistryValidation.ValidateTrailer(request, current.Tcscac, true, settings.BadiyaScac)); + + var tempIds = await attachments.EnsureTempFilesAsync(request.AttachmentIds, ct); + var stored = (await attachments.ListAsync(RegistryAttachmentService.KindTrailer, id, ct)).Count; + // legacy editTrailer: at least 2 attached files (it counted only the files added in that session; stored files count here) + if (!RegistryRules.HasEnoughAttachments(tempIds.Count, stored)) + throw new BusinessException(RegistryErrors.AttachmentsIncomplete, RegistryMessages.AttachmentsIncomplete); + + var is327 = current.Tcscac == settings.BadiyaScac; + await unitOfWork.ExecuteInTransactionAsync(async token => + { + var values = new NtpTrailer + { + RegDate = request.RegDate?.Date, + OwnerName = Clean(request.OwnerName), + OwnerNnpn = Clean(request.OwnerNnpn), + PhoneNumber = Clean(request.PhoneNumber), + ChasesNumber = request.ChasesNumber?.Trim().ToUpperInvariant(), + Axials = request.Axials + }; + // editTrailerDetails always writes STATUSCODE = 'OPEN'; the phone box is disabled for companies other than 327 + await repository.UpdateTrailerAsync(id, values, updatePhone: is327, user.UserId, token); + await attachments.AttachAsync(RegistryAttachmentService.KindTrailer, id, tempIds, token); + return true; + }, ct); + + return new RegistryResult(RegistryMessages.Done, id); + } + + public async Task AcceptAsync(long id, CancellationToken ct) + { + await access.RequireActionAsync(RegistryActions.AcceptTrailer, false, ct); + var trailer = await repository.GetTrailerAsync(id, ct) ?? throw new NotFoundException("Trailer", id); + access.EnsureCompanyAccess(trailer.Tcscac); + if (!RegistryRules.CanAccept(trailer.StatusCode)) + throw new BusinessException(RegistryErrors.InvalidState, RegistryMessages.NotAcceptable); + + // legacy also asks checkSULFPermit (returns false immediately, SULF check disabled) - nothing to do + await repository.AcceptTrailerAsync(id, user.UserId, ct); + return new RegistryResult(RegistryMessages.Accepted, id); + } + + public async Task RevokeAsync(long id, CancellationToken ct) + { + await access.RequireActionAsync(RegistryActions.RevokeTrailer, false, ct); + if (access.IsBadiyaCompany) + throw new ForbiddenException(RegistryErrors.Forbidden, RegistryMessages.Forbidden); // legacy hides the button for 327 + + var trailer = await repository.GetTrailerAsync(id, ct) ?? throw new NotFoundException("Trailer", id); + access.EnsureCompanyAccess(trailer.Tcscac); + if (!RegistryRules.CanRevoke(trailer.StatusCode)) + throw new BusinessException(RegistryErrors.InvalidState, RegistryMessages.AlreadyRevoked); + + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.RevokeTrailerAsync(id, user.UserId, token); + // the truck goes back to "awaiting registration" (was INCOMP until 30 Dec 2020) + if (trailer.TnId is not null) + { + var truck = await repository.GetTruckAsync(trailer.TnId.Value, token); + if (truck is not null && RegistryRules.CanRevoke(truck.StatusCode)) + await repository.SetTruckStatusAsync(truck.Id, RegistryStatus.RegReqst, user.UserId, token); + } + return true; + }, ct); + + return new RegistryResult(RegistryMessages.Revoked, id); + } + + private static string? Clean(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); +} diff --git a/src/NTP.Application/Grains/Registry/TruckRegistryService.cs b/src/NTP.Application/Grains/Registry/TruckRegistryService.cs new file mode 100644 index 0000000..daf4c66 --- /dev/null +++ b/src/NTP.Application/Grains/Registry/TruckRegistryService.cs @@ -0,0 +1,218 @@ +using NTP.Application.Access; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Grains.Registry; + +namespace NTP.Application.Grains.Registry; + +public interface ITruckRegistryService +{ + Task> SearchAsync(TruckListQuery query, PageRequest page, CancellationToken ct); + Task GetAsync(long id, CancellationToken ct); + Task> TrailersAsync(long? truckId, long? trailerId, CancellationToken ct); + Task CreateAsync(SaveTruckRequest request, CancellationToken ct); + Task UpdateAsync(long id, SaveTruckRequest request, CancellationToken ct); + Task AcceptAsync(long id, CancellationToken ct); + Task RevokeAsync(long id, CancellationToken ct); +} + +/// Port of register.cfc saveTrucksDetails / editTrucksDetails / getTruckInfo / getTruckGrid / revokeTruck / acceptTruck. +public sealed class TruckRegistryService( + IRegistryRepository repository, + IRegistryAccessService access, + IRegistryAttachmentService attachments, + IRegistryQueuePermitService queuePermits, + IRegistrySettingsService settings, + IUnitOfWork unitOfWork, + ICurrentUser user) : ITruckRegistryService +{ + public async Task> SearchAsync(TruckListQuery query, PageRequest page, CancellationToken ct) + { + var scope = access.Scope; + // company users only see their own company: a tcscac filter cannot widen that + var q = scope.CompanyOnly ? query with { Tcscac = null } : query; + var result = await repository.SearchTrucksAsync(scope, q, page, ct); + foreach (var r in result.Items) r.StatusCaption = RegistryRules.StatusCaption(r.StatusCode, r.StatusCaption); + return result; + } + + public async Task GetAsync(long id, CancellationToken ct) + { + var truck = await repository.GetTruckDetailAsync(id, ct) ?? throw new NotFoundException("Truck", id); + access.EnsureCompanyAccess(truck.Tcscac); + + truck.StatusCaption = RegistryRules.StatusCaption(truck.StatusCode, truck.StatusCaption); + truck.AxialsKind = RegistryRules.TruckKindOfAxials(truck.Axials); + + var trailer = await repository.GetLatestTrailerOfTruckAsync(id, ct); + truck.TrailerId = trailer?.Id; + truck.TrailerTn = trailer?.Tn; + + // destinations: users with action 107 or role GOO + if (user.IsInRole("GOO") || await access.HasActionAsync(RegistryActions.Destinations, ct)) + { + truck.DestinationIds = await repository.GetActiveDestinationIdsAsync(truck.Tn, ct); + truck.PendingDestination = await repository.GetPendingDestinationAsync(truck.Tn, ct); + } + + truck.Attachments = await attachments.ListAsync(RegistryAttachmentService.KindTruck, id, ct); + return truck; + } + + public async Task> TrailersAsync(long? truckId, long? trailerId, CancellationToken ct) + { + var rows = await repository.ListTrailersOfTruckAsync(access.Scope, truckId, trailerId, ct); + foreach (var r in rows) r.StatusCaption = RegistryRules.StatusCaption(r.StatusCode, r.StatusCaption); + return rows; + } + + // ------------------------------------------------------------------------------------------------ create + + public async Task CreateAsync(SaveTruckRequest request, CancellationToken ct) + { + await access.RequireAuthorityAsync(PermissionKeys.RegistryTrucksCreate, ct); + + // company users register for their own company (the legacy select offered every company; their grid only shows their own) + var tcscac = access.IsCompanyUser && access.CompanyCodeNo is not null ? access.CompanyCodeNo : request.Tcscac; + RegistryValidation.ThrowIfAny(RegistryValidation.ValidateTruck(request, tcscac, false, settings.BadiyaScac, DateTime.Now.Year)); + + var tn = request.Tn!.Trim(); + // validateUniqueTN + if (await repository.ActiveTruckExistsAsync(tn, ct)) + throw new BusinessException(RegistryErrors.TruckDuplicate, RegistryMessages.TruckDuplicate); + + var tempIds = await attachments.EnsureTempFilesAsync(request.AttachmentIds, ct); + var canSetDestinations = await access.HasActionAsync(RegistryActions.Destinations, ct); + + var id = await unitOfWork.ExecuteInTransactionAsync(async token => + { + // only users with action 107 pick destinations (NTP_COMPANY_DISTINATION, status ACTIVE) + if (canSetDestinations && request.Destinations is not null) + foreach (var dest in request.Destinations.All()) + await repository.InsertDestinationAsync(tn, dest, user.UserId, token); + + // legacy: every new truck starts as REGREQST ("awaiting registration", needs a trailer) + var truck = new NtpTruck + { + Tn = tn, + ChasesNumber = request.ChasesNumber?.Trim().ToUpperInvariant(), + RegDate = request.RegDate?.Date, + Axials = request.Axials, + StatusCode = RegistryStatus.RegReqst, + OwnerName = Clean(request.OwnerName), + OwnerNnpn = Clean(request.OwnerNnpn), + Color = Clean(request.Color), + Model = Clean(request.Model), + ManifactureYear = Clean(request.ManifactureYear), + PhoneNumber = Clean(request.PhoneNumber), + HeadType = Clean(request.HeadType), + Tcscac = tcscac, + CreateUserId = user.UserId + }; + var newId = await repository.InsertTruckAsync(truck, token); + await attachments.AttachAsync(RegistryAttachmentService.KindTruck, newId, tempIds, token); + return newId; + }, ct); + + if (tcscac != settings.BadiyaScac) + return new RegistryResult(RegistryMessages.TruckAddedAwaitingTrailer, id); + + // company 327: legacy then asks the queue web service for a PCKD and a BULK permit. The truck is still REGREQST, so + // createPermitRecord answers "not registered" (it only accepts OPEN/ACCPT trucks) - the permits are created when the trailer is added. + await queuePermits.CreatePermitRecordAsync(tn, settings.BadiyaScac, RegistryStatus.Open, "PCKD", true, ct); + await queuePermits.CreatePermitRecordAsync(tn, settings.BadiyaScac, RegistryStatus.Open, "BULK", true, ct); + return new RegistryResult(RegistryMessages.Done, id); + } + + // ------------------------------------------------------------------------------------------------ update + + public async Task UpdateAsync(long id, SaveTruckRequest request, CancellationToken ct) + { + await access.RequireAuthorityAsync(PermissionKeys.RegistryTrucksEdit, ct); + + var current = await repository.GetTruckAsync(id, ct) ?? throw new NotFoundException("Truck", id); + access.EnsureCompanyAccess(current.Tcscac); + if (!RegistryRules.CanEdit(current.StatusCode)) + throw new BusinessException(RegistryErrors.InvalidState, RegistryMessages.OnlyRevokedNotEditable); + + // the company select is disabled on edit: the stored company decides the rules + RegistryValidation.ThrowIfAny(RegistryValidation.ValidateTruck(request, current.Tcscac, true, settings.BadiyaScac, DateTime.Now.Year)); + + var tempIds = await attachments.EnsureTempFilesAsync(request.AttachmentIds, ct); + var canSetDestinations = await access.HasActionAsync(RegistryActions.Destinations, ct); + var newStatus = RegistryRules.StatusAfterTruckEdit(current.Tcscac, current.StatusCode, settings.BadiyaScac); + var is327 = current.Tcscac == settings.BadiyaScac; + + await unitOfWork.ExecuteInTransactionAsync(async token => + { + if (canSetDestinations && request.Destinations is not null) + { + await repository.DeactivateDestinationsAsync(current.Tn, user.UserId, token); + foreach (var dest in request.Destinations.All()) + await repository.InsertDestinationAsync(current.Tn, dest, user.UserId, token); + } + + var values = new NtpTruck + { + Color = Clean(request.Color), + RegDate = request.RegDate?.Date, + OwnerNnpn = Clean(request.OwnerNnpn), + PhoneNumber = Clean(request.PhoneNumber), + HeadType = Clean(request.HeadType), + ChasesNumber = request.ChasesNumber?.Trim().ToUpperInvariant(), + ManifactureYear = Clean(request.ManifactureYear), + Model = Clean(request.Model), + Axials = request.Axials, + OwnerName = Clean(request.OwnerName) + }; + // the phone box is disabled for the other companies in the legacy form (not posted, so not updated) + await repository.UpdateTruckAsync(id, values, updatePhone: is327, newStatus, user.UserId, token); + await attachments.AttachAsync(RegistryAttachmentService.KindTruck, id, tempIds, token); + return true; + }, ct); + + return new RegistryResult(RegistryMessages.Done, id); + } + + // ------------------------------------------------------------------------------------------------ accept / revoke + + public async Task AcceptAsync(long id, CancellationToken ct) + { + await access.RequireActionAsync(RegistryActions.AcceptTruck, false, ct); + var truck = await repository.GetTruckAsync(id, ct) ?? throw new NotFoundException("Truck", id); + access.EnsureCompanyAccess(truck.Tcscac); + if (!RegistryRules.CanAccept(truck.StatusCode)) + throw new BusinessException(RegistryErrors.InvalidState, RegistryMessages.NotAcceptable); + + await repository.AcceptTruckAsync(id, user.UserId, ct); + return new RegistryResult(RegistryMessages.Accepted, id); + } + + public async Task RevokeAsync(long id, CancellationToken ct) + { + await access.RequireActionAsync(RegistryActions.RevokeTruck, false, ct); + if (access.IsBadiyaCompany) + throw new ForbiddenException(RegistryErrors.Forbidden, RegistryMessages.Forbidden); // legacy hides the button for 327 + + var truck = await repository.GetTruckAsync(id, ct) ?? throw new NotFoundException("Truck", id); + access.EnsureCompanyAccess(truck.Tcscac); + if (!RegistryRules.CanRevoke(truck.StatusCode)) + throw new BusinessException(RegistryErrors.InvalidState, RegistryMessages.AlreadyRevoked); + + await unitOfWork.ExecuteInTransactionAsync(async token => + { + await repository.RevokeTruckAsync(id, user.UserId, token); + // trailers connected to the truck are revoked with it (30 Dec 2020) + await repository.RevokeTrailersOfTruckAsync(id, user.UserId, token); + // destinations of the truck are deactivated (30 Dec 2020) + await repository.DeactivateDestinationsAsync(truck.Tn, user.UserId, token); + // OPEN GN permits of the truck are revoked (6 Jan 2021) + await repository.RevokeOpenPermitsOfTruckAsync(truck.Tn, user.UserId, token); + return true; + }, ct); + + return new RegistryResult(RegistryMessages.Revoked, id); + } + + private static string? Clean(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); +} diff --git a/src/NTP.Application/Grains/Reports/IReports.cs b/src/NTP.Application/Grains/Reports/IReports.cs new file mode 100644 index 0000000..416a191 --- /dev/null +++ b/src/NTP.Application/Grains/Reports/IReports.cs @@ -0,0 +1,76 @@ +namespace NTP.Application.Grains.Reports; + +/// Caller facts the legacy report SQL depends on (session.userrolecode / locationid / stkid / companycodeno). +public sealed record ReportScope(string UserId, string RoleCode, long? LocationId, long? StkId, long? CompanyCodeNo); + +/// Raw SQL rows (keys are the upper-case Oracle aliases; read them case-insensitively). +public interface IReportsRepository +{ + Task> CompaniesAsync(CancellationToken ct); + Task> CargoTypesAsync(CancellationToken ct); + Task> DestinationsAsync(IReadOnlyList gnTypes, CancellationToken ct); + + Task> TripsPerCompanyAsync(DateOnly from, DateOnly to, CancellationToken ct); + Task> FrequencyAsync(DateOnly from, DateOnly to, string? scac, string? cargoType, CancellationToken ct); + Task> DetailsAsync(DateOnly from, DateOnly to, CancellationToken ct); + Task> WeighbridgeEventsAsync(DateOnly from, DateOnly to, long? locationId, CancellationToken ct); + + /// Table reports by key (see ). Returns the raw rows; the service shapes them. + Task>> TableAsync(string key, ReportFilter filter, ReportScope scope, CancellationToken ct); + + Task> MotMultiTripsAsync(CancellationToken ct); +} + +public static class ReportKeys +{ + public const string ClosedPermits = "closed-permits"; + public const string LoadingWeights = "loading-weights"; + public const string Incapability = "incapability"; + public const string WaybridgeSummary = "waybridge-summary"; + public const string WaybridgeDetails = "waybridge-details"; + public const string TenderOrder = "tender-order"; + public const string DistributionSummary = "distribution-summary"; + public const string CallList = "call-list"; + public const string CompaniesTurn = "companies-turn"; + public const string OwnersTurn = "owners-turn"; + public const string Drivers = "drivers"; + public const string Trucks = "trucks"; + public const string OrderDistribution = "order-distribution"; + public const string OrderDistributionByDest = "order-distribution-dest"; + public const string WeighbridgeEvents = "weighbridge-events"; + public const string MotGrainCube = "mot-grain-cube"; + public const string MotGrainFrequency = "mot-grain-frequency"; + + public static readonly string[] All = + [ + ClosedPermits, LoadingWeights, Incapability, WaybridgeSummary, WaybridgeDetails, TenderOrder, DistributionSummary, + CallList, CompaniesTurn, OwnersTurn, Drivers, Trucks, OrderDistribution, WeighbridgeEvents, MotGrainCube, MotGrainFrequency + ]; +} + +public interface IReportsService +{ + Task> CompaniesAsync(CancellationToken ct); + Task> CargoTypesAsync(CancellationToken ct); + Task> DestinationsAsync(string? shipmentMode, CancellationToken ct); + + Task NumOfTripsAndTrucksAsync(DateOnly from, DateOnly to, CancellationToken ct); + Task QuotaAsync(DateOnly from, DateOnly to, CancellationToken ct); + Task FrequencyAsync(DateOnly from, DateOnly to, string? scac, string? cargoType, CancellationToken ct); + Task DetailsAsync(DateOnly from, DateOnly to, CancellationToken ct); + Task MotMultiTripsAsync(CancellationToken ct); + + Task BuildTableAsync(string key, ReportFilter filter, CancellationToken ct); + Task PageAsync(string key, ReportFilter filter, int page, int pageSize, CancellationToken ct); + Task<(byte[] Content, string FileName)> ExportAsync(string key, ReportFilter filter, CancellationToken ct); +} + +/// Excel in/out (ClosedXML in Infrastructure). +public interface IReportExcelService +{ + /// Builds an RTL workbook: title, filter lines, header row, rows, footer (printed by / date / count). + byte[] Build(ReportTable table, string printedBy, DateTime printedAt, bool arabic); + + /// Reads the first worksheet as rows of strings (used when the approvals file is .xlsx instead of .csv). + List ReadFirstSheet(Stream stream); +} diff --git a/src/NTP.Application/Grains/Reports/ImportLogic.cs b/src/NTP.Application/Grains/Reports/ImportLogic.cs new file mode 100644 index 0000000..02cf193 --- /dev/null +++ b/src/NTP.Application/Grains/Reports/ImportLogic.cs @@ -0,0 +1,192 @@ +using System.Globalization; +using System.Text; + +namespace NTP.Application.Grains.Reports; + +/// Port of ParseFile.cfc CSVToQuery (RFC-4180 style: delimiter ',', qualifier '"', doubled qualifier escapes). +public static class CsvReader +{ + public static List Parse(string text, char delimiter = ',', char qualifier = '"') + { + var rows = new List(); + var row = new List(); + var sb = new StringBuilder(); + var inQ = false; + var any = false; + for (var i = 0; i < text.Length; i++) + { + var c = text[i]; + if (inQ) + { + if (c == qualifier) + { + if (i + 1 < text.Length && text[i + 1] == qualifier) { sb.Append(qualifier); i++; } + else inQ = false; + } + else sb.Append(c); + continue; + } + if (c == qualifier && sb.Length == 0) { inQ = true; any = true; continue; } + if (c == delimiter) { row.Add(sb.ToString()); sb.Clear(); any = true; continue; } + if (c == '\r') continue; + if (c == '\n') + { + row.Add(sb.ToString()); sb.Clear(); + rows.Add(row.ToArray()); row.Clear(); any = false; + continue; + } + sb.Append(c); any = true; + } + if (any || sb.Length > 0 || row.Count > 0) + { + row.Add(sb.ToString()); + rows.Add(row.ToArray()); + } + return rows; + } +} + +/// +/// ParseFile.cfc saveExaclFile: classification of one IVR call-result line. Columns (1-based, as the legacy COLUMN_n): +/// 17 = permit id, 18 = Confirmation, 19 = call number (days word at position 11..13), 20 = call status. +/// +public static class PhoneApprovalLogic +{ + public const string NoAnswerRemark = "لم يتم الإجابة على الإتصال"; + public const string AnsweredRemark = "تم الإجابة على الإتصال"; + public const string NoDecisionRemark = "لم يتخذ قرار"; + + private static string Col(string[] row, int n) => n - 1 < row.Length ? row[n - 1] : ""; + + public static int DelayDays(string callNo) + { + var word = callNo.Length >= 13 ? callNo.Substring(10, 3) : callNo.Length > 10 ? callNo[10..] : ""; + return word switch { "one" => 1, "two" => 2, "thr" => 3, "fou" => 4, "fiv" => 5, _ => 0 }; + } + + public static PhoneDecision Decide(string[] row) + { + var idText = Col(row, 17).Trim(); + if (!long.TryParse(idText, NumberStyles.None, CultureInfo.InvariantCulture, out var id)) + return new PhoneDecision(PhoneDecisionKind.Skip, 0, 0, ""); // legacy: not IsNumeric -> cfcontinue + + var status = Col(row, 20).Trim(); + var remarks = ""; + if (Has(status, "Call Made. Line disconnected.") || Has(status, "Call Made. No Answer.") || Has(status, "Call Made. timeout")) + remarks = NoAnswerRemark; + else if (Has(status, "Call Answered.")) + remarks = AnsweredRemark; + + var conf = Col(row, 18); + if (conf == "No" || conf.Contains(" No", StringComparison.Ordinal)) + { + var days = DelayDays(Col(row, 19)); + return new PhoneDecision(PhoneDecisionKind.Reject, id, days, $"{remarks} - تم التأجيل {days} يوم"); + } + if (conf == "" || (!conf.Contains("No", StringComparison.Ordinal) && !conf.Contains("Yes", StringComparison.Ordinal))) + return new PhoneDecision(PhoneDecisionKind.Reject, id, 1, $"{remarks} - {NoDecisionRemark}"); + return new PhoneDecision(PhoneDecisionKind.Accept, id, 0, remarks); + } + + private static bool Has(string s, string needle) => s.Contains(needle, StringComparison.OrdinalIgnoreCase); +} + +/// ReadFiles\parseIrbidFile.cfm / WB\cfc\ParseIrbidFile.cfc: line based weighbridge file of the Irbid/Gaban silo. +public static class IrbidFileParser +{ + /// + /// First line = record count (ignored). The FIRST record spans 9 lines (F9 stays null), every later one 10 lines. + /// Blanks are removed from every line; F1 is prefixed with "60" (truck number). WID is the 1-based record counter. + /// + public static List Parse(IEnumerable lines, string fileName) + { + var name = FileKey(fileName); + var result = new List(); + var vals = new List(); + var first = true; + var skippedHeader = false; + long wid = 0; + foreach (var raw in lines) + { + if (!skippedHeader) { skippedHeader = true; continue; } + vals.Add(raw.Replace(" ", "")); + var need = first ? 9 : 10; + if (vals.Count < need) continue; + result.Add(new IrbidRecord + { + Id = vals[0], F1 = "60" + vals[1], F2 = vals[2], F3 = vals[3], F4 = vals[4], F5 = vals[5], + F6 = vals[6], F7 = vals[7], F8 = vals[8], F9 = first ? null : vals[9], + Wid = ++wid, FileName = name, Location = "ir" + }); + vals.Clear(); + first = false; + } + return result; + } + + /// ListFirst(ListLast(fileName,'\'),'.') then (readOriginaldata / ParseIrbidFile) strip digits for the stored file name. + public static string FileKey(string path) + { + var last = path.Replace('/', '\\').Split('\\').Last(); + var stem = last.Split('.')[0]; + return new string(stem.Where(c => !char.IsAsciiDigit(c)).ToArray()); + } + + /// Event timestamp sent to the WS: F4 date (yyyy-mm-dd..) + F3 time -> yyyyMMddHHmmss, "" when either is empty. + public static string EventDate(IrbidRecord r) + { + var d = r.F4.Replace("00:00:00.0", "").Trim(); + if (d.Length == 0 || r.F3.Length == 0) return ""; + if (!DateTime.TryParse(d, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) return ""; + if (!TimeSpan.TryParse(r.F3, CultureInfo.InvariantCulture, out var time)) return ""; + return date.Date.Add(time).ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture); + } +} + +/// ReadFiles\Reading\reafFilesIntoTemp.cfm: "Rsifeh" file: count line, then (id line, CSV data line) pairs. +public static class RsifehFileParser +{ + public static List Parse(IEnumerable lines, string fileName) + { + var key = fileName.Replace('/', '\\').Split('\\').Last().Split('.')[0]; + key = key.Length > 0 && (key[0] == 'w' || key[0] == 'W') ? key.Remove(0, 1) : key; // ReplaceNoCase(...,'w','') (first only) + var all = lines.ToList(); + var result = new List(); + if (all.Count == 0 || !int.TryParse(all[0].Trim(), out var count)) return result; + string id = ""; + for (var n = 2; n <= all.Count; n++) // currentrecord is 1-based; line 1 is the count + { + if (n > count * 2 + 1) break; + var line = all[n - 1]; + if (n % 2 == 0) { id = line; continue; } + var f = SplitList(line); + string G(int i) => i - 1 < f.Count ? f[i - 1] : ""; + var r = new RsifehRecord + { + Id = id, FileName = key, + F1 = G(1).Replace("\"", "").Replace("/", "").Replace("*", ""), + F2 = G(2).Replace(" ", ""), + F3 = G(3).Replace("\"", ""), + F4 = G(4), + F5 = Dt(Strip(G(5))), F6 = Dt(Strip(G(6))), F7 = Dt(Strip(G(7))), F8 = Dt(Strip(G(8))), + F9 = G(9).Replace("\"", ""), F10 = G(10).Replace("\"", ""), F11 = G(11).Replace("\"", ""), + F12 = G(12).Replace("\"", ""), F13 = G(13).Replace("\"", "") + }; + r.F1 = "60" + r.F1; + result.Add(r); + } + return result; + } + + private static string Strip(string s) => s.Replace("#", "").Replace(" ", ""); // legacy also strips chr(32): "yyyy-mm-dd HH:mm:ss" loses its blank + + private static DateTime? Dt(string s) + { + s = s.Replace(".0", ""); + string[] fmts = ["yyyy-MM-ddHH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"]; + return DateTime.TryParseExact(s, fmts, CultureInfo.InvariantCulture, DateTimeStyles.None, out var d) ? d : null; + } + + /// CF list semantic: comma delimited, double-quoted items may contain commas. + private static List SplitList(string line) => CsvReader.Parse(line).FirstOrDefault()?.ToList() ?? []; +} diff --git a/src/NTP.Application/Grains/Reports/ImportServices.cs b/src/NTP.Application/Grains/Reports/ImportServices.cs new file mode 100644 index 0000000..37c15a6 --- /dev/null +++ b/src/NTP.Application/Grains/Reports/ImportServices.cs @@ -0,0 +1,257 @@ +using System.Text; +using NTP.Application.Abstractions; +using NTP.Application.Common; + +namespace NTP.Application.Grains.Reports; + +// ====================================================================== phone approvals (uploadAccptExlFile.cfm -> ParseFile.cfc) + +public sealed record PhoneActionResult(bool Ok, string Code, string Message); + +public interface IPhoneApprovalRepository +{ + /// grains.cfc addPhoneAcceptEvent (DB part). Notification push is not ported. + Task AcceptAsync(long permitId, string? remarks, string userId, CancellationToken ct); + /// grains.cfc addPhoneRejectEvent (blacklist, queue counters, permit back to OPEN, PHRJCT event). + Task RejectAsync(long permitId, int delayDays, string remarks, string userId, CancellationToken ct); +} + +public interface IPhoneApprovalImportService +{ + Task ImportAsync(Stream file, string fileName, CancellationToken ct); +} + +/// +/// Reads the IVR call-result file (CSV or XLSX, same column layout as the legacy CSV) and applies one accept/reject per row. +/// Legacy ran everything in one transaction but swallowed per-row errors; here each row has its own transaction and the +/// result lists every failure. +/// +public sealed class PhoneApprovalImportService( + IPhoneApprovalRepository repo, IReportExcelService excel, IUnitOfWork uow, ICurrentUser user) : IPhoneApprovalImportService +{ + public async Task ImportAsync(Stream file, string fileName, CancellationToken ct) + { + List rows; + var ext = Path.GetExtension(fileName).ToLowerInvariant(); + if (ext is ".xlsx" or ".xlsm") + rows = excel.ReadFirstSheet(file); + else if (ext is ".csv" or ".txt" or "") + { + using var sr = new StreamReader(file, new UTF8Encoding(false), true); + rows = CsvReader.Parse(await sr.ReadToEndAsync(ct)); + } + else throw new BusinessException("IMPORT_FILE_TYPE", "نوع الملف غير مدعوم، يرجى رفع ملف CSV أو XLSX"); + + if (rows.Count == 0) throw new BusinessException("IMPORT_FILE_EMPTY", "الملف فارغ"); + + int acc = 0, rej = 0, skip = 0, fail = 0; + var results = new List(); + for (var i = 0; i < rows.Count; i++) + { + ct.ThrowIfCancellationRequested(); + var d = PhoneApprovalLogic.Decide(rows[i]); + if (d.Kind == PhoneDecisionKind.Skip) { skip++; continue; } // header / non numeric id lines + try + { + var r = await uow.ExecuteInTransactionAsync(t => d.Kind == PhoneDecisionKind.Accept + ? repo.AcceptAsync(d.PermitId, null, user.UserId, t) // legacy computed remarks but never passed them to addPhoneAcceptEvent + : repo.RejectAsync(d.PermitId, d.DelayDays, d.Remarks, user.UserId, t), ct); + results.Add(new PhoneImportRowResult(i + 1, d.PermitId, d.Kind.ToString(), r.Ok, r.Code, r.Message)); + if (!r.Ok) fail++; else if (d.Kind == PhoneDecisionKind.Accept) acc++; else rej++; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + fail++; + results.Add(new PhoneImportRowResult(i + 1, d.PermitId, d.Kind.ToString(), false, "ROW_FAILED", ex.Message)); + } + } + var msg = fail == 0 ? "تمت العملية بنجاح" : $"تمت العملية مع {fail} أخطاء"; + return new PhoneImportResult(rows.Count, acc, rej, skip, fail, results, msg); + } +} + +// ====================================================================== weighbridge files (ReadFiles\*) + +public interface IWeighbridgeFileRepository +{ + // TEMP_WAYBRIDGE_IRBID (the "original" table of already processed records, keyed by location + file name + id) + Task IrbidExistsAsync(string location, string fileName, string id, CancellationToken ct); + Task InsertIrbidAsync(IrbidRecord r, CancellationToken ct); + Task UpdateIrbidAsync(IrbidRecord r, CancellationToken ct); + Task DeleteAllIrbidAsync(CancellationToken ct); + + // TEMP_WAYBRIDGE / TEMP_WAYBRIDGE_TEMP ("Rsifeh" format) + Task StageRsifehAsync(IReadOnlyList rows, CancellationToken ct); + Task PromoteNewRsifehAsync(string fileName, CancellationToken ct); + + // WEIGHBRIDGE_RAW_DATA -> permits/events (jobs/getWeighbridgeEvents.cfm second half) + Task> UnmatchedRawAsync(CancellationToken ct); + Task FindPermitForRawAsync(string truckNo, CancellationToken ct); + Task FindPermitByTimeAsync(string truckNo, string ginTime, string tt, CancellationToken ct); + Task SetRawPermitAsync(string rowId, long permitId, CancellationToken ct); + Task InsertRawEventsAndCloseAsync(RawWeighbridgeRow raw, RawPermit permit, CancellationToken ct); +} + +public sealed class RawWeighbridgeRow +{ + public string TransId { get; set; } = ""; + public long LocationId { get; set; } + public string CargoTruckNo { get; set; } = ""; + public string GinTime { get; set; } = ""; + public string GoutTime { get; set; } = ""; + public decimal CargoWeightIn { get; set; } + public decimal CargoWeightOut { get; set; } +} + +public sealed record RawPermit(long Id, string ShipmentStatusCode); + +public interface IWeighbridgeFileService +{ + Task ImportIrbidAsync(Stream content, string fileName, CancellationToken ct); + Task ImportOriginalAsync(Stream content, string fileName, bool replaceExisting, CancellationToken ct); + Task ImportRsifehAsync(Stream content, string fileName, CancellationToken ct); + /// One pass over the configured directory (what the directory watcher does for each new file). + Task ScanDirectoryAsync(string directory, string? archiveDirectory, CancellationToken ct); + Task SyncRawDataAsync(CancellationToken ct); +} + +public sealed class WeighbridgeFileService( + IWeighbridgeFileRepository repo, IWsService ws, IUnitOfWork uow) : IWeighbridgeFileService +{ + /// Weighbridge location of the Irbid/Gaban file (legacy hard-coded '225' / user 'W225'). + public const long IrbidLocationId = 225; + + private static async Task> ReadLinesAsync(Stream s, CancellationToken ct) + { + using var sr = new StreamReader(s, new UTF8Encoding(false), true); + var all = await sr.ReadToEndAsync(ct); + return all.Split('\n').Select(l => l.TrimEnd('\r')).ToList(); + } + + public async Task ImportIrbidAsync(Stream content, string fileName, CancellationToken ct) + { + var lines = await ReadLinesAsync(content, ct); + if (lines.Count > 0 && lines[^1].Length == 0) lines.RemoveAt(lines.Count - 1); + var recs = IrbidFileParser.Parse(lines, fileName); + int ins = 0, upd = 0, skip = 0, fail = 0; + var errors = new List(); + foreach (var r in recs) + { + ct.ThrowIfCancellationRequested(); + try + { + var exists = await repo.IrbidExistsAsync(r.Location, r.FileName, r.Id, ct); + var eDate = IrbidFileParser.EventDate(r); + if (!exists) + { + // legacy: call the WS (skip the record on exception), then insert; when F5 > 0 call again and update. + if (!await CallWs(r, eDate, errors, ct)) { skip++; continue; } + await repo.InsertIrbidAsync(r, ct); ins++; + if (double.TryParse(r.F5, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var f5) && f5 > 0) + { + if (!await CallWs(r, eDate, errors, ct)) { skip++; continue; } + await repo.UpdateIrbidAsync(r, ct); upd++; + } + } + else + { + if (!await CallWs(r, eDate, errors, ct)) { skip++; continue; } + await repo.UpdateIrbidAsync(r, ct); upd++; + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + fail++; errors.Add($"WID {r.Wid}: {ex.Message}"); + } + } + return new FileImportResult(fileName, recs.Count, ins, upd, skip, fail, errors); + } + + /// true when the web-service call did not throw (the legacy never inspected errorcode). No event date -> legacy returned an empty struct (success). + private async Task CallWs(IrbidRecord r, string eDate, List errors, CancellationToken ct) + { + if (eDate.Length == 0) return true; + try + { + var res = await ws.AddWeightBridgeEventAsync(new WeighbridgeEventRequest(r.F1, r.F2, IrbidLocationId, eDate, "EX", $"W{IrbidLocationId}"), ct); + if (res.ErrorCode != WbCodes.Ok) errors.Add($"WID {r.Wid} TN {r.F1}: [{res.ErrorCode}] {res.Msg}"); + return true; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + errors.Add($"WID {r.Wid} TN {r.F1}: {ex.Message}"); + return false; + } + } + + /// readOriginaldata.cfm: loads a snapshot file straight into TEMP_WAYBRIDGE_IRBID (optionally replacing the table, as legacy did). + public async Task ImportOriginalAsync(Stream content, string fileName, bool replaceExisting, CancellationToken ct) + { + var lines = await ReadLinesAsync(content, ct); + var recs = IrbidFileParser.Parse(lines, fileName); + if (replaceExisting) await repo.DeleteAllIrbidAsync(ct); + int ins = 0; + foreach (var r in recs) { await repo.InsertIrbidAsync(r, ct); ins++; } + return new FileImportResult(fileName, recs.Count, ins, 0, 0, 0, []); + } + + public async Task ImportRsifehAsync(Stream content, string fileName, CancellationToken ct) + { + var lines = await ReadLinesAsync(content, ct); + var recs = RsifehFileParser.Parse(lines, fileName); + if (recs.Count == 0) return new FileImportResult(fileName, 0, 0, 0, 0, 0, []); + await repo.StageRsifehAsync(recs, ct); + var ins = await repo.PromoteNewRsifehAsync(recs[0].FileName, ct); + return new FileImportResult(fileName, recs.Count, ins, 0, recs.Count - ins, 0, []); + } + + public async Task ScanDirectoryAsync(string directory, string? archiveDirectory, CancellationToken ct) + { + var results = new List(); + if (!Directory.Exists(directory)) return new WeighbridgeScanResult(0, results); + foreach (var path in Directory.EnumerateFiles(directory).OrderBy(p => p, StringComparer.OrdinalIgnoreCase)) + { + ct.ThrowIfCancellationRequested(); + await using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + results.Add(await ImportIrbidAsync(fs, Path.GetFileName(path), ct)); + // legacy: onAdd moved the file to D:\ArchiveFiles\ir after parsing + if (!string.IsNullOrWhiteSpace(archiveDirectory)) + { + Directory.CreateDirectory(archiveDirectory); + var dest = Path.Combine(archiveDirectory, Path.GetFileName(path)); + if (File.Exists(dest)) dest = Path.Combine(archiveDirectory, $"{DateTime.Now:yyyyMMddHHmmss}_{Path.GetFileName(path)}"); + File.Move(path, dest); + } + } + return new WeighbridgeScanResult(results.Count, results); + } + + /// + /// jobs/getWeighbridgeEvents.cfm (matching half): for every raw weighbridge row without a permit, find the truck's permit + /// (ACTRL/CLRPR/ACTWT, else the one active at the entry time), stamp the raw row, add DGW+DTW and close the permit. + /// + public async Task SyncRawDataAsync(CancellationToken ct) + { + var rows = await repo.UnmatchedRawAsync(ct); + int matched = 0, none = 0, failed = 0; + foreach (var raw in rows) + { + ct.ThrowIfCancellationRequested(); + try + { + await uow.ExecuteInTransactionAsync(async t => + { + var permit = await repo.FindPermitForRawAsync(raw.CargoTruckNo, t) + ?? await repo.FindPermitByTimeAsync(raw.CargoTruckNo, raw.GinTime, "BULK", t); + if (permit is null) { await repo.SetRawPermitAsync(raw.TransId, 0, t); none++; return 0; } // 0 flags "no permit found" + await repo.SetRawPermitAsync(raw.TransId, permit.Id, t); + await repo.InsertRawEventsAndCloseAsync(raw, permit, t); + matched++; + return 1; + }, ct); + } + catch (Exception ex) when (ex is not OperationCanceledException) { _ = ex; failed++; } + } + return new RawSyncResult(rows.Count, matched, none, failed); + } +} diff --git a/src/NTP.Application/Grains/Reports/ReportDtos.cs b/src/NTP.Application/Grains/Reports/ReportDtos.cs new file mode 100644 index 0000000..1cba3ed --- /dev/null +++ b/src/NTP.Application/Grains/Reports/ReportDtos.cs @@ -0,0 +1,214 @@ +namespace NTP.Application.Grains.Reports; + +/// Value/label pair for report filter drop-downs. +public sealed record LookupItem(string Value, string Label); + +/// Legacy GN permit codes used by the reports (legacy literals, kept in one place). +public static class GrainsReportConstants +{ + /// application.GN_BadiyaSCAC (individuals / "Badiya" company code, hard-coded '327' in reports.cfc). + public const string BadiyaScac = "327"; + /// Statuses counted as "completed trips" by every trips report. + public static readonly string[] TripStatuses = ["CLOSE", "RESD", "ACCPT", "ACTRL"]; + public const int MaxTripsBucket = 15; +} + +// ------------------------------------------------------------------ typed trips reports + +/// One row of reports.cfc getNumOfTripsAndTrucks (numbers instead of the legacy to_char strings). +public sealed class TripsPerCompanyRow +{ + public string Scac { get; set; } = ""; // company name (getcompanynamefromscac) + public string CompanyCode { get; set; } = ""; + public decimal AllTripNum { get; set; } + public decimal NumOfTruk { get; set; } + public decimal CompanyShare { get; set; } + public decimal AvgShare { get; set; } + public decimal TotalShare { get; set; } + public decimal AvgTotalTrucks { get; set; } + public decimal AvrgTrips { get; set; } + public bool IsBadiya => CompanyCode == GrainsReportConstants.BadiyaScac; +} + +public sealed record NumOfTripsTotals( + decimal CompanyShare, decimal AvgShare, decimal TotalShare, decimal Trucks, decimal Trips, decimal TripsPct); + +public sealed record NumOfTripsAndTrucksReport( + DateOnly From, DateOnly To, + IReadOnlyList Companies, + NumOfTripsTotals CompaniesTotal, + TripsPerCompanyRow? Individuals, + decimal GrandTotalShare, decimal GrandTrucks, decimal GrandTrips, decimal GrandTripsPct); + +public sealed record QuotaLine(string Label, decimal Trucks, decimal TruckPct, decimal Trips, decimal TripPct); +public sealed record QuotaReport(DateOnly From, DateOnly To, QuotaLine Companies, QuotaLine Individuals); + +/// Trucks by number of trips (1..15) and the derived figures used by freq / distribution / dashboard. +public sealed record FrequencyReport( + DateOnly From, DateOnly To, + IReadOnlyList Trucks, // index 0 => trucks that made 1 trip + IReadOnlyList Trips, // Trucks[i] * (i+1) + IReadOnlyList TripsPct, // Trips[i] / TotalTrips * 100 + long TotalTrucks, long TotalTrips, + IReadOnlyList Groups); + +public sealed record TripGroupLine(string Key, int FromTrips, int ToTrips, long Trucks, decimal TrucksPct, long Trips, decimal TripsPct); + +public sealed class DetailsRow +{ + public string Scac { get; set; } = ""; + public string Tn { get; set; } = ""; + public decimal Tt { get; set; } +} +public sealed record DetailsGroup(string Company, IReadOnlyList Rows, decimal TotalTrips, int TruckCount); +public sealed record DetailsReport(DateOnly From, DateOnly To, IReadOnlyList Groups); + +// ------------------------------------------------------------------ weighbridge events (Reports\weightbridgeEvents.cfm) + +/// Raw join row of reports.cfc getWieghtBridgeEvents (EVENTS may be null: legacy outer join). +public sealed class WeighbridgeEventRaw +{ + public long Pid { get; set; } + public string? Pn { get; set; } + public string? Tn { get; set; } + public string? Loc { get; set; } + public long? LocationId { get; set; } + public string? EventType { get; set; } + public string? Weight { get; set; } + public string? Scac { get; set; } + public string? CargoType { get; set; } + public string? Drvr { get; set; } + public string? Nnpn { get; set; } + public string? EventDate { get; set; } // dd/mm/yyyy of the weight event + public string? OriginAddressId { get; set; } // origin location name +} + +public sealed record WeighbridgeEventRow( + int Serial, string? Pn, string? Tn, string? CargoType, string? Scac, string? Loc, + decimal Ltw, decimal Lgw, decimal Lnw, string LoadDate, + decimal Dtw, decimal Dgw, decimal Dnw, string DischargeDate, + decimal NetLoss, string? Drvr, string? Nnpn, string Origin); + +// ------------------------------------------------------------------ generic tabular reports (grid + Excel) + +public sealed record ReportColumn(string Key, string HeaderAr, string HeaderEn, string Kind = "text"); + +/// +/// A tabular report: rows are dictionaries keyed by (camelCase). Used by the grid, the +/// Excel export and the print view alike. Extra carries report-specific blocks (e.g. summary tables). +/// +public sealed class ReportTable +{ + public string Key { get; init; } = ""; + public string TitleAr { get; init; } = ""; + public string TitleEn { get; init; } = ""; + public IReadOnlyList Columns { get; init; } = []; + public IReadOnlyList> Rows { get; init; } = []; + public IReadOnlyList FilterLines { get; init; } = []; + public IReadOnlyDictionary? Extra { get; init; } +} + +public sealed record ReportPage( + IReadOnlyList> Items, int Page, int PageSize, long TotalCount, + IReadOnlyList Columns, IReadOnlyDictionary? Extra); + +/// Filters of the table reports (only the members a given report uses are read). +public sealed class ReportFilter +{ + public DateOnly? From { get; set; } + public DateOnly? To { get; set; } + public DateOnly? OrderDate { get; set; } + public string? EventType { get; set; } + public string? ShipmentMode { get; set; } // BULK | PCKD | GALLAB (turn reports) / BULK|PCKD (distribution summary) + public string? DistributionType { get; set; } // COMP | AHALI | all + public long? DestAddressId { get; set; } + public string? Scac { get; set; } + public string? CargoType { get; set; } + public string? Tn { get; set; } + public string? StatusCode { get; set; } + public string? ChasesNumber { get; set; } + public string? HeadType { get; set; } + public string? Nnpn { get; set; } + public string? Name { get; set; } + public string? Tt { get; set; } + public string? ShipmentStatusCode { get; set; } + public string? CreationDate { get; set; } + public bool Download { get; set; } +} + +// ------------------------------------------------------------------ MOT (Ministry of Transport) grains reports + +/// Row of the GRAINSPERMITS view aggregate (MotDAO.getGrainsquery). +public sealed class MotMultiTripsRow +{ + public string Mm { get; set; } = ""; // yyyy-mm + public string RegType { get; set; } = ""; // OWN | COMP + public int Trips { get; set; } // 1..25, 0 = more than 25 + public long TnFreq { get; set; } + public long TripFreq { get; set; } +} + +public sealed record MotMonthLine(string Month, IReadOnlyList Trucks, IReadOnlyList Trips, long TrucksTotal, long TripsTotal); +public sealed record MotRegTypeBlock(string RegType, IReadOnlyList Months, IReadOnlyList AvgTrucksPerTrips, long AvgTrucksTotal, long TripsSum); +public sealed record MotMultiTripsReport( + int BucketCount, int MonthCount, + MotRegTypeBlock Individuals, MotRegTypeBlock Companies, + IReadOnlyList ChartCompanies, IReadOnlyList ChartIndividuals, + IReadOnlyList ChartCompaniesPct, IReadOnlyList ChartIndividualsPct, + long CompanyTrucks, long IndividualTrucks, long CompanyTrips, long IndividualTrips); + +// ------------------------------------------------------------------ phone approvals file import (ParseFile.cfc) + +public enum PhoneDecisionKind { Skip, Accept, Reject } + +public sealed record PhoneDecision(PhoneDecisionKind Kind, long PermitId, int DelayDays, string Remarks); + +public sealed record PhoneImportRowResult(int Line, long PermitId, string Action, bool Ok, string? Code, string Message); + +public sealed record PhoneImportResult(int Total, int Accepted, int Rejected, int Skipped, int Failed, + IReadOnlyList Rows, string Message); + +// ------------------------------------------------------------------ weighbridge file import + +public sealed class IrbidRecord +{ + public string Id { get; set; } = ""; + public string F1 { get; set; } = ""; // truck number ("60" + value) + public string F2 { get; set; } = ""; // weight + public string F3 { get; set; } = ""; + public string F4 { get; set; } = ""; + public string F5 { get; set; } = ""; + public string F6 { get; set; } = ""; + public string F7 { get; set; } = ""; + public string F8 { get; set; } = ""; + public string? F9 { get; set; } + public long Wid { get; set; } + public string FileName { get; set; } = ""; + public string Location { get; set; } = "ir"; +} + +public sealed class RsifehRecord +{ + public string Id { get; set; } = ""; + public string FileName { get; set; } = ""; + public string F1 { get; set; } = ""; + public string F2 { get; set; } = ""; + public string F3 { get; set; } = ""; + public string F4 { get; set; } = ""; + public DateTime? F5 { get; set; } + public DateTime? F6 { get; set; } + public DateTime? F7 { get; set; } + public DateTime? F8 { get; set; } + public string F9 { get; set; } = ""; + public string F10 { get; set; } = ""; + public string F11 { get; set; } = ""; + public string F12 { get; set; } = ""; + public string F13 { get; set; } = ""; +} + +public sealed record FileImportResult(string FileName, int Parsed, int Inserted, int Updated, int Skipped, int Failed, IReadOnlyList Errors); + +public sealed record WeighbridgeScanResult(int Files, IReadOnlyList Results); + +/// Result of syncing WEIGHBRIDGE_RAW_DATA into permits/events (jobs/getWeighbridgeEvents.cfm second half). +public sealed record RawSyncResult(int Candidates, int Matched, int NoPermit, int Failed); diff --git a/src/NTP.Application/Grains/Reports/ReportMath.cs b/src/NTP.Application/Grains/Reports/ReportMath.cs new file mode 100644 index 0000000..846e8a9 --- /dev/null +++ b/src/NTP.Application/Grains/Reports/ReportMath.cs @@ -0,0 +1,187 @@ +using System.Globalization; + +namespace NTP.Application.Grains.Reports; + +/// Pure calculations of Reports\TripsReports\*.cfm and the dashboard (no I/O, unit tested). +public static class TripsReportMath +{ + private static decimal Pct(decimal part, decimal whole) => whole == 0 ? 0 : Math.Round(part / whole * 100m, 2); + + /// numOfTripsAndTrucksRpt.cfm: companies (everyone except Badiya) are summed, Badiya is its own row. + public static NumOfTripsAndTrucksReport NumOfTrips(DateOnly from, DateOnly to, IReadOnlyList rows) + { + var companies = rows.Where(r => !r.IsBadiya).ToList(); + var badiya = rows.FirstOrDefault(r => r.IsBadiya); + // Legacy summed numOfTruk into the "all trips" total (copy/paste bug); allTripNum is summed here. + var total = new NumOfTripsTotals( + companies.Sum(r => r.CompanyShare), companies.Sum(r => r.AvgShare), companies.Sum(r => r.TotalShare), + companies.Sum(r => r.NumOfTruk), companies.Sum(r => r.AllTripNum), companies.Sum(r => r.AvrgTrips)); + return new NumOfTripsAndTrucksReport(from, to, companies, total, badiya, + total.TotalShare + (badiya?.TotalShare ?? 0), + total.Trucks + (badiya?.NumOfTruk ?? 0), + total.Trips + (badiya?.AllTripNum ?? 0), + total.TripsPct + (badiya?.AvrgTrips ?? 0)); + } + + /// QuotaRpt.cfm: companies vs individuals (Badiya). Percentages are 2-decimal here (legacy showed whole numbers). + public static QuotaReport Quota(DateOnly from, DateOnly to, IReadOnlyList rows) + { + var comp = rows.Where(r => !r.IsBadiya).ToList(); + var ind = rows.Where(r => r.IsBadiya).ToList(); + var compTrucks = comp.Sum(r => r.NumOfTruk); + var indTrucks = ind.Sum(r => r.NumOfTruk); + var all = compTrucks + indTrucks; + return new QuotaReport(from, to, + new QuotaLine("COMPANIES", compTrucks, Pct(compTrucks, all), comp.Sum(r => r.AllTripNum), comp.Sum(r => r.AvrgTrips)), + new QuotaLine("INDIVIDUALS", indTrucks, Pct(indTrucks, all), ind.Sum(r => r.AllTripNum), ind.Sum(r => r.AvrgTrips))); + } + + /// + /// freqOfTripRpt.cfm / TripsDistributionRpt.cfm / grainsDashboards.cfm. has 15 entries: + /// number of trucks that made 1..15 trips (nulls from SUM() must already be 0). + /// + public static FrequencyReport Frequency(DateOnly from, DateOnly to, IReadOnlyList trucksByTrips) + { + var trucks = new long[GrainsReportConstants.MaxTripsBucket]; + for (var i = 0; i < trucks.Length && i < trucksByTrips.Count; i++) trucks[i] = trucksByTrips[i]; + var trips = trucks.Select((t, i) => t * (i + 1)).ToArray(); + var totalTrucks = trucks.Sum(); + var totalTrips = trips.Sum(); + var tripsPct = trips.Select(t => Pct(t, totalTrips)).ToArray(); + + // TripsDistributionRpt.cfm groups: 1-3, 4-6, 7-9, 10-12, 13-15. (Legacy computed the "trips" column of groups 2..5 + // with the multipliers 1,2,3 - a copy/paste bug; the true per-bucket multiplier is used here.) + var groups = new List(); + for (var g = 0; g < 5; g++) + { + var lo = g * 3 + 1; var hi = lo + 2; + long gt = 0, gtr = 0; + for (var n = lo; n <= hi; n++) { gt += trucks[n - 1]; gtr += trips[n - 1]; } + groups.Add(new TripGroupLine($"{lo}-{hi}", lo, hi, gt, Pct(gt, totalTrucks), gtr, Pct(gtr, totalTrips))); + } + return new FrequencyReport(from, to, trucks, trips, tripsPct, totalTrucks, totalTrips, groups); + } + + /// DetailsRpt.cfm: rows grouped per company with a total line (trips sum + truck count). + public static DetailsReport Details(DateOnly from, DateOnly to, IReadOnlyList rows) + { + var groups = rows.GroupBy(r => r.Scac) + .Select(g => new DetailsGroup(g.Key, g.ToList(), g.Sum(x => x.Tt), g.Count())) + .ToList(); + return new DetailsReport(from, to, groups); + } +} + +/// weightbridgeEvents.cfm: collapses the event rows of a permit into one printable line. +public static class WeighbridgeEventMath +{ + private static decimal Parse(string? w) => + decimal.TryParse(w, NumberStyles.Number, CultureInfo.InvariantCulture, out var v) ? v : 0m; + + public static IReadOnlyList Pivot(IEnumerable raw) + { + var result = new List(); + var serial = 1; + foreach (var g in raw.GroupBy(r => r.Pid)) + { + decimal ltw = 0, lgw = 0, lnw = 0, dtw = 0, dgw = 0, dnw = 0; + string loadDate = "-", dischargeDate = "-"; + foreach (var e in g) + { + var w = Parse(e.Weight); + switch (e.EventType) + { + case "LTW": ltw = w; loadDate = e.EventDate ?? "-"; break; + case "LGW": lgw = w; break; + case "DTW": dtw = w; dischargeDate = e.EventDate ?? "-"; break; + case "DGW": dgw = w; break; + case "LNW": lnw = w; break; + case "DNW": dnw = w; dischargeDate = e.EventDate ?? "-"; break; + } + } + if (lnw == 0) lnw = lgw - ltw; + if (dnw == 0) dnw = dgw - dtw; + var netLoss = lnw - dnw; + var f = g.First(); + result.Add(new WeighbridgeEventRow(serial++, f.Pn, f.Tn, f.CargoType, f.Scac, f.Loc, + ltw, lgw, Math.Abs(lnw), loadDate, dtw, dgw, Math.Abs(dnw), dischargeDate, netLoss, + f.Drvr, f.Nnpn, $"العقبة \\ {f.OriginAddressId}")); + } + return result; + } +} + +/// Order label helpers of grains.cfc getOrderDetails (used by the phone-accept remark). +public static class GrainsOrderLabels +{ + public static string CargoTypeLabel(long? cargoType) => cargoType switch + { + 38 or 39 => "سائب", + 40 or 41 => "مشول", + _ => cargoType?.ToString() ?? "" + }; + + public static string LocationLabel(long? location) => location switch + { + 205 => "صوامع", + 210 => "مباشر", + 145 => "مستودعات الرز", + 105 => "الميناء الرئيسي/البضائع العامة", + 101 => "مستودعات العقبة", + 420 => "صوامع العقبة الجنوبية", + 110 => "الميناء الجنوبي/مباشر", + _ => location?.ToString() ?? "" + }; + + public static string OrderTypeLabel(string? ct) => ct switch + { + "PCKD" => "مشول", + "BULK_GALLAB" => "سائب قلاب", + "BULK" => "سائب", + _ => ct ?? "" + }; +} + +/// MOT multi-trips report (GNPermitsRpt.cfm / GrainsPermitsRpt.cfm): pivot of the GRAINSPERMITS view aggregate. +public static class MotMultiTripsBuilder +{ + public const int Buckets = 25; + + public static MotMultiTripsReport Build(IReadOnlyList rows) + { + var monthCount = Math.Max(1, rows.Select(r => r.Mm).Distinct().Count()); + var ind = Block("OWN", rows, monthCount); + var comp = Block("COMP", rows, monthCount); + + // TripDestriputionPerCount.cfm: average trucks per trips-bucket (avg of TN_freq over the rows present), 1..25. + long[] Avg(string reg) => Enumerable.Range(1, Buckets).Select(i => + { + var r = rows.Where(x => x.RegType == reg && x.Trips == i).Select(x => x.TnFreq).ToList(); + return r.Count == 0 ? 0L : (long)Math.Round(r.Average(), MidpointRounding.AwayFromZero); + }).ToArray(); + var c = Avg("COMP"); var o = Avg("OWN"); + // TripDestriputionPerPercentage.cfm + decimal[] PctOf(long[] a, long[] b) => a.Select((x, k) => x + b[k] > 0 ? Math.Round(x / (decimal)(x + b[k]) * 100m, 2) : 0m).ToArray(); + + return new MotMultiTripsReport(Buckets, monthCount, ind, comp, c, o, PctOf(c, o), PctOf(o, c), + comp.AvgTrucksTotal, ind.AvgTrucksTotal, comp.TripsSum, ind.TripsSum); + } + + private static MotRegTypeBlock Block(string reg, IReadOnlyList rows, int monthCount) + { + var sel = rows.Where(r => r.RegType == reg).ToList(); + var months = new List(); + foreach (var m in sel.Select(r => r.Mm).Distinct().OrderBy(x => x, StringComparer.Ordinal)) + { + var trucks = new long[Buckets]; var trips = new long[Buckets]; + foreach (var r in sel.Where(r => r.Mm == m && r.Trips is >= 1 and <= Buckets)) + { trucks[r.Trips - 1] = r.TnFreq; trips[r.Trips - 1] = r.TripFreq; } + months.Add(new MotMonthLine(m, trucks, trips, trucks.Sum(), trips.Sum())); + } + // "معدل الشاحنات": sum over months of TN_freq per bucket / number of months (all months of the report, legacy). + var avg = Enumerable.Range(1, Buckets).Select(i => + (long)Math.Round(sel.Where(r => r.Trips == i).Sum(r => r.TnFreq) / (double)monthCount, MidpointRounding.AwayFromZero)).ToArray(); + var totalAvg = (long)Math.Round(months.Sum(x => x.TrucksTotal) / (double)monthCount, MidpointRounding.AwayFromZero); + return new MotRegTypeBlock(reg, months, avg, totalAvg, months.Sum(x => x.TripsTotal)); + } +} diff --git a/src/NTP.Application/Grains/Reports/ReportsService.cs b/src/NTP.Application/Grains/Reports/ReportsService.cs new file mode 100644 index 0000000..c1470ae --- /dev/null +++ b/src/NTP.Application/Grains/Reports/ReportsService.cs @@ -0,0 +1,362 @@ +using NTP.Application.Abstractions; +using NTP.Application.Common; + +namespace NTP.Application.Grains.Reports; + +/// Reports, dashboards and Excel exports of the Grains module (legacy reports.cfc + Reports\*.cfm + *.cfr). +public sealed class ReportsService(IReportsRepository repo, IReportExcelService excel, ICurrentUser user) : IReportsService +{ + private ReportScope Scope() => new(user.UserId, user.RoleCode, user.LocationId, user.StkId, + long.TryParse(user.CompanyCode, out var c) ? c : null); + + public Task> CompaniesAsync(CancellationToken ct) => repo.CompaniesAsync(ct); + public Task> CargoTypesAsync(CancellationToken ct) => repo.CargoTypesAsync(ct); + + /// ownersTurn.cfm lists: BULK => gn_type in (BULK, BULK_GALLAB), anything else => PCKD (EX locations, status 1). + public Task> DestinationsAsync(string? shipmentMode, CancellationToken ct) => + repo.DestinationsAsync(string.Equals(shipmentMode, "BULK", StringComparison.OrdinalIgnoreCase) + ? ["BULK", "BULK_GALLAB"] : ["PCKD"], ct); + + private static void CheckRange(DateOnly from, DateOnly to) + { + if (to < from) throw new BusinessException("REPORT_RANGE_INVALID", "تاريخ النهاية يجب أن يكون بعد تاريخ البداية"); + } + + public async Task NumOfTripsAndTrucksAsync(DateOnly from, DateOnly to, CancellationToken ct) + { + CheckRange(from, to); + return TripsReportMath.NumOfTrips(from, to, await repo.TripsPerCompanyAsync(from, to, ct)); + } + + public async Task QuotaAsync(DateOnly from, DateOnly to, CancellationToken ct) + { + CheckRange(from, to); + return TripsReportMath.Quota(from, to, await repo.TripsPerCompanyAsync(from, to, ct)); + } + + public async Task FrequencyAsync(DateOnly from, DateOnly to, string? scac, string? cargoType, CancellationToken ct) + { + CheckRange(from, to); + scac = Zero(scac); cargoType = Zero(cargoType); + return TripsReportMath.Frequency(from, to, await repo.FrequencyAsync(from, to, scac, cargoType, ct)); + } + + /// Legacy: empty or "0" means "no filter". + private static string? Zero(string? v) => string.IsNullOrWhiteSpace(v) || v.Trim() == "0" ? null : v.Trim(); + + public async Task DetailsAsync(DateOnly from, DateOnly to, CancellationToken ct) + { + CheckRange(from, to); + return TripsReportMath.Details(from, to, await repo.DetailsAsync(from, to, ct)); + } + + public async Task MotMultiTripsAsync(CancellationToken ct) => + MotMultiTripsBuilder.Build(await repo.MotMultiTripsAsync(ct)); + + // ------------------------------------------------------------------ table reports + + private static ReportColumn C(string key, string ar, string en, string kind = "text") => new(key, ar, en, kind); + + private static string Fmt(DateOnly? d) => d?.ToString("yyyy/MM/dd") ?? ""; + + public async Task BuildTableAsync(string key, ReportFilter f, CancellationToken ct) + { + key = (key ?? "").ToLowerInvariant(); + if (!ReportKeys.All.Contains(key)) throw new NotFoundException("Report", key); + + if (key == ReportKeys.WeighbridgeEvents) return await WeighbridgeEventsAsync(f, ct); + + if (key == ReportKeys.Incapability) Validate(f); + if (key is ReportKeys.ClosedPermits or ReportKeys.LoadingWeights or ReportKeys.Incapability or ReportKeys.WaybridgeSummary + or ReportKeys.WaybridgeDetails or ReportKeys.MotGrainCube or ReportKeys.MotGrainFrequency) + { + if (f.From is null || f.To is null) throw new BusinessException("REPORT_DATES_REQUIRED", "يرجى تحديد الفترة (من - إلى)"); + CheckRange(f.From.Value, f.To.Value); + } + if ((key is ReportKeys.DistributionSummary or ReportKeys.OrderDistribution) && f.OrderDate is null) + throw new BusinessException("REPORT_ORDERDATE_REQUIRED", "يرجى تحديد تاريخ الطلبية"); + if (key == ReportKeys.OwnersTurn && f.DestAddressId is null) + throw new BusinessException("REPORT_DEST_REQUIRED", "يرجى تحديد الوجهة"); + + var raw = await repo.TableAsync(key, f, Scope(), ct); + return Shape(key, f, raw); + } + + /// GRINS_INCAPABILITY: the legacy page refuses a "to" date after yesterday. + private static void Validate(ReportFilter f) + { + var yesterday = DateOnly.FromDateTime(DateTime.Today.AddDays(-1)); + if (f.To is { } to && to > yesterday) + throw new BusinessException("REPORT_DATE_AFTER_YESTERDAY", "التاريخ لا يجوز ان يتجاوز " + yesterday.ToString("yyyy/MM/dd")); + } + + private static object? Get(IDictionary r, string key) + { + foreach (var kv in r) + if (string.Equals(kv.Key, key, StringComparison.OrdinalIgnoreCase)) return kv.Value is DBNull ? null : kv.Value; + return null; + } + + private static IReadOnlyList> Project(IReadOnlyList> raw, IReadOnlyList cols) + => raw.Select(r => (IReadOnlyDictionary)cols.ToDictionary(c => c.Key, c => Get(r, c.Key))).ToList(); + + private ReportTable Shape(string key, ReportFilter f, IReadOnlyList> raw) + { + var period = new List(); + if (f.From is not null) period.Add($"من: {Fmt(f.From)} إلى: {Fmt(f.To)}"); + + switch (key) + { + case ReportKeys.ClosedPermits: + return Make(key, "الارساليات المكتملة", "Completed permits", period, raw, + [ + C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم القاطرة", "Truck no."), C("company", "الشركة", "Company"), + C("cargoType", "نوع المادة", "Cargo"), C("origin", "موقع التحميل", "Loading site"), C("destination", "موقع التفريغ", "Discharge site"), + C("drvr", "اسم السائق", "Driver"), C("nnpn", "الرقم الوطني", "National no."), C("closeDate", "تاريخ الإغلاق", "Closed on", "datetime") + ]); + case ReportKeys.LoadingWeights: + return Make(key, "تقرير أوزان التحميل", "Loading weights", period, raw, + [ + C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم القاطرة", "Truck no."), C("company", "الشركة", "Company"), + C("cargoType", "نوع المادة", "Cargo"), C("origin", "موقع التحميل", "Loading site"), C("destination", "موقع التفريغ", "Discharge site"), + C("tare", "وزن الفارغ", "Tare", "number"), C("gross", "وزن القائم", "Gross", "number"), C("net", "الصافي", "Net", "number"), + C("eventDate", "تاريخ التحميل", "Loaded on", "datetime") + ]); + case ReportKeys.Incapability: return Incapability(period, raw); + case ReportKeys.WaybridgeSummary: + return Make(key, "تقرير إجمالي حركات القبان", "Weighbridge totals", [.. period, EventLine(f.EventType)], raw, + [ + C("company", "الشركة", "Company"), C("cargoType", "نوع المادة", "Cargo"), + C("trips", "عدد الحركات", "Movements", "number"), C("totalWeight", "إجمالي الوزن", "Total weight", "number") + ]); + case ReportKeys.WaybridgeDetails: + return Make(key, "تقرير تفصيلي لحركات القبان", "Weighbridge details", [.. period, EventLine(f.EventType)], raw, + [ + C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم القاطرة", "Truck no."), C("company", "الشركة", "Company"), + C("cargoType", "نوع المادة", "Cargo"), C("eventType", "نوع الحركة", "Event"), C("location", "الموقع", "Site"), + C("weight", "الوزن", "Weight", "number"), C("eventDate", "تاريخ الحركة", "Event date", "datetime"), C("doneBy", "المستخدم", "User") + ]); + case ReportKeys.TenderOrder: + return Make(key, "ارسالية عطاء التموين", "Tender order permits", TenderFilterLines(f), raw, + [ + C("phoneAccpt", "موافق : 1 | غير موافق : 0", "Phone approval"), C("statusCaption", "الحالة", "Status"), + C("destName", "الوجهة", "Destination"), C("remarks", "موقع التحميل", "Loading site"), C("tn", "رقم القاطرة", "Truck no."), + C("type", "نوع الحمولة", "Load type"), C("drvr", "اسم السائق", "Driver"), + C("creationDate", "تاريخ الإرسالية", "Permit date", "datetime"), C("phoneNumber", "رقم هاتف الشركة", "Company phone"), + C("compName", "اسم الشركة", "Company"), C("queueNo", "رقم الدور", "Queue no."), C("pn", "رقم الأرسالية", "Permit no.") + ], rowFix: r => { if (r["phoneAccpt"] is null or "") r["phoneAccpt"] = "لم يتم الاتصال بعد"; }); + case ReportKeys.DistributionSummary: + return Make(key, "ملخص التوزيع", "Distribution summary", [$"تاريخ الطلبية : {Fmt(f.OrderDate)}"], raw, + [ + C("name", "الشركة", "Company"), C("cnt", "العدد", "Count", "number"), C("shift", "الشفت", "Shift"), + C("orderDate", "تاريخ الطلبية", "Order date") + ]); + case ReportKeys.CallList: return CallList(raw); + case ReportKeys.CompaniesTurn: + return Make(key, "تقرير دور الشركات", "Companies turn", [$"نوع المادة: {f.ShipmentMode} نوع التوزيع: {f.DistributionType}"], raw, + [ + C("turn", "الدور", "Turn", "number"), C("scac", "رقم الشركة", "Company code"), C("company", "اسم الشركة", "Company"), + C("code", "نوع المادة", "Cargo"), C("type", "نوع التوزيع", "Distribution"), C("counter", "العداد", "Counter", "number") + ]); + case ReportKeys.OwnersTurn: + return Make(key, "تقرير دور الأفراد", "Individuals turn", [$"نوع المادة: {f.ShipmentMode} الوجهة: {f.DestAddressId}"], raw, + [ + C("turn", "الدور", "Turn", "number"), C("tn", "رقم القاطرة", "Truck no."), C("trips", "عدد الرحلات", "Trips", "number"), + C("lastTrip", "آخر رحلة", "Last trip", "datetime") + ]); + case ReportKeys.Drivers: + return Make(key, "تقرير السائقين المسجلين", "Registered drivers", [], raw, + [ + C("nnpn", "الرقم الوطني", "National no."), C("name", "الاسم", "Name"), C("dln", "رقم الرخصة", "Licence no."), + C("dled", "انتهاء الرخصة", "Licence expiry"), C("company", "الشركة", "Company"), C("status", "الحالة", "Status"), + C("createDate", "تاريخ التسجيل", "Registered on"), C("createUser", "المستخدم", "User") + ]); + case ReportKeys.Trucks: + return Make(key, "تقرير القاطرات المسجلة", "Registered trucks", [], raw, + [ + C("tn", "رقم القاطرة", "Truck no."), C("chasesNumber", "رقم الشاصي", "Chassis no."), C("company", "الشركة", "Company"), + C("status", "الحالة", "Status"), C("regDate", "تاريخ التسجيل", "Reg. date"), C("createDate", "تاريخ الإنشاء", "Created on"), + C("createUser", "المستخدم", "User") + ]); + case ReportKeys.OrderDistribution: return OrderDistribution(f, raw); + case ReportKeys.MotGrainCube: + return Make(key, "مكعب الحبوب (وزارة النقل)", "Grain cube (MOT)", period, raw, + [ + C("loc", "الوجهة", "Destination"), C("company", "الشركة", "Company"), C("trucks", "الشاحنات", "Trucks", "number"), + C("cTrucks", "شاحنات الشركات", "Company trucks", "number"), C("trails", "المقطورات", "Trailers", "number"), + C("cTrails", "مقطورات الشركات", "Company trailers", "number"), C("trips", "الرحلات", "Trips", "number"), + C("cTrips", "رحلات الشركات", "Company trips", "number") + ]); + case ReportKeys.MotGrainFrequency: + return Make(key, "تكرار رحلات الحبوب (وزارة النقل)", "Grain trip frequency (MOT)", period, raw, + [ + C("c", "عدد الرحلات", "Trips", "number"), C("contCnt", "أفراد - عدد", "Individuals - count", "number"), + C("contPerc", "أفراد %", "Individuals %", "number"), C("compCnt", "شركات - عدد", "Companies - count", "number"), + C("compPerc", "شركات %", "Companies %", "number") + ]); + default: throw new NotFoundException("Report", key); + } + } + + private static string EventLine(string? t) => "نوع الحركة: " + t switch + { + "LTW" => "قبان دخول موقع التحميل", "LGW" => "قبان خروج موقع التحميل", + "DTW" => "قبان دخول موقع التفريغ", "DGW" => "قبان خروج موقع التفريغ", _ => "الكل" + }; + + private static List TenderFilterLines(ReportFilter f) + { + var l = new List(); + if (!string.IsNullOrEmpty(f.ShipmentStatusCode)) l.Add($"الحالة: {f.ShipmentStatusCode}"); + if (f.OrderDate is not null) l.Add($"تاريخ الطلبية: {Fmt(f.OrderDate)}"); + if (f.DestAddressId is not null) l.Add($"الوجهة: {f.DestAddressId}"); + if (!string.IsNullOrEmpty(f.Tn)) l.Add($"رقم القاطرة: {f.Tn}"); + if (!string.IsNullOrEmpty(f.Scac)) l.Add($"رقم الشركة: {f.Scac}"); + return l; + } + + private static ReportTable Make(string key, string ar, string en, IReadOnlyList lines, + IReadOnlyList> raw, ReportColumn[] cols, Action>? rowFix = null) + { + var rows = Project(raw, cols); + if (rowFix is not null) + rows = rows.Select(r => { var d = r.ToDictionary(k => k.Key, k => k.Value); rowFix(d); return (IReadOnlyDictionary)d; }).ToList(); + return new ReportTable { Key = key, TitleAr = ar, TitleEn = en, Columns = cols, Rows = rows, FilterLines = lines }; + } + + private static decimal Num(object? v) => v is null ? 0m : Convert.ToDecimal(v, System.Globalization.CultureInfo.InvariantCulture); + + /// GRINS_INCAPABILITY (shortage = loaded net - discharged net). Net falls back to gross - tare like the weighbridge report. + private static ReportTable Incapability(IReadOnlyList period, IReadOnlyList> raw) + { + ReportColumn[] cols = + [ + C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم القاطرة", "Truck no."), C("company", "الشركة", "Company"), + C("cargoType", "نوع المادة", "Cargo"), C("destination", "موقع التفريغ", "Discharge site"), + C("loadNet", "صافي التحميل", "Loaded net", "number"), C("dischargeNet", "صافي التفريغ", "Discharged net", "number"), + C("shortage", "العجز", "Shortage", "number"), C("orderDate", "تاريخ الطلبية", "Order date", "date") + ]; + var rows = new List>(); + foreach (var r in raw) + { + var lnw = Num(Get(r, "lnw")); if (lnw == 0) lnw = Num(Get(r, "lgw")) - Num(Get(r, "ltw")); + var dnw = Num(Get(r, "dnw")); if (dnw == 0) dnw = Num(Get(r, "dgw")) - Num(Get(r, "dtw")); + lnw = Math.Abs(lnw); dnw = Math.Abs(dnw); + rows.Add(new Dictionary + { + ["pn"] = Get(r, "pn"), ["tn"] = Get(r, "tn"), ["company"] = Get(r, "company"), ["cargoType"] = Get(r, "cargoType"), + ["destination"] = Get(r, "destination"), ["loadNet"] = lnw, ["dischargeNet"] = dnw, ["shortage"] = lnw - dnw, + ["orderDate"] = Get(r, "orderDate") + }); + } + rows = rows.OrderByDescending(x => Num(x["shortage"])).ToList(); + return new ReportTable + { + Key = ReportKeys.Incapability, TitleAr = "تقرير العجز", TitleEn = "Shortage report", Columns = cols, Rows = rows, FilterLines = period, + Extra = new Dictionary { ["totalShortage"] = rows.Sum(x => Num(x["shortage"])) } + }; + } + + /// callRpt.cfm: IVR call list (Name, Phone, Code1.. sound-file names). "DayNight" derives from MOBILE_SHIFT. + private static ReportTable CallList(IReadOnlyList> raw) + { + ReportColumn[] cols = + [ + C("name", "Name", "Name"), C("phone", "Phone", "Phone"), C("code1", "Code1", "Code1"), C("code2", "Code2", "Code2"), + C("number1", "Number1", "Number1"), C("number2", "Number2", "Number2"), C("number3", "Number3", "Number3"), + C("number4", "Number4", "Number4"), C("number5", "Number5", "Number5"), C("item", "Item", "Item"), + C("fromDist", "From", "From"), C("origin", "Origin", "Origin"), C("week", "Week", "Week"), C("day", "Day", "Day"), + C("month", "Month", "Month"), C("dayNight", "DayNight", "DayNight"), C("id", "ID", "ID") + ]; + var projected = Project(raw, cols); + var rows = new List>(); + for (var i = 0; i < projected.Count; i++) + { + var d = projected[i].ToDictionary(k => k.Key, k => k.Value); + d["dayNight"] = Get(raw[i], "mobileShift")?.ToString() switch { "1" => @"c:\\D.wav", "2" => @"c:\\E.wav", "3" => @"c:\\N.wav", _ => "" }; + rows.Add(d); + } + return new ReportTable { Key = ReportKeys.CallList, TitleAr = "قائمة الاتصال", TitleEn = "Call list", Columns = cols, Rows = rows }; + } + + /// grainsOrder.cfm: first block = individuals vs companies totals, second = per destination with percentages. + private static ReportTable OrderDistribution(ReportFilter f, IReadOnlyList> raw) + { + ReportColumn[] cols = + [ + C("dest", "الوجهة", "Destination"), C("ahale", "عدد الافراد", "Individuals", "number"), C("ahalePct", "نسبة الافراد", "Individuals %", "number"), + C("company", "عدد الشركات", "Companies", "number"), C("companyPct", "نسبة الشركات", "Companies %", "number"), C("total", "المجموع", "Total", "number") + ]; + var rows = new List>(); + foreach (var r in raw) + { + var a = Num(Get(r, "ahale")); var c = Num(Get(r, "company")); var all = a + c; + rows.Add(new Dictionary + { + ["dest"] = Get(r, "dest"), ["ahale"] = a, ["ahalePct"] = all == 0 ? 0m : Math.Round(a / all * 100m, 1), + ["company"] = c, ["companyPct"] = all == 0 ? 0m : Math.Round(c / all * 100m, 1), ["total"] = all + }); + } + var totA = rows.Sum(x => Num(x["ahale"])); var totC = rows.Sum(x => Num(x["company"])); var tot = totA + totC; + return new ReportTable + { + Key = ReportKeys.OrderDistribution, TitleAr = "نسب التوزيع في طلبيات السائب", TitleEn = "Bulk order distribution", + Columns = cols, Rows = rows, FilterLines = [$"تاريخ الطلبية : {Fmt(f.OrderDate)}"], + Extra = new Dictionary + { + ["individuals"] = totA, ["companies"] = totC, ["total"] = tot, + ["individualsPct"] = tot == 0 ? 0m : Math.Round(totA / tot * 100m, 2), + ["companiesPct"] = tot == 0 ? 0m : Math.Round(totC / tot * 100m, 2) + } + }; + } + + private async Task WeighbridgeEventsAsync(ReportFilter f, CancellationToken ct) + { + if (f.From is null || f.To is null) throw new BusinessException("REPORT_DATES_REQUIRED", "يرجى تحديد الفترة (من - إلى)"); + CheckRange(f.From.Value, f.To.Value); + // Legacy: role GNDSTV only sees the movements of its own location. + long? loc = user.IsInRole("GNDSTV") ? (user.LocationId ?? -1) : null; + var raw = await repo.WeighbridgeEventsAsync(f.From.Value, f.To.Value, loc, ct); + var pivot = WeighbridgeEventMath.Pivot(raw); + ReportColumn[] cols = + [ + C("serial", "الرقم التسلسلي", "#", "number"), C("pn", "رقم الإرسالية", "Permit no."), C("tn", "رقم السيارة", "Truck no."), + C("cargoType", "نوع المادة", "Cargo"), C("scac", "الشركة", "Company"), C("loc", "موقع التفريغ", "Discharge site"), + C("ltw", "وزن الفارغ (تحميل)", "Load tare", "number"), C("lgw", "وزن القائم (تحميل)", "Load gross", "number"), + C("lnw", "الصافي (تحميل)", "Load net", "number"), C("loadDate", "تاريخ التحميل", "Loaded on"), + C("dtw", "وزن الفارغ (تفريغ)", "Discharge tare", "number"), C("dgw", "وزن القائم (تفريغ)", "Discharge gross", "number"), + C("dnw", "الصافي (تفريغ)", "Discharge net", "number"), C("dischargeDate", "تاريخ التفريغ", "Discharged on"), + C("netLoss", "صافي النقص", "Net loss", "number"), C("drvr", "اسم السائق", "Driver"), C("nnpn", "الرقم الوطني", "National no."), + C("origin", "جهة التحميل", "Origin") + ]; + var rows = pivot.Select(p => (IReadOnlyDictionary)new Dictionary + { + ["serial"] = p.Serial, ["pn"] = p.Pn, ["tn"] = p.Tn, ["cargoType"] = p.CargoType, ["scac"] = p.Scac, ["loc"] = p.Loc, + ["ltw"] = p.Ltw, ["lgw"] = p.Lgw, ["lnw"] = p.Lnw, ["loadDate"] = p.LoadDate, ["dtw"] = p.Dtw, ["dgw"] = p.Dgw, + ["dnw"] = p.Dnw, ["dischargeDate"] = p.DischargeDate, ["netLoss"] = p.NetLoss, ["drvr"] = p.Drvr, ["nnpn"] = p.Nnpn, ["origin"] = p.Origin + }).ToList(); + return new ReportTable + { + Key = ReportKeys.WeighbridgeEvents, TitleAr = "تقارير حركات قبان التحميل والتفريغ", TitleEn = "Loading and discharge weighbridge movements", + Columns = cols, Rows = rows, FilterLines = [$"تاريخ الحركات : من : {Fmt(f.From)} إلى : {Fmt(f.To)}"] + }; + } + + // ------------------------------------------------------------------ paging + export + + public async Task PageAsync(string key, ReportFilter filter, int page, int pageSize, CancellationToken ct) + { + var t = await BuildTableAsync(key, filter, ct); + var req = new PageRequest(page, pageSize); + var items = t.Rows.Skip(req.MinRow).Take(req.SafePageSize).ToList(); + return new ReportPage(items, req.SafePage, req.SafePageSize, t.Rows.Count, t.Columns, t.Extra); + } + + public async Task<(byte[] Content, string FileName)> ExportAsync(string key, ReportFilter filter, CancellationToken ct) + { + var t = await BuildTableAsync(key, filter, ct); + var bytes = excel.Build(t, user.UserId, DateTime.Now, user.Lang != "EN"); + return (bytes, $"{t.Key}-{DateTime.Now:yyyyMMdd-HHmm}.xlsx"); + } +} diff --git a/src/NTP.Application/Grains/Reports/WsRules.cs b/src/NTP.Application/Grains/Reports/WsRules.cs new file mode 100644 index 0000000..dc6a452 --- /dev/null +++ b/src/NTP.Application/Grains/Reports/WsRules.cs @@ -0,0 +1,82 @@ +using System.Globalization; + +namespace NTP.Application.Grains.Reports; + +/// Weighbridge transaction codes of ws.cfc addWeightBridgeEvent (errorcode 0..4). +public static class WbCodes +{ + public const string Ok = "0"; + public const string WrongStatus = "1"; + public const string LocationNotOnRoute = "2"; + public const string AssignDestError = "3"; + public const string Generic = "4"; + + public const string MsgOk = "تمت العملية بنجاح"; + public const string MsgWrongStatus = "حالة السيارة غير صحيحة"; + public const string MsgLocationNotOnRoute = "الموقع غير موجود على مسار الشاحنة"; +} + +/// The decision table of ws.cfc addWeightBridgeEvent (pure: unit tested). +public sealed record WbPlan(string EventType, string CurrentStatus, string? NewPermitStatus, string? Action, bool UseProvidedEventDate); + +public static class WbRules +{ + public enum LocationType { None, Origin, Destination } + + public static LocationType Locate(long? originId, long? destinationId, long locationId) => + originId == locationId ? LocationType.Origin + : destinationId == locationId ? LocationType.Destination + : LocationType.None; + + /// + /// Returns the plan for (location type, EN/EX, current permit status) or null when the status is not valid for that step + /// (errorcode 1). Unknown trxType -> null plan with = true (errorcode 4). + /// + public static WbPlan? Plan(LocationType loc, string trxType, string status, out bool generic) + { + generic = false; + var t = (trxType ?? "").Trim().ToUpperInvariant(); + switch (loc, t) + { + case (LocationType.Origin, "EN"): // LTW, status unchanged + return status is "ACCPT" or "RESD" ? new WbPlan("LTW", status, null, null, true) : null; + case (LocationType.Origin, "EX"): // LGW -> ACTRL + return status is "ACCPT" or "RESD" or "ACTRL" ? new WbPlan("LGW", "ACTRL", "ACTRL", "printPage1", true) : null; + case (LocationType.Destination, "EN"): // DGW -> CLRPR + return status is "ACCPT" or "RESD" or "ACTRL" or "CLRPR" ? new WbPlan("DGW", "CLRPR", "CLRPR", null, false) : null; + case (LocationType.Destination, "EX"): // DTW -> CLOSE + return status == "CLRPR" ? new WbPlan("DTW", "CLOSE", "CLOSE", "printPage2", false) : null; + default: + generic = true; + return null; + } + } + + /// Accepts the legacy "yyyymmdd HH24miss" and the compact "yyyymmddHH24miss" (what grains.cfc sends). + public static bool TryParseEventDate(string? s, out DateTime value) + { + string[] fmts = ["yyyyMMdd HHmmss", "yyyyMMddHHmmss"]; + return DateTime.TryParseExact((s ?? "").Trim(), fmts, CultureInfo.InvariantCulture, DateTimeStyles.None, out value); + } +} + +/// grains.cfc generatePermitNumber. +public static class PermitNumber +{ + private static string Pad(long n, int width) => n.ToString(CultureInfo.InvariantCulture).PadLeft(width, '0'); + + /// Returns null for a cargo type other than BULK/PCKD (legacy left PN empty). + public static string? Generate(string tt, long seq, string companyCode, long tenderCount) + { + var badiya = companyCode == GrainsReportConstants.BadiyaScac; + var pckdTender = 41 + tenderCount; + return (badiya, (tt ?? "").ToUpperInvariant()) switch + { + (true, "BULK") => "30" + Pad(tenderCount, 2) + Pad(seq, 6), + (true, "PCKD") => "3" + pckdTender.ToString(CultureInfo.InvariantCulture) + Pad(seq, 7), + (false, "BULK") => "1" + Pad(tenderCount, 2) + Pad(seq, 6), + (false, "PCKD") => "1" + pckdTender.ToString(CultureInfo.InvariantCulture) + Pad(seq, 6), + _ => null + }; + } +} diff --git a/src/NTP.Application/Grains/Reports/WsService.cs b/src/NTP.Application/Grains/Reports/WsService.cs new file mode 100644 index 0000000..6c60fa5 --- /dev/null +++ b/src/NTP.Application/Grains/Reports/WsService.cs @@ -0,0 +1,276 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; + +namespace NTP.Application.Grains.Reports; + +// ------------------------------------------------------------------ contracts (legacy ws.cfc) + +public sealed record GetTrackNoRequest(string TN, string TRNAT, string? CloseDate); +public sealed record ChangeStatusToReqstRequest(string TN); +public sealed record SaveShipmentInfoRequest(string PN, string CargoType, string UserId, string AddressId, string Weight, string? Domain); +public sealed record LoadingWeightRequest(long Pid, string UserId, string LocationId, string TareWeight, string GrossWeight, string NetWeight); +public sealed record CreatePermitRecordRequest(string? TN, string? SCAC, string? NextStatus, string? TT, bool? CheckStatuses); +public sealed record WeighbridgeEventRequest(string TN, string Weight, long LocationId, string EventDate, string TrxType, string UserId); + +public sealed record WsResult(bool Success, string Code, string Message, IReadOnlyDictionary? Data = null); + +/// ws.cfc addWeightBridgeEvent: errorcode "0".."4" + Arabic MSG (kept verbatim for the integrating systems). +public sealed record WbEventResult(string ErrorCode, string Msg, string? Action = null, long? PermitId = null, + string? EventType = null, long? LocationId = null); + +public sealed record WbPermit(long Id, string ShipmentStatusCode, long? OriginAddressId, long? DestinationAddressId); + +public sealed record QueuedPermit(string? Pn, DateTime? CreationDate); + +public sealed record NewPermit(string Pn, string Tn, string CompanyCode, string StatusCode, string Tt, long? TripCounter); + +public sealed record WsWbEventInsert(long PermitId, DateTime? EventDate, string EventType, string PrevStatus, string CurrentStatus, + string DoneBy, long LocationId, decimal Weight); + +public interface IWsRepository +{ + Task CloseActivePermitsAsync(string tn, string user, CancellationToken ct); + Task FindQueuedAsync(string tn, CancellationToken ct); + /// grains.cfc getNextTrackingNo: first of the next 7 days where quota is not exhausted (trackNo 0 when none). + Task<(long TrackNo, string QueueDate)> NextTrackingNoAsync(CancellationToken ct); + Task InsertQueuedPermitAsync(string tn, string trnat, long pn, string queueDate, CancellationToken ct); + + Task> OpenPermitIdsAsync(string tn, CancellationToken ct); + Task UpdateStatusByTnAsync(string tn, string fromStatus, string toStatus, string user, CancellationToken ct); + + Task TruckCompanyIfRegisteredAsync(string tn, CancellationToken ct); + Task HasActivePermitAsync(string tn, string tt, bool checkAllStatuses, CancellationToken ct); + Task NextQueueSequenceAsync(bool badiya, CancellationToken ct); + Task TripCounterAsync(string tt, CancellationToken ct); + Task TenderCountAsync(CancellationToken ct); + Task InsertPermitAsync(NewPermit p, CancellationToken ct); + + Task PermitExistsAsync(long pid, CancellationToken ct); + Task UpdatePermitStatusAsync(long pid, string status, string user, CancellationToken ct); + Task PermitIdByPnAsync(string pn, CancellationToken ct); + Task UpdateShipmentModeAsync(long pid, string cargoType, CancellationToken ct); + + Task FindWbPermitAsync(string tn, CancellationToken ct); + Task InsertWbEventAsync(WsWbEventInsert e, CancellationToken ct); + Task LogIntegrationAsync(string? ip, string tn, string argsJson, CancellationToken ct); +} + +public interface IWsService +{ + Task GetTrackNoAsync(GetTrackNoRequest r, string caller, CancellationToken ct); + Task ChangeStatusToReqstAsync(ChangeStatusToReqstRequest r, string caller, CancellationToken ct); + Task SaveShipmentInfoAsync(SaveShipmentInfoRequest r, string caller, CancellationToken ct); + Task AddLoadingWeightEventAsync(LoadingWeightRequest r, string caller, CancellationToken ct); + Task AddDischargeWeightEventAsync(LoadingWeightRequest r, string caller, CancellationToken ct); + Task CreatePermitRecordAsync(CreatePermitRecordRequest r, string caller, CancellationToken ct); + /// addWeightBridgeEventWS: logs the call to GN_TCS_INTEGRATION first, then runs the same logic. + Task AddWeightBridgeEventWsAsync(WeighbridgeEventRequest r, string caller, string? remoteIp, CancellationToken ct); + /// addWeightBridgeEvent (public, used by the screens and the file importers). + Task AddWeightBridgeEventAsync(WeighbridgeEventRequest r, CancellationToken ct); +} + +// ------------------------------------------------------------------ validators + +public sealed class GetTrackNoRequestValidator : AbstractValidator +{ + public GetTrackNoRequestValidator() + { + RuleFor(x => x.TN).NotEmpty().MaximumLength(20); + RuleFor(x => x.TRNAT).NotEmpty().MaximumLength(20); + } +} + +public sealed class WeighbridgeEventRequestValidator : AbstractValidator +{ + public WeighbridgeEventRequestValidator() + { + RuleFor(x => x.TN).NotEmpty().MaximumLength(20); + RuleFor(x => x.Weight).Must(w => decimal.TryParse(w, System.Globalization.NumberStyles.Number, + System.Globalization.CultureInfo.InvariantCulture, out var v) && v >= 0).WithMessage("الوزن غير صحيح"); + RuleFor(x => x.TrxType).Must(t => t is not null && (t.Equals("EN", StringComparison.OrdinalIgnoreCase) || t.Equals("EX", StringComparison.OrdinalIgnoreCase))) + .WithMessage("trxType must be EN or EX"); + RuleFor(x => x.EventDate).Must(d => WbRules.TryParseEventDate(d, out _)).WithMessage("EVENTDATE must be yyyyMMdd HHmmss"); + RuleFor(x => x.UserId).NotEmpty().MaximumLength(30); + } +} + +public sealed class LoadingWeightRequestValidator : AbstractValidator +{ + public LoadingWeightRequestValidator() + { + RuleFor(x => x.Pid).GreaterThan(0); + RuleFor(x => x.UserId).NotEmpty().MaximumLength(30); + RuleFor(x => x.LocationId).NotEmpty(); + RuleFor(x => x.TareWeight).Must(IsNumber).WithMessage("الوزن غير صحيح"); + RuleFor(x => x.GrossWeight).Must(IsNumber).WithMessage("الوزن غير صحيح"); + RuleFor(x => x.NetWeight).Must(IsNumber).WithMessage("الوزن غير صحيح"); + } + + private static bool IsNumber(string? w) => decimal.TryParse(w, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out _); +} + +// ------------------------------------------------------------------ service + +/// +/// Port of ws.cfc. The caller id replaces legacy session.userid (default "system"): JWT user id or the API-key name. +/// +public sealed class WsService( + IWsRepository repo, IEventLogger events, IUnitOfWork uow, + IValidator trackNoValidator, + IValidator wbValidator, + IValidator weightValidator) : IWsService +{ + public const string TcsUser = "TCSWS"; + private const string Ok = "تمت العملية بنجاح"; + + private static WsResult Fail(string code, string msg) => new(false, code, msg); + + public async Task GetTrackNoAsync(GetTrackNoRequest r, string caller, CancellationToken ct) + { + await trackNoValidator.ValidateAndThrowAsync(r, ct); + return await uow.ExecuteInTransactionAsync(async t => + { + // 1. close the truck's old active permits (everything active except QUED) + await repo.CloseActivePermitsAsync(r.TN, caller, t); + + // 2. refuse when a QUED one exists (legacy returns the text, the close above stays committed) + var queued = await repo.FindQueuedAsync(r.TN, t); + if (queued is not null) + return Fail("TRUCK_HAS_QUEUED_REQUEST", + $"الشاحنة لديها طلب أخر
رقم الدور {queued.Pn} بتاريخ {queued.CreationDate:dd-MM-yyyy}"); + + // 3. next queue number within the quota + var (trackNo, queueDate) = await repo.NextTrackingNoAsync(t); + if (trackNo <= 0) + return Fail("NO_QUOTA_AVAILABLE", "لا توجد حصة متاحة لتسجيل دور جديد"); + + var id = await repo.InsertQueuedPermitAsync(r.TN, r.TRNAT, trackNo, queueDate, t); + await events.AddAsync(new EventEntry("PERMITID", id, "", "QUED", TcsUser, "CREATE", "GN", "", TcsUser), t); + return new WsResult(true, "OK", $"{trackNo} {queueDate}", + new Dictionary { ["permitId"] = id, ["pn"] = trackNo, ["queueDate"] = queueDate }); + }, ct); + } + + public async Task ChangeStatusToReqstAsync(ChangeStatusToReqstRequest r, string caller, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(r.TN)) throw new BusinessException("TN_REQUIRED", "رقم القاطرة مطلوب"); + return await uow.ExecuteInTransactionAsync(async t => + { + var ids = await repo.OpenPermitIdsAsync(r.TN, t); + if (ids.Count == 0) return Fail("NO_OPEN_PERMIT", "لا يوجد إرسالية مفتوحة لهذه القاطرة"); + await repo.UpdateStatusByTnAsync(r.TN, "OPEN", "REQST", caller, t); + foreach (var id in ids) + await events.AddAsync(new EventEntry("PERMITID", id, "OPEN", "REQST", "SYSTEM", "OVRD", "GN", "", TcsUser), t); + return new WsResult(true, "OK", Ok); + }, ct); + } + + /// Commented out in the legacy ws.cfc (PH domain, 'WEIGH' event); ported for completeness, see the controller gate. + public async Task SaveShipmentInfoAsync(SaveShipmentInfoRequest r, string caller, CancellationToken ct) + { + if (!long.TryParse(r.PN, out _)) throw new BusinessException("PN_INVALID", "Wrong PN"); + return await uow.ExecuteInTransactionAsync(async t => + { + var id = await repo.PermitIdByPnAsync(r.PN, t); + if (id is null) return Fail("WRONG_PN", "Wrong PN"); + await repo.UpdateShipmentModeAsync(id.Value, r.CargoType, t); + await events.AddAsync(new EventEntry("PERMITID", id.Value, "", "", r.UserId, "WEIGH", + string.IsNullOrEmpty(r.Domain) ? "PH" : r.Domain, r.AddressId, "NTP", r.Weight), t); + return new WsResult(true, "OK", Ok); + }, ct); + } + + public Task AddLoadingWeightEventAsync(LoadingWeightRequest r, string caller, CancellationToken ct) => + WeightEvents(r, caller, ("LTW", "LGW", "LNW"), "RESD", "ACTRL", ct); + + public Task AddDischargeWeightEventAsync(LoadingWeightRequest r, string caller, CancellationToken ct) => + WeightEvents(r, caller, ("DTW", "DGW", "DNW"), "ACTRL", "CLOSE", ct); + + private async Task WeightEvents(LoadingWeightRequest r, string caller, (string Tare, string Gross, string Net) types, + string prev, string next, CancellationToken ct) + { + await weightValidator.ValidateAndThrowAsync(r, ct); + return await uow.ExecuteInTransactionAsync(async t => + { + if (!await repo.PermitExistsAsync(r.Pid, t)) throw new NotFoundException("Permit", r.Pid); + await events.AddAsync(new EventEntry("PERMITID", r.Pid, prev, prev, r.UserId, types.Tare, "GN", r.LocationId, "NTP", r.TareWeight), t); + await events.AddAsync(new EventEntry("PERMITID", r.Pid, prev, prev, r.UserId, types.Gross, "GN", r.LocationId, "NTP", r.GrossWeight), t); + await events.AddAsync(new EventEntry("PERMITID", r.Pid, prev, prev, r.UserId, types.Net, "GN", r.LocationId, "NTP", r.NetWeight), t); + await repo.UpdatePermitStatusAsync(r.Pid, next, caller, t); + await events.AddAsync(new EventEntry("PERMITID", r.Pid, prev, next, r.UserId, "OVRD", "GN", r.LocationId, "NTP"), t); + return new WsResult(true, "OK", Ok); + }, ct); + } + + public async Task CreatePermitRecordAsync(CreatePermitRecordRequest r, string caller, CancellationToken ct) + { + var tn = (r.TN ?? "").Trim(); + var scac = (r.SCAC ?? "").Trim(); + var next = string.IsNullOrWhiteSpace(r.NextStatus) ? "OPEN" : r.NextStatus.Trim(); + var tt = (r.TT ?? "").Trim(); + if (tn.Length == 0 && scac.Length == 0) + return Fail("INVALID_ARGUMENTS", "Invalid arguments, TN or SCAC is required"); + + return await uow.ExecuteInTransactionAsync(async t => + { + if (tn.Length > 0) + { + var truckScac = await repo.TruckCompanyIfRegisteredAsync(tn, t); + if (truckScac is null) return Fail("TRUCK_NOT_REGISTERED", $"القاطرة رقم: {tn} غير مسجلة "); + if (await repo.HasActivePermitAsync(tn, tt, r.CheckStatuses ?? true, t)) + return Fail("TRUCK_HAS_ACTIVE_PERMIT", $"القاطره رقم: {tn} ، لها دور فعّال "); + if (scac.Length == 0) scac = truckScac; // legacy left SCAC empty here (and then failed); the truck's company is the evident intent + } + var badiya = scac == GrainsReportConstants.BadiyaScac; + var seq = await repo.NextQueueSequenceAsync(badiya, t); + long? tripCounter = badiya ? await repo.TripCounterAsync(tt, t) : null; + var pn = PermitNumber.Generate(tt, seq, scac, await repo.TenderCountAsync(t)); + if (pn is null) return Fail("TT_UNSUPPORTED", "نوع المادة غير مدعوم لتوليد رقم الإرسالية"); + + var id = await repo.InsertPermitAsync(new NewPermit(pn, tn, scac, next, tt, tripCounter), t); + await events.AddAsync(new EventEntry("PERMITID", id, "", next, "SYSTEM", "OVRD", "GN", "", "NTP"), t); + return new WsResult(true, "OK", "تمت العملية بنجاح ورقم الإرسالية هو : " + pn, + new Dictionary { ["permitId"] = id, ["pn"] = pn }); + }, ct); + } + + public async Task AddWeightBridgeEventWsAsync(WeighbridgeEventRequest r, string caller, string? remoteIp, CancellationToken ct) + { + await wbValidator.ValidateAndThrowAsync(r, ct); + // The legacy audit row is written before (and independent of) the event logic. + await repo.LogIntegrationAsync(remoteIp, r.TN, System.Text.Json.JsonSerializer.Serialize(r), ct); + return await AddWeightBridgeEventAsync(r, ct); + } + + public async Task AddWeightBridgeEventAsync(WeighbridgeEventRequest r, CancellationToken ct) + { + await wbValidator.ValidateAndThrowAsync(r, ct); + WbRules.TryParseEventDate(r.EventDate, out var eventDate); + var weight = decimal.Parse(r.Weight, System.Globalization.CultureInfo.InvariantCulture); + var trx = r.TrxType.Trim().ToUpperInvariant(); + + return await uow.ExecuteInTransactionAsync(async t => + { + var p = await repo.FindWbPermitAsync(r.TN, t); + if (p is null) return new WbEventResult(WbCodes.WrongStatus, WbCodes.MsgWrongStatus); + + var loc = WbRules.Locate(p.OriginAddressId, p.DestinationAddressId, r.LocationId); + if (loc == WbRules.LocationType.None) return new WbEventResult(WbCodes.LocationNotOnRoute, WbCodes.MsgLocationNotOnRoute); + + var plan = WbRules.Plan(loc, trx, p.ShipmentStatusCode, out var generic); + if (plan is null) + return generic ? new WbEventResult(WbCodes.Generic, "") : new WbEventResult(WbCodes.WrongStatus, WbCodes.MsgWrongStatus); + + // Origin events carry the device's timestamp; destination events are stamped by the database (legacy). + await repo.InsertWbEventAsync(new WsWbEventInsert(p.Id, plan.UseProvidedEventDate ? eventDate : null, plan.EventType, + p.ShipmentStatusCode, plan.CurrentStatus, plan.UseProvidedEventDate ? $"W{r.LocationId}" : r.UserId, r.LocationId, weight), t); + + if (plan.NewPermitStatus is not null) + await repo.UpdateStatusByTnAsync(r.TN, p.ShipmentStatusCode, plan.NewPermitStatus, "system", t); + + return new WbEventResult(WbCodes.Ok, WbCodes.MsgOk, plan.Action, plan.Action is null ? null : p.Id, + plan.EventType == "DTW" ? "DTW" : null, plan.EventType == "DTW" ? r.LocationId : null); + }, ct); + } +} diff --git a/src/NTP.Application/Lookups/LookupContracts.cs b/src/NTP.Application/Lookups/LookupContracts.cs new file mode 100644 index 0000000..044c448 --- /dev/null +++ b/src/NTP.Application/Lookups/LookupContracts.cs @@ -0,0 +1,57 @@ +namespace NTP.Application.Lookups; + +/// STATUS row (CODE, DESCRIPTION, DOMAIN, ISACTIVE). +public sealed class StatusDto +{ + public string Code { get; set; } = string.Empty; + public string? Description { get; set; } + public int? IsActive { get; set; } +} + +/// LOCATIONS row (ID, NAME, TYPE, DOMAIN). Types seen: LOC, EX (exit/destination), EN (entry). +public sealed class LocationDto +{ + public long Id { get; set; } + public string? Name { get; set; } + public string? Type { get; set; } + public string? Domain { get; set; } +} + +/// CARGOTYPE row (ID, NAME, DOMAIN). +public sealed class CargoTypeDto +{ + public long Id { get; set; } + public string? Name { get; set; } + public string? Domain { get; set; } +} + +/// COMPANIES row. Code is COMPANIES.DESCRIPTION (legacy "companyCode"). +public sealed class CompanyDto +{ + public long Id { get; set; } + public string? Name { get; set; } + public string? Code { get; set; } +} + +/// NATIONALITY (LANGID = 0) row. +public sealed class NationalityDto +{ + public string Code { get; set; } = string.Empty; + public string? Name { get; set; } +} + +public sealed class CityDto +{ + public long Id { get; set; } + public string? Name { get; set; } +} + +public interface ILookupRepository +{ + Task> GetStatusesAsync(string domain, bool? isActive, CancellationToken ct = default); + Task> GetLocationsAsync(string domain, string? type, bool includeInactive, CancellationToken ct = default); + Task> GetCargoTypesAsync(string domain, CancellationToken ct = default); + Task> GetCompaniesAsync(bool includeInactive, CancellationToken ct = default); + Task> GetNationalitiesAsync(CancellationToken ct = default); + Task> GetCitiesAsync(CancellationToken ct = default); +} diff --git a/src/NTP.Application/Lookups/LookupService.cs b/src/NTP.Application/Lookups/LookupService.cs new file mode 100644 index 0000000..a01ceee --- /dev/null +++ b/src/NTP.Application/Lookups/LookupService.cs @@ -0,0 +1,36 @@ +using NTP.Application.Abstractions; + +namespace NTP.Application.Lookups; + +public interface ILookupService +{ + Task> StatusesAsync(string? domain, bool? isActive, CancellationToken ct); + Task> LocationsAsync(string? domain, string? type, bool includeInactive, CancellationToken ct); + Task> CargoTypesAsync(string? domain, CancellationToken ct); + Task> CompaniesAsync(bool includeInactive, CancellationToken ct); + Task> NationalitiesAsync(CancellationToken ct); + Task> CitiesAsync(CancellationToken ct); +} + +/// Generic lookups. Domain defaults to the caller's domain (legacy session.domain). +public sealed class LookupService(ILookupRepository repository, ICurrentUser user) : ILookupService +{ + private string DomainOrCurrent(string? domain) => + string.IsNullOrWhiteSpace(domain) ? user.Domain : domain.Trim().ToUpperInvariant(); + + public Task> StatusesAsync(string? domain, bool? isActive, CancellationToken ct) => + repository.GetStatusesAsync(DomainOrCurrent(domain), isActive, ct); + + public Task> LocationsAsync(string? domain, string? type, bool includeInactive, CancellationToken ct) => + repository.GetLocationsAsync(DomainOrCurrent(domain), string.IsNullOrWhiteSpace(type) ? null : type.Trim().ToUpperInvariant(), includeInactive, ct); + + public Task> CargoTypesAsync(string? domain, CancellationToken ct) => + repository.GetCargoTypesAsync(DomainOrCurrent(domain), ct); + + public Task> CompaniesAsync(bool includeInactive, CancellationToken ct) => + repository.GetCompaniesAsync(includeInactive, ct); + + public Task> NationalitiesAsync(CancellationToken ct) => repository.GetNationalitiesAsync(ct); + + public Task> CitiesAsync(CancellationToken ct) => repository.GetCitiesAsync(ct); +} diff --git a/src/NTP.Application/NTP.Application.csproj b/src/NTP.Application/NTP.Application.csproj new file mode 100644 index 0000000..b600a6d --- /dev/null +++ b/src/NTP.Application/NTP.Application.csproj @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/src/NTP.Application/Shipments/ShipmentContracts.cs b/src/NTP.Application/Shipments/ShipmentContracts.cs new file mode 100644 index 0000000..1b68dbb --- /dev/null +++ b/src/NTP.Application/Shipments/ShipmentContracts.cs @@ -0,0 +1,38 @@ +using NTP.Domain.Entities; + +namespace NTP.Application.Shipments; + +public sealed record ShipmentQuery(string? ShipmentNo = null, string? Status = null, bool? IsActive = null); + +public sealed record ShipmentDto( + long ShipmentId, + string ShipmentNo, + string? OriginCode, + string? DestinationCode, + decimal? WeightKg, + string Status, + bool IsActive, + DateTime CreatedAt, + DateTime? UpdatedAt, + int RowVersion) +{ + public static ShipmentDto From(Shipment s) => new( + s.ShipmentId, s.ShipmentNo, s.OriginCode, s.DestinationCode, s.WeightKg, + s.Status, s.IsActive, s.CreatedAt, s.UpdatedAt, s.RowVersion); +} + +public sealed record CreateShipmentRequest( + string ShipmentNo, + string? OriginCode, + string? DestinationCode, + decimal? WeightKg, + string Status = "NEW"); + +public sealed record UpdateShipmentRequest( + string ShipmentNo, + string? OriginCode, + string? DestinationCode, + decimal? WeightKg, + string Status, + bool IsActive, + int RowVersion); diff --git a/src/NTP.Application/Shipments/ShipmentService.cs b/src/NTP.Application/Shipments/ShipmentService.cs new file mode 100644 index 0000000..ad4d768 --- /dev/null +++ b/src/NTP.Application/Shipments/ShipmentService.cs @@ -0,0 +1,105 @@ +using FluentValidation; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Domain.Entities; + +namespace NTP.Application.Shipments; + +public interface IShipmentService +{ + Task GetAsync(long id, CancellationToken ct); + Task> SearchAsync(ShipmentQuery query, PageRequest page, CancellationToken ct); + Task CreateAsync(CreateShipmentRequest request, CancellationToken ct); + Task UpdateAsync(long id, UpdateShipmentRequest request, CancellationToken ct); + Task DeleteAsync(long id, int rowVersion, CancellationToken ct); +} + +/// +/// Business logic lives here (ported from the current backend), not in SQL and not in controllers. +/// +public sealed class ShipmentService( + IShipmentRepository repository, + IUnitOfWork unitOfWork, + IValidator createValidator, + IValidator updateValidator) : IShipmentService +{ + private const string Entity = nameof(Shipment); + + public async Task GetAsync(long id, CancellationToken ct) + { + var shipment = await repository.GetByIdAsync(id, ct) ?? throw new NotFoundException(Entity, id); + return ShipmentDto.From(shipment); + } + + public async Task> SearchAsync(ShipmentQuery query, PageRequest page, CancellationToken ct) + { + var result = await repository.SearchAsync(query, page, ct); + return new PagedResult( + result.Items.Select(ShipmentDto.From).ToList(), result.Page, result.PageSize, result.TotalCount); + } + + public async Task CreateAsync(CreateShipmentRequest request, CancellationToken ct) + { + await createValidator.ValidateAndThrowAsync(request, ct); + + return await unitOfWork.ExecuteInTransactionAsync(async token => + { + if (await repository.ExistsByNumberAsync(request.ShipmentNo, null, token)) + throw new ValidationException($"Shipment number '{request.ShipmentNo}' already exists."); + + var shipment = new Shipment + { + ShipmentNo = request.ShipmentNo.Trim(), + OriginCode = request.OriginCode, + DestinationCode = request.DestinationCode, + WeightKg = request.WeightKg, + Status = request.Status, + IsActive = true + }; + + var id = await repository.InsertAsync(shipment, token); + var created = await repository.GetByIdAsync(id, token) ?? throw new NotFoundException(Entity, id); + return ShipmentDto.From(created); + }, ct); + } + + public async Task UpdateAsync(long id, UpdateShipmentRequest request, CancellationToken ct) + { + await updateValidator.ValidateAndThrowAsync(request, ct); + + return await unitOfWork.ExecuteInTransactionAsync(async token => + { + var existing = await repository.GetByIdAsync(id, token) ?? throw new NotFoundException(Entity, id); + + if (await repository.ExistsByNumberAsync(request.ShipmentNo, id, token)) + throw new ValidationException($"Shipment number '{request.ShipmentNo}' already exists."); + + existing.ShipmentNo = request.ShipmentNo.Trim(); + existing.OriginCode = request.OriginCode; + existing.DestinationCode = request.DestinationCode; + existing.WeightKg = request.WeightKg; + existing.Status = request.Status; + existing.IsActive = request.IsActive; + existing.RowVersion = request.RowVersion; // client's version is what we check against + + if (await repository.UpdateAsync(existing, token) == 0) + throw new ConcurrencyException(Entity, id); + + var updated = await repository.GetByIdAsync(id, token) ?? throw new NotFoundException(Entity, id); + return ShipmentDto.From(updated); + }, ct); + } + + public async Task DeleteAsync(long id, int rowVersion, CancellationToken ct) + { + await unitOfWork.ExecuteInTransactionAsync(async token => + { + _ = await repository.GetByIdAsync(id, token) ?? throw new NotFoundException(Entity, id); + + if (await repository.DeleteAsync(id, rowVersion, token) == 0) + throw new ConcurrencyException(Entity, id); + + return true; + }, ct); + } +} diff --git a/src/NTP.Application/Shipments/ShipmentValidators.cs b/src/NTP.Application/Shipments/ShipmentValidators.cs new file mode 100644 index 0000000..4056513 --- /dev/null +++ b/src/NTP.Application/Shipments/ShipmentValidators.cs @@ -0,0 +1,39 @@ +using FluentValidation; + +namespace NTP.Application.Shipments; + +internal static class ShipmentRules +{ + // Keep in sync with the Oracle column sizes (VARCHAR2 lengths are in BYTES by default on 11g, + // so Arabic text can hit the limit sooner than the character count suggests). + public const int ShipmentNoMax = 30; + public const int LocationCodeMax = 10; + public static readonly string[] Statuses = ["NEW", "IN_TRANSIT", "DELIVERED", "CANCELLED"]; +} + +public sealed class CreateShipmentValidator : AbstractValidator +{ + public CreateShipmentValidator() + { + RuleFor(x => x.ShipmentNo).NotEmpty().MaximumLength(ShipmentRules.ShipmentNoMax); + RuleFor(x => x.OriginCode).MaximumLength(ShipmentRules.LocationCodeMax); + RuleFor(x => x.DestinationCode).MaximumLength(ShipmentRules.LocationCodeMax); + RuleFor(x => x.WeightKg).GreaterThan(0).When(x => x.WeightKg.HasValue); + RuleFor(x => x.Status).Must(s => ShipmentRules.Statuses.Contains(s)) + .WithMessage($"Status must be one of: {string.Join(", ", ShipmentRules.Statuses)}"); + } +} + +public sealed class UpdateShipmentValidator : AbstractValidator +{ + public UpdateShipmentValidator() + { + RuleFor(x => x.ShipmentNo).NotEmpty().MaximumLength(ShipmentRules.ShipmentNoMax); + RuleFor(x => x.OriginCode).MaximumLength(ShipmentRules.LocationCodeMax); + RuleFor(x => x.DestinationCode).MaximumLength(ShipmentRules.LocationCodeMax); + RuleFor(x => x.WeightKg).GreaterThan(0).When(x => x.WeightKg.HasValue); + RuleFor(x => x.Status).Must(s => ShipmentRules.Statuses.Contains(s)) + .WithMessage($"Status must be one of: {string.Join(", ", ShipmentRules.Statuses)}"); + RuleFor(x => x.RowVersion).GreaterThanOrEqualTo(0); + } +} diff --git a/src/NTP.Domain/Entities/Shipment.cs b/src/NTP.Domain/Entities/Shipment.cs new file mode 100644 index 0000000..96f9990 --- /dev/null +++ b/src/NTP.Domain/Entities/Shipment.cs @@ -0,0 +1,29 @@ +namespace NTP.Domain.Entities; + +/// +/// SAMPLE entity mapped to an existing Oracle 11g table (NAFITH.SHIPMENTS). +/// Replace / duplicate this for each real table you migrate. +/// +/// Mapping rules (configured in Infrastructure/DependencyInjection.cs): +/// - Oracle column SHIPMENT_NO maps to property ShipmentNo automatically +/// (Dapper MatchNamesWithUnderscores = true). +/// - NUMBER(p,0) columns map to int/long; NUMBER(p,s) to decimal. +/// - NUMBER(1) "boolean" flags: reading 0/1 into bool works out of the box; +/// when WRITING, pass 1/0 explicitly (ODP.NET 21.x has no Boolean bind type). +/// - DATE columns map to DateTime. +/// +public sealed class Shipment +{ + public long ShipmentId { get; set; } + public string ShipmentNo { get; set; } = string.Empty; + public string? OriginCode { get; set; } + public string? DestinationCode { get; set; } + public decimal? WeightKg { get; set; } + public string Status { get; set; } = "NEW"; + public bool IsActive { get; set; } = true; + public DateTime CreatedAt { get; set; } + public DateTime? UpdatedAt { get; set; } + + /// Optimistic concurrency counter (ROW_VERSION NUMBER(10)). + public int RowVersion { get; set; } +} diff --git a/src/NTP.Domain/Grains/Orders/OrdersDomain.cs b/src/NTP.Domain/Grains/Orders/OrdersDomain.cs new file mode 100644 index 0000000..8a1bd64 --- /dev/null +++ b/src/NTP.Domain/Grains/Orders/OrdersDomain.cs @@ -0,0 +1,62 @@ +namespace NTP.Domain.Grains.Orders; + +/// GRAINSTENDERORDER.STATUSCODE values used by legacy tenderOrder.cfc. +public static class TenderOrderStatus +{ + public const string Active = "ACTIVE"; + public const string Deleted = "DELETED"; +} + +/// GRAINSTENDERORDER.TYPE: who the order is for (legacy form option values). +public static class TenderOrderType +{ + public const string Company = "COMP"; + public const string Individuals = "AHALE"; +} + +/// GRAINSTENDERORDER.CT: cargo class derived at creation time. +public static class TenderCargoClass +{ + public const string Packed = "PCKD"; + public const string Bulk = "BULK"; + public const string BulkTipper = "BULK_GALLAB"; +} + +/// Hard-coded ids and codes found in the legacy Grains orders/billing code. +public static class GrainsOrderConstants +{ + /// CARGOTYPE.ID 41 = packed cargo (type/tipper options are disabled for it). + public const long PackedCargoTypeId = 41; + + /// LOCATIONS.ID of destinations that always receive tipper (gallab) trucks. + public static readonly IReadOnlySet TipperDestinationIds = new HashSet { 350, 440, 465 }; + + public const int MinTrucksPerOrder = 1; + public const int MaxTrucksPerOrder = 200; + + /// Order date may be chosen from today up to today + 4 days (legacy dropdown). + public const int MaxDaysAhead = 4; + + /// SCAC 327 = the pseudo company that represents individuals (AHALE). + public const long IndividualsScac = 327; + + /// Billing origin id written to GRAINS_BILLING.ORIGIN (legacy comment: Aqaba silos). + public const long BillingOriginId = 205; + + /// Fine rows in GRAINS_FINE are looked up for this cargo type only (legacy hard-code). + public const long FineCargoTypeId = 38; + + /// Tender number printed on the financial billing report (hard-coded in legacy FinancialBilling.cfm). + public const string BillingTenderNumber = "28/2020/50"; +} + +/// New GRAINSTENDERORDER row. +public sealed record NewTenderOrder( + long CargoType, long Location, long Destination, DateTime OrderDate, int MobileShift, + int Quantity, string? Type, string Ct, string CreatedBy); + +/// New GRAINS_BILLING row (columns exactly as written by legacy addBillingInfo). +public sealed record NewGrainsBilling( + long Pn, string SerialNo, string Tn, long CargoType, long Destination, DateTime LoadDate, DateTime DischargeDate, + decimal Dtw, decimal Dgw, decimal Dnw, decimal Ltw, decimal Lgw, decimal Lnw, long Scac, long InvoiceNumber, + long Origin, decimal Price, decimal FinePrice, decimal FinalCost, decimal LoseFine); diff --git a/src/NTP.Domain/Grains/Permits/PermitConstants.cs b/src/NTP.Domain/Grains/Permits/PermitConstants.cs new file mode 100644 index 0000000..ddf6004 --- /dev/null +++ b/src/NTP.Domain/Grains/Permits/PermitConstants.cs @@ -0,0 +1,74 @@ +namespace NTP.Domain.Grains.Permits; + +/// PERMITS.SHIPMENTSTATUSCODE values used by the Grains (GN) domain (legacy grains.cfc). +public static class PermitStatus +{ + public const string Queued = "QUED"; + public const string Open = "OPEN"; + public const string Requested = "REQST"; + public const string Planned = "PLND"; + public const string Accepted = "ACCPT"; + public const string Released = "RESD"; + public const string ArrivedControl = "ACTRL"; + public const string ClearedPreliminary = "CLRPR"; + public const string Closed = "CLOSE"; + public const string Revoked = "RVKD"; + public const string Rejected = "RJCTD"; + + /// Statuses for which a truck/trailer/driver may not appear on another permit (submitOrder/updateOrder). + public static readonly string[] ActiveForDuplicateCheck = [Requested, Planned, Accepted, Released, ArrivedControl]; + + /// Statuses listed by getGNPermits (grid). + public static readonly string[] GridStatuses = + [Requested, Planned, Open, Accepted, Released, ArrivedControl, Closed, Revoked, ClearedPreliminary]; +} + +/// EVENTS.EVENTTYPE codes written/read by the Grains permits slice. +public static class PermitEventType +{ + public const string AssignDest = "ASSIGNDEST"; + public const string ManualAssignDest = "MANASGNDST"; + public const string LoadingTare = "LTW"; + public const string LoadingGross = "LGW"; + public const string LoadingNet = "LNW"; + public const string DischargeTare = "DTW"; + public const string DischargeGross = "DGW"; + public const string DischargeNet = "DNW"; + public const string AssignGrainsDest = "ASSGIN_GRAINS_DEST"; + public const string Override = "OVRD"; + public const string PhoneAccept = "PHACCPT"; + public const string PhoneReject = "PHRJCT"; + public const string SaveOperationType = "SAVE_OPERATION_TYPE"; + public const string AddWeights = "ADD_WEIGHTS"; + public const string ConvertToResd = "CONVERT_TO_RESD"; + public const string NoAnswer = "NO_ANSWER"; + public const string Print = "GNPRNT"; + public const string Modify = "MODIFY"; + public const string Cancel = "Cancel"; + public const string Revoked = "RVKD"; + public const string Create = "CREATE"; +} + +/// Grains cargo / order types (GRAINSTENDERORDER.CT and PERMITS.TT). +public static class GrainsCargo +{ + public const string Bulk = "BULK"; + public const string BulkGallab = "BULK_GALLAB"; + public const string Packed = "PCKD"; + + public const long WheatBulk = 38; + public const long BarleyBulk = 39; + public const long PackedA = 40; + public const long PackedBarley = 41; +} + +public static class GrainsLocations +{ + public const long Silos = 205; + public const long Direct = 210; + public const long RiceWarehouses = 145; + public const long MainPortGeneral = 105; + public const long AqabaWarehouses = 101; + public const long AqabaSouthSilos = 420; + public const long SouthPortDirect = 110; +} diff --git a/src/NTP.Domain/Grains/Permits/PermitRules.cs b/src/NTP.Domain/Grains/Permits/PermitRules.cs new file mode 100644 index 0000000..4b9ec35 --- /dev/null +++ b/src/NTP.Domain/Grains/Permits/PermitRules.cs @@ -0,0 +1,334 @@ +using System.Globalization; + +namespace NTP.Domain.Grains.Permits; + +/// generatePermitNumber (grains.cfc): permit number layout per company type and cargo type. +public static class PermitNumberGenerator +{ + /// BULK or PCKD (anything else yields an empty number, as in legacy). + /// next value of SEQ_GRAINS_TRACKINGNO_OWN (owners) or SEQ_GRAINS_TRACKINGNO_CO (companies). + /// SCAC of the company the permit belongs to. + /// SCAC of the owners (individuals) pseudo company (legacy application.GN_BadiyaSCAC). + /// max(NTP_TENDER.ID) for domain GN. + public static string Generate(string cargoType, long sequence, long companyCode, long badiyaScac, long tenderCount) + { + var isOwner = companyCode == badiyaScac; + var t2 = Pad(tenderCount, 2); + if (string.Equals(cargoType, GrainsCargo.Bulk, StringComparison.OrdinalIgnoreCase)) + return isOwner ? "30" + t2 + Pad(sequence, 6) : "1" + t2 + Pad(sequence, 6); + if (string.Equals(cargoType, GrainsCargo.Packed, StringComparison.OrdinalIgnoreCase)) + { + var packedTender = 41 + tenderCount; + return isOwner + ? "3" + packedTender.ToString(CultureInfo.InvariantCulture) + Pad(sequence, 7) + : "1" + packedTender.ToString(CultureInfo.InvariantCulture) + Pad(sequence, 6); + } + return string.Empty; + } + + private static string Pad(long v, int width) => v.ToString(CultureInfo.InvariantCulture).PadLeft(width, '0'); +} + +/// What a weighbridge reading does to a permit. +public enum WeighbridgeAction { None, LoadingTare, LoadingGross, DischargeGross, DischargeTare } + +public sealed record WeighbridgeDecision( + bool Allowed, + string ErrorCode, + string? Message, + WeighbridgeAction Action = WeighbridgeAction.None, + string? EventType = null, + string? CurrentStatus = null, + string? NewPermitStatus = null, + string? PrintAction = null) +{ + public const string WrongStatus = "حالة السيارة غير صحيحة"; + public const string LocationNotOnRoute = "الموقع غير موجود على مسار الشاحنة"; + public const string Success = "تمت العملية بنجاح"; +} + +/// Weighbridge transaction state machine (ws.cfc addWeightBridgeEvent). +public static class WeighbridgeRules +{ + public const string Entry = "EN"; + public const string Exit = "EX"; + + /// + /// Origin location + EN = loading tare (LTW); origin + EX = loading gross (LGW, status ACTRL); + /// destination + EN = discharge gross (DGW, status CLRPR); destination + EX = discharge tare (DTW, CLOSE). + /// + public static WeighbridgeDecision Decide(string status, long? originId, long? destinationId, long locationId, string trxType) + { + string? locType = null; + if (originId == locationId) locType = "ORG"; + else if (destinationId == locationId) locType = "DEST"; + if (locType is null) + return new(false, "2", WeighbridgeDecision.LocationNotOnRoute); + + bool In(params string[] s) => s.Contains(status); + var wrong = new WeighbridgeDecision(false, "1", WeighbridgeDecision.WrongStatus); + + switch (locType, trxType) + { + case ("ORG", Entry): + return In(PermitStatus.Accepted, PermitStatus.Released) + ? new(true, "0", WeighbridgeDecision.Success, WeighbridgeAction.LoadingTare, PermitEventType.LoadingTare, status) + : wrong; + case ("ORG", Exit): + return In(PermitStatus.Accepted, PermitStatus.Released, PermitStatus.ArrivedControl) + ? new(true, "0", WeighbridgeDecision.Success, WeighbridgeAction.LoadingGross, PermitEventType.LoadingGross, + PermitStatus.ArrivedControl, PermitStatus.ArrivedControl, "printPage1") + : wrong; + case ("DEST", Entry): + return In(PermitStatus.Accepted, PermitStatus.Released, PermitStatus.ArrivedControl, PermitStatus.ClearedPreliminary) + ? new(true, "0", WeighbridgeDecision.Success, WeighbridgeAction.DischargeGross, PermitEventType.DischargeGross, + PermitStatus.ClearedPreliminary, PermitStatus.ClearedPreliminary) + : wrong; + case ("DEST", Exit): + return status == PermitStatus.ClearedPreliminary + ? new(true, "0", WeighbridgeDecision.Success, WeighbridgeAction.DischargeTare, PermitEventType.DischargeTare, + PermitStatus.Closed, PermitStatus.Closed, "printPage2") + : wrong; + default: + return new(false, "4", null); + } + } + + /// WeightBridge.cfm: first (tare) 10000..25000, second (gross) 35000..75000 and gross greater than tare. + public static string? ValidateManualWeights(long weightIn, long weightOut) + { + if (!(weightIn is >= 10000 and <= 25000 && weightOut is >= 35000 and <= 75000)) + return "الوزن الاول يجب ان يكون بين 10000 و 25000 والوزن الثاني يجب ان يكون بين 35000 و 75000"; + if (weightOut <= weightIn) + return "الوزن الاول يحب أن يكون أصغر من الوزن الثاني"; + return null; + } + + /// loadingWeightBridge/dischargeWeightBridge.cfm: gross must be greater than tare. + public static string? ValidateGrossTare(long gross, long tare) => + gross > tare ? null : "الوزن القائم يجب ان يكون اكبر من الفارغ"; + + /// saveGrainsWeights: every weight needs at least 5 digits. + public static string? ValidateStoredWeights(string? empty, string? gross) => + (empty?.Trim().Length ?? 0) < 5 || (gross?.Trim().Length ?? 0) < 5 ? "يجب ان يكون الوزن من 5 خانات" : null; +} + +/// printIn.cfm weight arithmetic (kilograms split into ton + kilo, signed difference). +public sealed record WeightBreakdown( + long LoadingNet, long DischargeNet, + long LoadingTon, long LoadingKilo, long DischargeTon, long DischargeKilo, + long TonDifference, long KiloDifference, string Sign) +{ + public static WeightBreakdown Compute(decimal loadingTare, decimal loadingGross, decimal dischargeTare, decimal dischargeGross) + { + var lnw = (long)(loadingGross - loadingTare); + var dnw = (long)(dischargeGross - dischargeTare); + var dTon = dnw / 1000; + var lTon = lnw / 1000; + var dKilo = dnw - dTon * 1000; + var lKilo = lnw - lTon * 1000; + var sign = Math.Sign(dnw - lnw) switch { -1 => "(-)", 1 => "(+)", _ => " " }; + return new(lnw, dnw, lTon, lKilo, dTon, dKilo, dTon - lTon, dKilo - lKilo, sign); + } + + public static (long Ton, long Kilo) Split(decimal weight) + { + var w = (long)weight; + var ton = w / 1000; + return (ton, w - ton * 1000); + } +} + +/// distributePackedBulk: maps the requested category to queue code / type / permit cargo type. +public sealed record DistributionCategory(string Request, string DistributionCode, string QueueType, string PermitCargoType) +{ + public bool IsPacked => DistributionCode == GrainsCargo.Packed; + public bool IsGallabCompany => Request == "BULK_GALLAB_COMP"; + + public static readonly string[] Allowed = + ["PCKD", "BULK_AHALE", "BULK_COMP", "BULK_GALLAB_COMP", "BULK_GALLAB_AHALE"]; + + public static DistributionCategory? Parse(string? request) + { + var r = request?.Trim() ?? string.Empty; + return r switch + { + "BULK_AHALE" => new(r, "BULK", "AHALE", "BULK"), + "BULK_COMP" => new(r, "BULK", "COMP", "BULK"), + "PCKD" => new(r, "PCKD", "", "PCKD"), + "BULK_GALLAB_COMP" => new(r, "BULK_GALLAB", "COMP", "BULK"), + "BULK_GALLAB_AHALE" => new(r, "BULK_GALLAB", "AHALE", "BULK"), + _ => null + }; + } + + /// GRAINS_COMPANIES_QUEUE code/type filter used to compute each company's share (queue spelling is AHALI). + public (string Code, string? Type) QueueFilter => Request switch + { + "BULK_AHALE" => ("BULK", "AHALI"), + "BULK_COMP" => ("BULK", "COMP"), + "PCKD" => ("PCKD", null), + "BULK_GALLAB_AHALE" => ("BULK", "AHALI"), + "BULK_GALLAB_COMP" => ("GALLAB", "COMP"), + _ => (DistributionCode, null) + }; + + public string NoOrdersMessage => Request switch + { + "PCKD" => "لا توجد طلبات مشول مسجلة على النظام ، او قد تم توزيع كامل الطلبية", + "BULK_AHALE" => "لا توجد طلبات سائب أفراد مسجلة على النظام ، او قد تم توزيع كامل الطلبية", + "BULK_COMP" => "لا توجد طلبات سائب شركات مسجلة على النظام ، او قد تم توزيع كامل الطلبية", + "BULK_GALLAB_COMP" => "لا توجد طلبات قلاب شركات مسجلة على النظام ، او قد تم توزيع كامل الطلبية", + "BULK_GALLAB_AHALE" => "لا توجد طلبات قلاب أفراد مسجلة على النظام ، او قد تم توزيع كامل الطلبية", + _ => string.Empty + }; +} + +/// Arabic captions used by getOrderDetails / events grids. +public static class OrderLabels +{ + public static string CargoGroup(long? cargoType, string fallback) => cargoType switch + { + GrainsCargo.WheatBulk or GrainsCargo.BarleyBulk => "سائب", + GrainsCargo.PackedA or GrainsCargo.PackedBarley => "مشول", + _ => fallback + }; + + public static string Location(long? id, string fallback) => id switch + { + GrainsLocations.Silos => "صوامع", + GrainsLocations.Direct => "مباشر", + GrainsLocations.RiceWarehouses => "مستودعات الرز", + GrainsLocations.MainPortGeneral => "الميناء الرئيسي/البضائع العامة", + GrainsLocations.AqabaWarehouses => "مستودعات العقبة", + GrainsLocations.AqabaSouthSilos => "صوامع العقبة الجنوبية", + GrainsLocations.SouthPortDirect => "الميناء الجنوبي/مباشر", + _ => fallback + }; + + public static string OrderType(string? ct) => ct switch + { + "PCKD" => "مشول", + "BULK_GALLAB" => "سائب قلاب", + "BULK" => "سائب", + _ => ct ?? string.Empty + }; + + /// Shift label as in getOrderDetails (1 morning, 2 evening). + public static string MobileShift(long? shift) => + shift switch { 1 => "الشفت الصباحي", 2 => "الشفت المسائي", 3 => "الشفت الليلي", _ => string.Empty }; + + /// Short shift label as in getPermitInfo / acceptPrint. + public static string ShiftShort(long? shift) => + shift switch { 1 => "صباحي", 2 => "مسائي", 3 => "ليلي", _ => string.Empty }; + + public static string OperationType(string? inbondTypeCode) => + inbondTypeCode switch { "EXPT" => "فارغ", "IMPT" => "محمل", _ => string.Empty }; +} + +/// getAllEvents: legacy Arabic event captions (EVENTS.EVENTTYPE + current status). +public static class PermitEventCaptions +{ + public static string Caption(string? eventType, string? currentStatus) + { + switch (eventType) + { + case PermitEventType.AssignDest: return "تحديد وجهة"; + case PermitEventType.ManualAssignDest: return "تحديد وجهة يدوي"; + case PermitEventType.LoadingTare: return "قبان تحميل وزنة أولى"; + case PermitEventType.LoadingGross: return "قبان تحميل وزنة ثانية"; + case PermitEventType.DischargeGross: return "قبان تفريغ وزنة أولى"; + case PermitEventType.DischargeTare: return "قبان تفريغ وزنة ثانية"; + case PermitEventType.AssignGrainsDest: return "تحديد وجهة ارسالية تموين"; + case PermitEventType.PhoneAccept: return "تأكيد الطلبية هاتفيا"; + case PermitEventType.PhoneReject: return "الغاء الطلبية هاتفيا"; + case PermitEventType.SaveOperationType: return "تحديد نوع العملية"; + case PermitEventType.AddWeights: return "تثبيت أوزان التحميل"; + case PermitEventType.ConvertToResd: return "تحويل الى تم التسريب"; + case PermitEventType.NoAnswer: return "لم يتم الرد"; + case PermitEventType.Override: + return currentStatus switch + { + PermitStatus.Open => "تسجيل دور", + PermitStatus.Requested => "توزيع طلبية", + PermitStatus.Planned => "تثبيت دور", + PermitStatus.Accepted => "كشف حسي", + PermitStatus.Released => "تقديم ارسالية", + _ => eventType + }; + default: return eventType ?? string.Empty; + } + } +} + +/// addPhoneRejectEvent rules. +public static class PhoneRejectRules +{ + public static readonly string[] AbsenceReasons = + ["عدم الحضور بعد التسريب", "عدم الحضور بعد التوزيع", "تجاوز عدد الإستنكافات المسموح بها"]; + + public static readonly string[] AllowedReasons = + [ + "لايمكن الاتصال به", "رقم الهاتف غير صحيح", "الهاتف مغلق", "قائمة الانتظار", "لايرد", "غير موافق", + .. AbsenceReasons + ]; + + public static readonly int[] AllowedExpiryDays = [1, 2, 3, 4, 5, 14, 30]; + + public static bool IsAbsence(string? reason) => AbsenceReasons.Contains(reason?.Trim() ?? string.Empty); + + /// BL_addToBlacklist expiry: date part of (now - (24 + shiftStart) h) + days + shiftEnd h. + public static DateTime BlacklistExpiry(DateTime now, int shiftStartHour, int shiftEndHour, int days) => + now.AddHours(-(24 + shiftStartHour)).Date.AddDays(days).AddHours(shiftEndHour); + + /// autoDailerResponse: maps the dialer's word suffix to a postponement of N days. + public static int PostponeDaysFromDialerKey(string? three) => (three ?? string.Empty).ToLowerInvariant() switch + { + "one" => 1, "two" => 2, "thr" => 3, "fou" => 4, "fiv" => 5, _ => 0 + }; +} + +/// assignDestination location filtering by truck type (packed trucks lose the bulk silo/berth set). +public static class DestinationRules +{ + public static readonly long[] BulkLocations = [215, 220, 225, 350]; + public static readonly string[] PackedTruckAsrns = ["201401693756", "201401693891"]; + + public static IReadOnlyList FilterCompanyLocations(IEnumerable locations, string? lastAsrn) + { + var packed = lastAsrn is not null && PackedTruckAsrns.Contains(lastAsrn); + return packed + ? locations.Where(l => !BulkLocations.Contains(l)).ToList() + : locations.Where(l => BulkLocations.Contains(l)).ToList(); + } + + /// Cargo types that may be assigned when a permit already holds an order (38/39 and 40/41 are interchangeable). + public static long[]? CargoGroup(long? cargoType) => cargoType switch + { + 38 or 39 => [38, 39], + 40 or 41 => [40, 41], + _ => null + }; +} + +public static class OperationWindow +{ + /// "sysdate between orderdate + first/24 and orderdate + last/24" for a shift given as [first,last] hours. + public static bool IsWithin(DateTime now, DateTime orderDate, int firstHour, int lastHour) => + now >= orderDate.Date.AddHours(firstHour) && now <= orderDate.Date.AddHours(lastHour); +} + +/// submitOrder/updateOrder: which plate/driver combination is acceptable for an order (pure part). +public static class PermitAssignmentRules +{ + public const string TruckNotInFleet = "هذه القاطرة ليست ضمن قاطرات الشركة"; + public const string TrailerNotInFleet = "هذه المقطورة ليست ضمن مقطورات الشركة"; + public const string TruckOnForeignPermit = "لا يمكن تثبيت القاطرة على ارسالية غير تابعه للشركة"; + public const string TrailerOnForeignPermit = "لا يمكن تثبيت المقطورة على ارسالية غير تابعه للشركة"; + public const string DriverNotRegistered = "السائق يجب ان يكون مسجل في شاشة السائقين"; + public const string GallabNeedsTripper = "يجب ان تكون النمط قلاب كون الطلبية قلاب"; + public const string BadStatus = "حالة الارسالية غير صحيحة"; + + /// A gallab order (CT ends with GALLAB) needs a head of type Tripper. + public static bool IsGallabOrder(string? ct) => ct is { Length: >= 6 } && ct[^6..] == "GALLAB"; +} diff --git a/src/NTP.Domain/Grains/Registry/RegistryDomain.cs b/src/NTP.Domain/Grains/Registry/RegistryDomain.cs new file mode 100644 index 0000000..e2ad49d --- /dev/null +++ b/src/NTP.Domain/Grains/Registry/RegistryDomain.cs @@ -0,0 +1,150 @@ +namespace NTP.Domain.Grains.Registry; + +/// Status codes of NTP_TRUCKS / NTP_TRAILERS / NTP_DRIVERS (STATUS table, domain GN). +public static class RegistryStatus +{ + public const string Open = "OPEN"; + public const string RegReqst = "REGREQST"; + public const string Accpt = "ACCPT"; + public const string Rvkd = "RVKD"; + public const string Incomp = "INCOMP"; +} + +/// GRAINSBLACKLIST statuses and categories (legacy grains.cfc BL_* functions, jobs\changeBlacklistStatus.cfm). +public static class BlacklistValues +{ + public const string Open = "OPEN"; + public const string Deleted = "DELETED"; + public const string Expired = "EXPIRED"; + + public const string CategoryPhoneDecline = "PHONEDECLINE"; + public const string CategoryWaitingList = "WAITINGLIST"; + + public const string EntityPermit = "PERMIT"; + public const string EntityDriver = "DRIVERNUMBER"; + public const string EntityTruck = "TRUCKNUMBER"; + public const string EntityTrailer = "TRAILERNUMBER"; +} + +public static class RegistryConstants +{ + /// Legacy application.GN_BadiyaSCAC (hard-coded 327 all over the legacy Grains code). + public const long DefaultBadiyaScac = 327; + /// Stakeholder id of transport companies (legacy session.stkid eq 62). + public const long CompanyStakeholderId = 62; + public const string Domain = "GN"; +} + +/// Attachment types stored in GRAINS_FILES.ATTACHMENTTYPE and the legacy upload folders. +public static class RegistryAttachmentTypes +{ + public const string TruckLicense = "TRUCKLICENSE"; + public const string TrailerLicense = "TRAILERLICENSE"; + public const string DriverLicense = "DRIVERLICENSE"; + + public const string TruckFolder = "ntp_trucks_files"; + public const string TrailerFolder = "ntp_trailers_files"; + public const string DriverFolder = "ntp_drivers_files"; +} + +/// Legacy ACTIONS ids checked with application.objAuth.isActAuthorized in the Grains registry pages. +public static class RegistryActions +{ + public const int AddTruck = 81; + public const int AddTrailer = 82; + public const int AddDriver = 83; + public const int RevokeTruck = 66; + public const int RevokeTrailer = 67; + public const int RevokeDriver = 68; + public const int AcceptTruck = 69; + public const int AcceptTrailer = 70; + public const int AcceptDriver = 71; + public const int EditTruckTrailer = 108; + /// Choose / see the destinations of a truck (company 327). + public const int Destinations = 107; +} + +/// NTP_TRUCKS row (columns the legacy code reads/writes). +public sealed class NtpTruck +{ + public long Id { get; set; } + public string Tn { get; set; } = string.Empty; + public string? ChasesNumber { get; set; } + public DateTime? RegDate { get; set; } + public long? Axials { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? OwnerName { get; set; } + public string? OwnerNnpn { get; set; } + public string? Color { get; set; } + public string? Model { get; set; } + public string? ManifactureYear { get; set; } + public string? PhoneNumber { get; set; } + public string? HeadType { get; set; } + public long? Tcscac { get; set; } + public string? CreateUserId { get; set; } + public DateTime? CreateTimestamp { get; set; } + public string? LastUpdateUserId { get; set; } + public DateTime? LastUpdateTimestamp { get; set; } +} + +/// NTP_TRAILERS row. +public sealed class NtpTrailer +{ + public long Id { get; set; } + public string Tn { get; set; } = string.Empty; + public string? ChasesNumber { get; set; } + public DateTime? RegDate { get; set; } + public long? Axials { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? OwnerName { get; set; } + public string? OwnerNnpn { get; set; } + public string? PhoneNumber { get; set; } + public long? TnId { get; set; } + public long? Tcscac { get; set; } + public string? CreateUserId { get; set; } + public DateTime? CreateTimestamp { get; set; } + public string? LastUpdateUserId { get; set; } + public DateTime? LastUpdateTimestamp { get; set; } +} + +/// NTP_DRIVERS row. +public sealed class NtpDriver +{ + public long Id { get; set; } + public string Nnpn { get; set; } = string.Empty; + public string? Name { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } + public string? Nat { get; set; } + public string? Cat { get; set; } + public string? Mobile1 { get; set; } + public string? Mobile2 { get; set; } + public string StatusCode { get; set; } = string.Empty; + public long? Tcscac { get; set; } + public string? CreateUserId { get; set; } + public DateTime? CreateTimestamp { get; set; } +} + +/// GRAINSBLACKLIST row. +public sealed class GrainsBlacklistEntry +{ + public long Id { get; set; } + public string? Category { get; set; } + public string? EntityType { get; set; } + public string? EntityId { get; set; } + public string? CreatedBy { get; set; } + public DateTime? ExpiryDate { get; set; } + public string StatusCode { get; set; } = string.Empty; + public string? Remarks { get; set; } + public string? LastUpdateUser { get; set; } + public DateTime? LastUpdateDate { get; set; } +} + +/// GRAINS_FILES row. +public sealed class GrainsFile +{ + public long EntityId { get; set; } + public string AttachmentType { get; set; } = string.Empty; + public string OriginalName { get; set; } = string.Empty; + public string FileName { get; set; } = string.Empty; +} diff --git a/src/NTP.Domain/Grains/Reports/GrainsCodes.cs b/src/NTP.Domain/Grains/Reports/GrainsCodes.cs new file mode 100644 index 0000000..956c3b1 --- /dev/null +++ b/src/NTP.Domain/Grains/Reports/GrainsCodes.cs @@ -0,0 +1,30 @@ +namespace NTP.Domain.Grains.Reports; + +/// Legacy GN (grains) permit statuses and EVENTS types touched by the reports / WS / file import slice. +public static class GrainsPermitStatus +{ + public const string Queued = "QUED"; + public const string Open = "OPEN"; + public const string Requested = "REQST"; + public const string Planned = "PLND"; + public const string Accepted = "ACCPT"; + public const string Released = "RESD"; + public const string ActiveControl = "ACTRL"; + public const string ClearedPermit = "CLRPR"; + public const string Closed = "CLOSE"; + public const string Revoked = "RVKD"; +} + +public static class GrainsEventType +{ + public const string LoadTare = "LTW"; + public const string LoadGross = "LGW"; + public const string LoadNet = "LNW"; + public const string DischargeTare = "DTW"; + public const string DischargeGross = "DGW"; + public const string DischargeNet = "DNW"; + public const string AssignDestination = "ASSIGNDEST"; + public const string PhoneAccept = "PHACCPT"; + public const string PhoneReject = "PHRJCT"; + public const string Override = "OVRD"; +} diff --git a/src/NTP.Domain/NTP.Domain.csproj b/src/NTP.Domain/NTP.Domain.csproj new file mode 100644 index 0000000..35e3d84 --- /dev/null +++ b/src/NTP.Domain/NTP.Domain.csproj @@ -0,0 +1,2 @@ + + diff --git a/src/NTP.Infrastructure/DependencyInjection.cs b/src/NTP.Infrastructure/DependencyInjection.cs new file mode 100644 index 0000000..530c9e0 --- /dev/null +++ b/src/NTP.Infrastructure/DependencyInjection.cs @@ -0,0 +1,62 @@ +using Dapper; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Infrastructure.HealthChecks; +using NTP.Infrastructure.Persistence; + +namespace NTP.Infrastructure; + +public static class DependencyInjection +{ + public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) + { + services.AddOptions() + .Bind(configuration.GetSection(OracleOptions.SectionName)) + .PostConfigure(o => + { + // 1. ConnectionStrings:NAFITHTCS 2. ConnectionStrings:NTP (legacy) 3. Oracle:ConnectionString 4. Oracle:Host/Port/... parts + var named = configuration.GetConnectionString(OracleOptions.ConnectionStringName); + var legacy = configuration.GetConnectionString(OracleOptions.LegacyConnectionStringName); + if (!string.IsNullOrWhiteSpace(named)) + o.ConnectionString = named; + else if (!string.IsNullOrWhiteSpace(legacy)) + o.ConnectionString = legacy; + else if (string.IsNullOrWhiteSpace(o.ConnectionString) && o.HasParts) + o.ConnectionString = o.BuildFromParts(); + }) + .Validate(o => !string.IsNullOrWhiteSpace(o.ConnectionString), + "No Oracle connection configured. Set ConnectionStrings:NAFITHTCS, Oracle:ConnectionString, " + + "or Oracle:Host + ServiceName (or Sid) + UserId + Password in appsettings.json.") + .Validate(o => o.CommandTimeoutSeconds is > 0 and <= 600, "Oracle:CommandTimeoutSeconds must be 1-600.") + .ValidateOnStart(); + + services.AddOptions() + .PostConfigure(o => o.ConnectionString = configuration.GetConnectionString(NtpSchemaOptions.ConnectionStringName) ?? string.Empty) + .Validate(o => !string.IsNullOrWhiteSpace(o.ConnectionString), "No NTP-schema Oracle connection configured. Set ConnectionStrings:NtpSchema (user NTP).") + .ValidateOnStart(); + + // SHIPMENT_NO -> ShipmentNo, CREATED_AT -> CreatedAt (case-insensitive, underscores ignored). + DefaultTypeMap.MatchNamesWithUnderscores = true; + + services.AddScoped(); + services.AddScoped(sp => sp.GetRequiredService()); + services.AddScoped(sp => sp.GetRequiredService()); + // Second connection (NTP schema). IDbSession / IUnitOfWork keep meaning the primary NAFITHTCS connection. + services.AddScoped(); + services.AddScoped(sp => sp.GetRequiredService()); + services.AddScoped(sp => sp.GetRequiredService()); + services.AddScoped(); + + // Convention: every concrete *Repository / *Service in this assembly is registered against I{Name} (scoped). + // Do NOT add per-table lines here. + services.AddConventionalServices(typeof(DependencyInjection).Assembly); + + services.AddHealthChecks() + .AddCheck("oracle", tags: ["ready"]) + .AddCheck("oracle-ntp", tags: ["ready"]); + + return services; + } +} diff --git a/src/NTP.Infrastructure/Grains/GrainsPermitJobsWorker.cs b/src/NTP.Infrastructure/Grains/GrainsPermitJobsWorker.cs new file mode 100644 index 0000000..6edd647 --- /dev/null +++ b/src/NTP.Infrastructure/Grains/GrainsPermitJobsWorker.cs @@ -0,0 +1,65 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Permits; + +namespace NTP.Infrastructure.Grains; + +/// +/// Scheduled jobs of the Grains permits slice (legacy jobs\activateGrainsDestination.cfm, checkForGabanEvents.cfm, parseGrainsPermits*.cfm, +/// getWeighbridgeEvents.cfm, getAqabaWeighbridgeEvents.cfm). Every job is DISABLED by default (Grains:Permits:Jobs:*:Enabled). +/// NOT registered automatically (the shared DI file is off-limits): add services.AddHostedService<GrainsPermitJobsWorker>() +/// (or call GrainsPermitJobsWorker.Register(services)) in Program.cs / DependencyInjection.cs. Each job can also be run on +/// demand through the SU-only endpoints of the permit controllers. +/// +public sealed class GrainsPermitJobsWorker(IServiceScopeFactory scopes, ILogger logger) : BackgroundService +{ + public static void Register(IServiceCollection services) => services.AddHostedService(); + + private readonly Dictionary _lastRun = []; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(TimeSpan.FromSeconds(30)); + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + try + { + await using var scope = scopes.CreateAsyncScope(); + var options = scope.ServiceProvider.GetRequiredService().Value.Jobs; + + await Run("activate-destinations", options.ActivateDestinations, scope, + sp => sp.GetRequiredService().ActivatePendingCompanyDestinationsAsync(stoppingToken), stoppingToken); + await Run("gaban-timeout", options.GabanTimeout, scope, + sp => sp.GetRequiredService().RevertUnloadedPermitsAsync("SYSTEM", stoppingToken), stoppingToken); + await Run("permit-seeding", options.PermitSeeding, scope, + sp => sp.GetRequiredService().FillCompanySharesAsync(stoppingToken), stoppingToken); + await Run("weighbridge-sync", options.WeighbridgeSync, scope, + sp => sp.GetRequiredService().SyncAsync(false, stoppingToken), stoppingToken); + await Run("aqaba-weighbridge-sync", options.AqabaWeighbridgeSync, scope, + sp => sp.GetRequiredService().SyncAsync(true, stoppingToken), stoppingToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Grains permit jobs tick failed"); + } + } + } + + private async Task Run(string name, JobSchedule schedule, AsyncServiceScope scope, Func> job, CancellationToken ct) + { + if (!schedule.Enabled) return; + var now = DateTime.UtcNow; + if (_lastRun.TryGetValue(name, out var last) && now - last < TimeSpan.FromMinutes(Math.Max(1, schedule.IntervalMinutes))) return; + _lastRun[name] = now; + try + { + var n = await job(scope.ServiceProvider); + logger.LogInformation("Grains job {Job} finished: {Count} row(s)", name, n); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Grains job {Job} failed", name); + } + } +} diff --git a/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs b/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs new file mode 100644 index 0000000..2bd5e3a --- /dev/null +++ b/src/NTP.Infrastructure/Grains/GrainsPermitsGateways.cs @@ -0,0 +1,200 @@ +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Xml.Linq; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Permits; + +namespace NTP.Infrastructure.Grains; + +// All classes end in "Service" so the shared convention registration (class X -> interface IX) picks them up without editing the DI files. + +/// Binds configuration section "Grains:Permits" (see GrainsPermitsOptions); settings are read once per scope. +internal sealed class GrainsPermitsSettingsService : IGrainsPermitsSettingsService +{ + public GrainsPermitsSettingsService(IConfiguration configuration) + { + Value = new GrainsPermitsOptions(); + configuration.GetSection(GrainsPermitsOptions.SectionName).Bind(Value); + } + + public GrainsPermitsOptions Value { get; } +} + +/// +/// TCS petroleum permit web service (legacy application.PetWS / ColdFusion cfinvoke). The Axis operation name and namespace are not in the +/// repository: SOAP 1.1 with operation createPermit(xml, flag) / getFopDetail(FOP) is assumed (UNVERIFIED, cannot be called from +/// here). Disabled unless Grains:Permits:Tcs:Enabled is true. +/// +internal sealed class TcsPermitGatewayService(IGrainsPermitsSettingsService settings, ILogger logger) + : ITcsPermitGatewayService +{ + private static readonly HttpClient Http = new(); + + private TcsOptions Options => settings.Value.Tcs; + + public async Task CreatePermitAsync(TcsPermitRequest r, CancellationToken ct = default) + { + if (!Options.Enabled) return new(null, null, "خدمة TCS غير مفعلة في الإعدادات"); + var xml = BuildShipmentXml(r); + try + { + var response = await CallAsync("createPermit", $"{Escape(xml)}1", ct); + var doc = XDocument.Parse(WebUnescape(response)); + var kids = doc.Root?.Elements().ToList() ?? []; + if (kids.Count < 3) return new(null, null, "خطأ في الاتصال
استجابة غير متوقعة"); + return new(kids[0].Value.Trim(), kids[2].Value.Trim(), string.Empty); // PN, status; kids[1] = error codes (CheckWSError) + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "TCS createPermit failed"); + return new(null, null, "خطأ في الاتصال
" + ex.Message); + } + } + + public async Task GetFopDetailAsync(string fop, CancellationToken ct = default) + { + if (!Options.Enabled) return Empty("خدمة TCS غير مفعلة في الإعدادات"); + try + { + var response = await CallAsync("getFopDetail", $"{Escape(fop)}", ct); + var root = XDocument.Parse(WebUnescape(response)).Root; + if (root is null || !root.HasElements) return Empty(string.Empty); + var k = root.Elements().ToList(); + var d = root.Element("DRIVER")?.Elements().ToList() ?? []; + string V(IReadOnlyList l, int i) => i < l.Count ? l[i].Value.Trim() : string.Empty; + return new(string.Empty, V(k, 0), V(k, 1), V(k, 2), V(k, 3), V(k, 6), V(d, 0), V(d, 1), V(d, 2), V(d, 4), V(d, 5), V(d, 6)); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "TCS getFopDetail failed"); + return Empty("خطأ في الاتصال
" + ex.Message); + } + } + + private static TcsFopDetail Empty(string error) => new(error, "", "", "", "", "", "", "", "", "", "", ""); + + private async Task CallAsync(string operation, string body, CancellationToken ct) + { + var envelope = $""" + + <{operation}>{body} + """; + using var req = new HttpRequestMessage(HttpMethod.Post, Options.PermitServiceUrl) + { + Content = new StringContent(envelope, Encoding.UTF8, "text/xml") + }; + req.Headers.Add("SOAPAction", "\"\""); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); + cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(5, Options.TimeoutSeconds))); + using var res = await Http.SendAsync(req, cts.Token); + res.EnsureSuccessStatusCode(); + var text = await res.Content.ReadAsStringAsync(cts.Token); + var soap = XDocument.Parse(text); + var ret = soap.Descendants().FirstOrDefault(e => e.Name.LocalName.EndsWith("Return", StringComparison.OrdinalIgnoreCase)); + return ret?.Value ?? text; + } + + private static string WebUnescape(string s) => s; + private static string Escape(string s) => System.Security.SecurityElement.Escape(s) ?? string.Empty; + + internal static string BuildShipmentXml(TcsPermitRequest r) + { + var asrn = r.Asrn.Length == 12 && r.Asrn.StartsWith("20", StringComparison.Ordinal) ? r.Asrn : string.Empty; + var crn = asrn.Length == 0 ? r.Asrn : string.Empty; + string A(string? v) => System.Security.SecurityElement.Escape(v ?? string.Empty) ?? string.Empty; + return TcsXmlTemplate.Shipment + .Replace("@@USERID@@", A(r.UserId.ToUpperInvariant())).Replace("@@COMPANYNAME@@", A(r.CompanyName)) + .Replace("@@DRVR@@", A(r.Drvr.Trim())).Replace("@@ASRN@@", A(asrn)).Replace("@@CRN@@", A(crn)).Replace("@@FOP@@", A(r.Fop)) + .Replace("@@SEALN@@", A(r.SealN)).Replace("@@TST@@", A(r.Tst)).Replace("@@CANNAME@@", A(r.CanName)).Replace("@@CAN@@", A(r.Can)) + .Replace("@@TN@@", A(r.Tn)).Replace("@@TRNAT@@", A(r.TrnAt)).Replace("@@TRN@@", A(r.Trn)).Replace("@@TT@@", A(r.Tt)) + .Replace("@@NNPN@@", A(r.Nnpn)).Replace("@@NAT@@", A(r.Nat)).Replace("@@CAT@@", A(r.Cat)).Replace("@@DLN@@", A(r.Dln)) + .Replace("@@FIRMS@@", A(r.Firms)).Replace("@@INBONDTYPECODE@@", A(r.InbondTypeCode)) + .Replace("@@ROUTINGTEMPLATEID@@", r.RoutingTemplateId.ToString()).Replace("@@SHIPMENTMODE@@", A(r.ShipmentMode)) + .Replace("@@ORIGINADDRESSID@@", r.OriginAddressId.ToString()).Replace("@@DESTINATIONADDRESSID@@", r.DestinationAddressId.ToString()); + } +} + +/// Mobile push notifications (legacy NTP.components.MobileNotifications). POSTs {template, payload} JSON to the configured URL. +internal sealed class MobileNotificationGatewayService(IGrainsPermitsSettingsService settings, ILogger logger) + : IMobileNotificationGatewayService +{ + private static readonly HttpClient Http = new(); + + public async Task SendAsync(string template, IReadOnlyDictionary payload, CancellationToken ct = default) + { + var o = settings.Value.Notifications; + if (!o.Enabled || string.IsNullOrWhiteSpace(o.Url)) return; + try + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); + cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds))); + var json = JsonSerializer.Serialize(new { template, payload }); + using var res = await Http.PostAsync(o.Url, new StringContent(json, Encoding.UTF8, "application/json"), cts.Token); + if (!res.IsSuccessStatusCode) logger.LogWarning("Notification {Template} -> {Status}", template, (int)res.StatusCode); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // legacy notifications were fire-and-forget; a failure never rolls back the business operation + logger.LogWarning(ex, "Notification {Template} failed", template); + } + } +} + +/// Auto dialer / IVR (GrainsFactoryWeb.autoCallService2 and callAPI). +internal sealed class AutoCallGatewayService(IGrainsPermitsSettingsService settings, ILogger logger) + : IAutoCallGatewayService +{ + private static readonly HttpClient Http = new(); + + public async Task SendCallFileAsync(byte[] csv, CancellationToken ct = default) + { + var o = settings.Value.AutoCall; + if (!o.Enabled || string.IsNullOrWhiteSpace(o.SendUrl)) return false; + try + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); + cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds))); + var body = "{\"TYPE\":\"TEST\",\"FILE\":\"" + Convert.ToBase64String(csv) + "\"}"; + using var res = await Http.PostAsync(o.SendUrl, new StringContent(body, Encoding.UTF8, new MediaTypeHeaderValue("application/json")), cts.Token); + return res.StatusCode == System.Net.HttpStatusCode.OK; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogWarning(ex, "Auto call dialer unreachable"); + return false; + } + } + + public async Task TriggerIvrAsync(CancellationToken ct = default) + { + var o = settings.Value.AutoCall; + if (!o.Enabled || string.IsNullOrWhiteSpace(o.IvrUrl)) return false; + try + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); + cts.CancelAfter(TimeSpan.FromSeconds(Math.Max(3, o.TimeoutSeconds))); + using var res = await Http.GetAsync(o.IvrUrl, cts.Token); + return res.IsSuccessStatusCode; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogWarning(ex, "IVR unreachable"); + return false; + } + } +} + +/// +/// External weighbridge database (legacy datasource GrainsWeighbridge, table CARGO). The database engine of that datasource is not known +/// (the connection is defined in the ColdFusion administrator, not in the repository), so no driver is bundled: this source reports +/// "not configured" and the weighbridge sync jobs skip. Provide another IWeighbridgeSourceService implementation to enable them. +/// +internal sealed class WeighbridgeSourceService : IWeighbridgeSourceService +{ + public bool IsConfigured => false; + + public Task> ReadNewAsync(long locationId, DateTime? after, CancellationToken ct = default) => + Task.FromResult>([]); +} diff --git a/src/NTP.Infrastructure/Grains/ReportExcelService.cs b/src/NTP.Infrastructure/Grains/ReportExcelService.cs new file mode 100644 index 0000000..f26f50e --- /dev/null +++ b/src/NTP.Infrastructure/Grains/ReportExcelService.cs @@ -0,0 +1,112 @@ +using ClosedXML.Excel; +using NTP.Application.Grains.Reports; + +namespace NTP.Infrastructure.Grains; + +/// ClosedXML implementation of (RTL worksheet, brand header row). +internal sealed class ReportExcelService : IReportExcelService +{ + private const string HeaderFill = "#17375D"; // legacy report header colour (.sub_header) + + public byte[] Build(ReportTable table, string printedBy, DateTime printedAt, bool arabic) + { + using var wb = new XLWorkbook(); + var title = arabic ? table.TitleAr : table.TitleEn; + var ws = wb.Worksheets.Add(SafeSheetName(title)); + ws.RightToLeft = arabic; + var cols = table.Columns; + var last = Math.Max(1, cols.Count); + + var r = 1; + ws.Cell(r, 1).Value = title; + ws.Range(r, 1, r, last).Merge().Style.Font.SetBold().Font.SetFontSize(18).Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center); + r++; + foreach (var line in table.FilterLines) + { + ws.Cell(r, 1).Value = line; + ws.Range(r, 1, r, last).Merge().Style.Font.SetBold(); + r++; + } + r++; + + var headerRow = r; + for (var c = 0; c < cols.Count; c++) + { + var cell = ws.Cell(r, c + 1); + cell.Value = arabic ? cols[c].HeaderAr : cols[c].HeaderEn; + cell.Style.Font.SetBold().Font.SetFontColor(XLColor.White).Fill.SetBackgroundColor(XLColor.FromHtml(HeaderFill)) + .Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center).Alignment.SetWrapText(); + } + r++; + + foreach (var row in table.Rows) + { + for (var c = 0; c < cols.Count; c++) + { + row.TryGetValue(cols[c].Key, out var v); + SetCell(ws.Cell(r, c + 1), v, cols[c].Kind); + } + r++; + } + if (cols.Count > 0 && table.Rows.Count > 0) + ws.Range(headerRow, 1, r - 1, last).Style.Border.SetOutsideBorder(XLBorderStyleValues.Thin).Border.SetInsideBorder(XLBorderStyleValues.Thin); + + r++; + ws.Cell(r, 1).Value = (arabic ? "طبع التقرير بواسطة : " : "Printed by: ") + printedBy; + ws.Cell(r + 1, 1).Value = (arabic ? "عدد النتائج : " : "Rows: ") + table.Rows.Count; + ws.Cell(r + 2, 1).Value = (arabic ? "بتاريخ : " : "On: ") + printedAt.ToString("dd/MM/yyyy HH:mm"); + + ws.SheetView.FreezeRows(headerRow); + ws.Columns().AdjustToContents(headerRow, headerRow + Math.Min(table.Rows.Count, 200)); + foreach (var col in ws.ColumnsUsed()) if (col.Width > 60) col.Width = 60; + ws.PageSetup.PageOrientation = XLPageOrientation.Landscape; + ws.PageSetup.FitToPages(1, 0); + + using var ms = new MemoryStream(); + wb.SaveAs(ms); + return ms.ToArray(); + } + + private static void SetCell(IXLCell cell, object? v, string kind) + { + switch (v) + { + case null: return; + case DateTime d: + cell.Value = d; + cell.Style.DateFormat.Format = kind == "date" ? "dd/MM/yyyy" : "dd/MM/yyyy HH:mm"; + return; + case decimal or double or float or int or long or short or byte: + cell.Value = Convert.ToDouble(v, System.Globalization.CultureInfo.InvariantCulture); + return; + case bool b: cell.Value = b; return; + default: + cell.Value = v.ToString() ?? ""; // ClosedXML stores strings as text (never as formulas) + return; + } + } + + private static string SafeSheetName(string s) + { + var bad = new[] { (char)92, '/', '?', '*', '[', ']', ':' }; + var n = new string(s.Where(c => !bad.Contains(c)).ToArray()).Trim(); + return string.IsNullOrEmpty(n) ? "Report" : n.Length > 31 ? n[..31] : n; + } + + public List ReadFirstSheet(Stream stream) + { + using var wb = new XLWorkbook(stream); + var ws = wb.Worksheets.First(); + var range = ws.RangeUsed(); + var rows = new List(); + if (range is null) return rows; + var cols = range.LastColumn().ColumnNumber(); + foreach (var row in range.Rows()) + { + var vals = new string[cols]; + for (var c = 1; c <= cols; c++) vals[c - 1] = row.Cell(c).GetFormattedString(); + rows.Add(vals); + } + return rows; + } +} diff --git a/src/NTP.Infrastructure/Grains/TcsXmlTemplate.cs b/src/NTP.Infrastructure/Grains/TcsXmlTemplate.cs new file mode 100644 index 0000000..bdf99c2 --- /dev/null +++ b/src/NTP.Infrastructure/Grains/TcsXmlTemplate.cs @@ -0,0 +1,84 @@ +namespace NTP.Infrastructure.Grains; + +/// Request body of the TCS petroleum permit web service (legacy grains.cfc createXML). Placeholders are @@NAME@@. +internal static class TcsXmlTemplate +{ + public const string Shipment = """ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"""; +} diff --git a/src/NTP.Infrastructure/Grains/WeighbridgeDirectoryWatcherWorker.cs b/src/NTP.Infrastructure/Grains/WeighbridgeDirectoryWatcherWorker.cs new file mode 100644 index 0000000..ca8f549 --- /dev/null +++ b/src/NTP.Infrastructure/Grains/WeighbridgeDirectoryWatcherWorker.cs @@ -0,0 +1,43 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Reports; +using NTP.Infrastructure.Persistence.Repositories.Grains.Reports; + +namespace NTP.Infrastructure.Grains; + +/// +/// Optional replacement of the ColdFusion DirectoryWatcher gateway (ReadFiles\DirectoryWatcherRs.cfg + WB\cfc\onAddDirectoryWatcher.cfc). +/// DISABLED by default (GrainsReports:Watcher:Enabled=false). It polls the configured directory every +/// IntervalSeconds, imports each file through and moves it to the archive directory. +/// NOT registered automatically (shared DI file is off-limits): add services.AddHostedService<WeighbridgeDirectoryWatcherWorker>() +/// to AddInfrastructure when the watcher should run. The same scan is available on demand at POST api/v1/grains/reports/weighbridge-files/scan. +/// +public sealed class WeighbridgeDirectoryWatcherWorker(IServiceScopeFactory scopes, IConfiguration configuration, + ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var cfg = new GrainsReportsConfig(configuration); + if (!cfg.WatcherEnabled || string.IsNullOrWhiteSpace(cfg.WatcherDirectory)) + { + logger.LogInformation("Weighbridge directory watcher is disabled (GrainsReports:Watcher:Enabled)."); + return; + } + logger.LogInformation("Weighbridge directory watcher started on {Dir} every {Seconds}s", cfg.WatcherDirectory, cfg.WatcherIntervalSeconds); + using var timer = new PeriodicTimer(TimeSpan.FromSeconds(cfg.WatcherIntervalSeconds)); + do + { + try + { + using var scope = scopes.CreateScope(); + var svc = scope.ServiceProvider.GetRequiredService(); + var r = await svc.ScanDirectoryAsync(cfg.WatcherDirectory!, cfg.WatcherArchive, stoppingToken); + if (r.Files > 0) logger.LogInformation("Weighbridge watcher imported {Files} file(s)", r.Files); + } + catch (OperationCanceledException) { break; } + catch (Exception ex) { logger.LogError(ex, "Weighbridge directory watcher pass failed"); } + } while (await timer.WaitForNextTickAsync(stoppingToken)); + } +} diff --git a/src/NTP.Infrastructure/HealthChecks/OracleHealthCheck.cs b/src/NTP.Infrastructure/HealthChecks/OracleHealthCheck.cs new file mode 100644 index 0000000..63a9758 --- /dev/null +++ b/src/NTP.Infrastructure/HealthChecks/OracleHealthCheck.cs @@ -0,0 +1,50 @@ +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Options; +using NTP.Infrastructure.Persistence; +using Oracle.ManagedDataAccess.Client; + +namespace NTP.Infrastructure.HealthChecks; + +internal static class OracleProbe +{ + public static async Task RunAsync(string connectionString, string name, CancellationToken ct) + { + var key = OracleCredentialGuard.KeyOf(connectionString); + try + { + // a monitor polling /health/ready must not keep failing logins against a rejected account + OracleCredentialGuard.EnsureAllowed(key); + await using var connection = new OracleConnection(connectionString); + try { await connection.OpenAsync(ct); } + catch (OracleException ex) { OracleCredentialGuard.Record(key, ex.Number); throw; } + OracleCredentialGuard.Succeeded(key); + await using var cmd = connection.CreateCommand(); + cmd.CommandText = "SELECT USER FROM DUAL"; + cmd.CommandTimeout = 5; + var user = await cmd.ExecuteScalarAsync(ct); + return HealthCheckResult.Healthy($"{name}: Oracle {connection.ServerVersion} as {user}"); + } + catch (DatabaseCredentialsRejectedException ex) + { + return HealthCheckResult.Unhealthy($"{name}: {ex.Message}"); + } + catch (Exception ex) + { + return HealthCheckResult.Unhealthy($"{name}: Oracle unreachable", ex); + } + } +} + +/// Primary connection (NAFITHTCS). +internal sealed class OracleHealthCheck(IOptions options) : IHealthCheck +{ + public Task CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default) => + OracleProbe.RunAsync(options.Value.ConnectionString, "NAFITHTCS", ct); +} + +/// Second connection (NTP schema). +internal sealed class NtpSchemaHealthCheck(IOptions options) : IHealthCheck +{ + public Task CheckHealthAsync(HealthCheckContext context, CancellationToken ct = default) => + OracleProbe.RunAsync(options.Value.ConnectionString, "NTP", ct); +} diff --git a/src/NTP.Infrastructure/NTP.Infrastructure.csproj b/src/NTP.Infrastructure/NTP.Infrastructure.csproj new file mode 100644 index 0000000..4727d95 --- /dev/null +++ b/src/NTP.Infrastructure/NTP.Infrastructure.csproj @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/src/NTP.Infrastructure/Persistence/DbSession.cs b/src/NTP.Infrastructure/Persistence/DbSession.cs new file mode 100644 index 0000000..c4cdb5e --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/DbSession.cs @@ -0,0 +1,135 @@ +using System.Data; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NTP.Application.Abstractions; +using Oracle.ManagedDataAccess.Client; + +namespace NTP.Infrastructure.Persistence; + +/// Connection + transaction shared by all repositories within one request scope. +public interface IDbSession +{ + Task GetConnectionAsync(CancellationToken ct = default); + OracleTransaction? Transaction { get; } + int CommandTimeoutSeconds { get; } +} + +/// +/// Session for the legacy NTP schema (NTPUSERS, ROLES, LOGS, COMPANIES, NATIONALITY, URL_SECURITY). +/// alone always means the primary NAFITHTCS connection. Transactions are per connection. +/// +public interface INtpDbSession : IDbSession; + +/// +/// Scoped per HTTP request. Opens one pooled Oracle connection lazily, and exposes it plus the +/// active transaction (if any) to repositories. Implements . +/// +internal abstract class OracleSessionBase(string connectionString, int commandTimeoutSeconds, ILogger logger) + : IDbSession, IUnitOfWork, IAsyncDisposable, IDisposable +{ + private OracleConnection? _connection; + private readonly string _accountKey = OracleCredentialGuard.KeyOf(connectionString); + + public OracleTransaction? Transaction { get; private set; } + public int CommandTimeoutSeconds => commandTimeoutSeconds; + + public async Task GetConnectionAsync(CancellationToken ct = default) + { + if (_connection is { State: ConnectionState.Open }) + return _connection; + + // never retry a rejected / locked account in a loop (see OracleCredentialGuard) + OracleCredentialGuard.EnsureAllowed(_accountKey); + _connection ??= new OracleConnection(connectionString); + try + { + await _connection.OpenAsync(ct); + } + catch (OracleException ex) + { + OracleCredentialGuard.Record(_accountKey, ex.Number, logger); + throw; + } + OracleCredentialGuard.Succeeded(_accountKey); + return _connection; + } + + public async Task BeginAsync(CancellationToken ct = default) + { + if (Transaction is not null) + throw new InvalidOperationException("A transaction is already active in this scope."); + + var connection = await GetConnectionAsync(ct); + // Oracle supports ReadCommitted (default) and Serializable only. + Transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted); + } + + public Task CommitAsync(CancellationToken ct = default) + { + if (Transaction is null) throw new InvalidOperationException("No active transaction."); + Transaction.Commit(); + EndTransaction(); + return Task.CompletedTask; + } + + public Task RollbackAsync(CancellationToken ct = default) + { + if (Transaction is null) return Task.CompletedTask; + try { Transaction.Rollback(); } + finally { EndTransaction(); } + return Task.CompletedTask; + } + + public async Task ExecuteInTransactionAsync(Func> work, CancellationToken ct = default) + { + // Join an outer transaction if one is already running (simple nesting support). + if (Transaction is not null) + return await work(ct); + + await BeginAsync(ct); + try + { + var result = await work(ct); + await CommitAsync(ct); + return result; + } + catch + { + try { await RollbackAsync(CancellationToken.None); } + catch (Exception rollbackEx) { logger.LogError(rollbackEx, "Oracle transaction rollback failed"); } + throw; + } + } + + private void EndTransaction() + { + Transaction?.Dispose(); + Transaction = null; + } + + public void Dispose() + { + if (Transaction is not null) + { + logger.LogWarning("Disposing DbSession with an uncommitted transaction - rolling back."); + try { Transaction.Rollback(); } catch { /* connection may already be broken */ } + EndTransaction(); + } + _connection?.Dispose(); // returns the connection to the ODP.NET pool + _connection = null; + } + + public ValueTask DisposeAsync() + { + Dispose(); + return ValueTask.CompletedTask; + } +} + +/// Primary connection = NAFITHTCS schema (legacy datasource "nafithtcs"). +internal sealed class DbSession(IOptions options, ILogger logger) + : OracleSessionBase(options.Value.ConnectionString, options.Value.CommandTimeoutSeconds, logger); + +/// Second connection = NTP schema (legacy datasource "NTP"). +internal sealed class NtpDbSession(IOptions options, IOptions primary, ILogger logger) + : OracleSessionBase(options.Value.ConnectionString, primary.Value.CommandTimeoutSeconds, logger), INtpDbSession, INtpUnitOfWork; diff --git a/src/NTP.Infrastructure/Persistence/EventLogger.cs b/src/NTP.Infrastructure/Persistence/EventLogger.cs new file mode 100644 index 0000000..b98b370 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/EventLogger.cs @@ -0,0 +1,72 @@ +using System.Text; +using System.Text.RegularExpressions; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Abstractions; + +namespace NTP.Infrastructure.Persistence; + +/// Port of services.cfc addEvent: INSERT INTO EVENTS with SEQ_EVENTS.nextval and bind variables. +internal sealed partial class EventLogger(IDbSession session, ICurrentUser currentUser, ILogger logger) + : OracleRepositoryBase(session, logger), IEventLogger +{ + private static readonly HashSet FixedColumns = new(StringComparer.OrdinalIgnoreCase) + { + "ID", "PREVSTATUS", "CURRENTSTATUS", "DONEBY", "EVENTTYPE", "DOMAIN", "LOCATIONID", "UPDATEDTYPE", "WEIGHT" + }; + + [GeneratedRegex("^[A-Z][A-Z0-9_]{0,29}$")] + private static partial Regex IdentifierRegex(); + + public Task AddForCurrentUserAsync(string refColumn, long refId, string? prevStatus, string? currentStatus, + string eventType, string? remarks = null, string? weight = null, CancellationToken ct = default) => + AddAsync(new EventEntry(refColumn, refId, prevStatus, currentStatus, currentUser.UserId, eventType, + currentUser.Domain, currentUser.LocationId?.ToString(), "NTP", weight, + remarks is null ? null : new Dictionary { ["REMARKS"] = remarks }), ct); + + public async Task AddAsync(EventEntry e, CancellationToken ct = default) + { + var refColumn = ValidateIdentifier(e.RefColumn, allowFixed: false); + + var cols = new StringBuilder($"ID, {refColumn}, PREVSTATUS, CURRENTSTATUS, DONEBY, EVENTTYPE, DOMAIN, LOCATIONID, UPDATEDTYPE, WEIGHT"); + var vals = new StringBuilder("SEQ_EVENTS.NEXTVAL, :RefId, :Prev, :Curr, :DoneBy, :EventType, :Domain, :LocationId, :UpdatedType, :Weight"); + + var p = new DynamicParameters(); + p.Add("RefId", e.RefId); + p.Add("Prev", e.PrevStatus); + p.Add("Curr", e.CurrentStatus); + p.Add("DoneBy", e.DoneBy?.ToUpperInvariant()); + p.Add("EventType", e.EventType); + p.Add("Domain", e.Domain); + p.Add("LocationId", string.IsNullOrEmpty(e.LocationId) ? null : e.LocationId); + p.Add("UpdatedType", e.UpdatedType); + p.Add("Weight", string.IsNullOrEmpty(e.Weight) ? null : e.Weight); + + if (e.ExtraColumns is { Count: > 0 }) + { + var i = 0; + foreach (var (name, value) in e.ExtraColumns) + { + var col = ValidateIdentifier(name, allowFixed: false); + if (string.Equals(col, refColumn, StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException($"Extra column '{col}' duplicates the reference column."); + cols.Append(", ").Append(col); + vals.Append(", :X").Append(i); + p.Add($"X{i}", value); + i++; + } + } + + await ExecuteAsync($"INSERT INTO EVENTS ({cols}) VALUES ({vals})", p, ct); + } + + private static string ValidateIdentifier(string name, bool allowFixed) + { + var upper = (name ?? string.Empty).Trim().ToUpperInvariant(); + if (!IdentifierRegex().IsMatch(upper)) + throw new ArgumentException($"'{name}' is not a valid EVENTS column name."); + if (!allowFixed && FixedColumns.Contains(upper)) + throw new ArgumentException($"'{name}' is a fixed EVENTS column and cannot be used here."); + return upper; + } +} diff --git a/src/NTP.Infrastructure/Persistence/NtpRepositoryBase.cs b/src/NTP.Infrastructure/Persistence/NtpRepositoryBase.cs new file mode 100644 index 0000000..5f3009a --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/NtpRepositoryBase.cs @@ -0,0 +1,9 @@ +using Microsoft.Extensions.Logging; + +namespace NTP.Infrastructure.Persistence; + +/// +/// Same Dapper helpers as but bound to the NTP-schema connection +/// (NTPUSERS, ROLES, LOGS, COMPANIES, NATIONALITY, URL_SECURITY ...). See docs/schema/NTP.md. +/// +public abstract class NtpRepositoryBase(INtpDbSession session, ILogger logger) : OracleRepositoryBase(session, logger); diff --git a/src/NTP.Infrastructure/Persistence/OracleCredentialGuard.cs b/src/NTP.Infrastructure/Persistence/OracleCredentialGuard.cs new file mode 100644 index 0000000..982bc67 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/OracleCredentialGuard.cs @@ -0,0 +1,83 @@ +using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; +using Oracle.ManagedDataAccess.Client; + +namespace NTP.Infrastructure.Persistence; + +/// Thrown instead of trying to connect while Oracle is known to reject (or lock) the configured account. +public sealed class DatabaseCredentialsRejectedException(string message) : InvalidOperationException(message); + +/// +/// Stops the application from locking its own database account. Every failed login counts towards the account's +/// FAILED_LOGIN_ATTEMPTS, so an instance that is configured with a wrong password (typically after the password was changed) +/// would lock the account again within seconds and keep re-locking it after every unlock. +/// +/// ORA-01017 (invalid username/password): the credential is wrong. Attempts for that account are suspended until the +/// process restarts (a corrected connection string needs a restart anyway) - one failed attempt, not hundreds. +/// ORA-28000 (account locked) / ORA-28001 (password expired): wait before the next attempt, so a +/// DBA unlock is picked up soon but a locked account is not hammered. +/// +/// State is per "user@data source"; the password is never stored or logged. +/// +public static class OracleCredentialGuard +{ + public static TimeSpan Cooldown { get; set; } = TimeSpan.FromSeconds(60); + + private sealed record State(bool Permanent, DateTime RetryAtUtc, int OraNumber); + private static readonly ConcurrentDictionary States = new(StringComparer.OrdinalIgnoreCase); + + /// "USER@datasource" taken from the connection string (no password). + public static string KeyOf(string connectionString) + { + try + { + var b = new OracleConnectionStringBuilder(connectionString); + return $"{b.UserID}@{b.DataSource}"; + } + catch + { + return "unknown"; + } + } + + /// Throws when a connection attempt must not be made now. + public static void EnsureAllowed(string key, DateTime? nowUtc = null) + { + if (!States.TryGetValue(key, out var s)) return; + if (s.Permanent) + throw new DatabaseCredentialsRejectedException( + $"Oracle rejected the credentials of {key} (ORA-{s.OraNumber:D5}). Connection attempts are suspended so the account is not locked by repeated failures; fix the connection string and restart the application."); + if ((nowUtc ?? DateTime.UtcNow) < s.RetryAtUtc) + throw new DatabaseCredentialsRejectedException( + $"Oracle account {key} is locked or expired (ORA-{s.OraNumber:D5}); the next attempt is after {s.RetryAtUtc:HH:mm:ss} UTC."); + } + + /// Remember a failed open. Returns true when it was a credential/lock problem the guard now handles. + public static bool Record(string key, int oraNumber, ILogger? logger = null, DateTime? nowUtc = null) + { + var now = nowUtc ?? DateTime.UtcNow; + switch (oraNumber) + { + case 1017: + if (States.TryAdd(key, new State(true, DateTime.MaxValue, oraNumber))) + logger?.LogError("Oracle rejected the credentials of {Account} (ORA-01017). Further attempts are suspended until the application restarts so the account is not locked; fix the connection string and restart.", key); + return true; + case 28000: + case 28001: + States[key] = new State(false, now + Cooldown, oraNumber); + logger?.LogWarning("Oracle account {Account} is locked or expired (ORA-{Ora:D5}); pausing connection attempts for {Seconds}s.", key, oraNumber, (int)Cooldown.TotalSeconds); + return true; + default: + return false; + } + } + + /// A connection opened fine: forget a temporary lock state. + public static void Succeeded(string key) + { + if (States.TryGetValue(key, out var s) && !s.Permanent) States.TryRemove(key, out _); + } + + /// For tests. + public static void Reset() => States.Clear(); +} diff --git a/src/NTP.Infrastructure/Persistence/OracleOptions.cs b/src/NTP.Infrastructure/Persistence/OracleOptions.cs new file mode 100644 index 0000000..d5688a7 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/OracleOptions.cs @@ -0,0 +1,95 @@ +using Oracle.ManagedDataAccess.Client; + +namespace NTP.Infrastructure.Persistence; + +/// +/// Oracle settings, bound from the "Oracle" section of appsettings*.json. +/// +/// The connection string is resolved in this order (first non-empty wins): +/// 1. ConnectionStrings:NAFITHTCS (primary = NAFITHTCS schema; the NTP schema is ConnectionStrings:NtpSchema) +/// 1b. ConnectionStrings:NTP (legacy fallback) +/// 2. Oracle:ConnectionString (full ODP.NET connection string) +/// 3. Oracle:Host/Port/ServiceName|Sid/UserId/Password (+ pool settings) - built for you +/// +/// Any value can be overridden per environment by appsettings.{Environment}.json, +/// appsettings.Local.json (git-ignored), or environment variables, e.g. +/// ConnectionStrings__NAFITHTCS=... or Oracle__Password=... +/// +public sealed class OracleOptions +{ + public const string SectionName = "Oracle"; + public const string ConnectionStringName = "NAFITHTCS"; + public const string LegacyConnectionStringName = "NTP"; + + /// Full ODP.NET connection string. After startup this always holds the resolved value. + public string ConnectionString { get; set; } = string.Empty; + + // ---- Option 3: individual parts (easier for ops to edit than a long string) ---- + public string? Host { get; set; } + public int Port { get; set; } = 1521; + + /// Service name (preferred). Use only for old SID-based listeners. + public string? ServiceName { get; set; } + public string? Sid { get; set; } + + public string? UserId { get; set; } + public string? Password { get; set; } + + // ---- Pooling / performance (applied in option 3; ignored when a full string is supplied) ---- + public int MinPoolSize { get; set; } = 1; + public int MaxPoolSize { get; set; } = 50; + public int ConnectionTimeoutSeconds { get; set; } = 15; + public int StatementCacheSize { get; set; } = 50; + + /// Per-command timeout. Keep below the gateway/HTTP timeout. + public int CommandTimeoutSeconds { get; set; } = 30; + + internal bool HasParts => + !string.IsNullOrWhiteSpace(Host) && + (!string.IsNullOrWhiteSpace(ServiceName) || !string.IsNullOrWhiteSpace(Sid)) && + !string.IsNullOrWhiteSpace(UserId) && + !string.IsNullOrWhiteSpace(Password); + + /// Builds an ODP.NET connection string from the individual parts. + internal string BuildFromParts() + { + var connectData = !string.IsNullOrWhiteSpace(ServiceName) + ? $"(SERVICE_NAME={ServiceName})" + : $"(SID={Sid})"; + + var builder = new OracleConnectionStringBuilder + { + DataSource = $"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={Host})(PORT={Port}))(CONNECT_DATA={connectData}))", + UserID = UserId, + Password = Password, + Pooling = true, + MinPoolSize = MinPoolSize, + MaxPoolSize = MaxPoolSize, + ConnectionTimeout = ConnectionTimeoutSeconds, + StatementCacheSize = StatementCacheSize + }; + return builder.ConnectionString; + } + + /// Connection string with the password masked - safe to log. + public string ToSafeString() + { + try + { + var b = new OracleConnectionStringBuilder(ConnectionString); + if (!string.IsNullOrEmpty(b.Password)) b.Password = "****"; + return b.ConnectionString; + } + catch + { + return ""; + } + } +} + +/// Second connection, to the NTP schema: ConnectionStrings:NtpSchema (required). +public sealed class NtpSchemaOptions +{ + public const string ConnectionStringName = "NtpSchema"; + public string ConnectionString { get; set; } = string.Empty; +} diff --git a/src/NTP.Infrastructure/Persistence/OracleRepositoryBase.cs b/src/NTP.Infrastructure/Persistence/OracleRepositoryBase.cs new file mode 100644 index 0000000..c568e97 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/OracleRepositoryBase.cs @@ -0,0 +1,55 @@ +using Dapper; +using Microsoft.Extensions.Logging; + +namespace NTP.Infrastructure.Persistence; + +/// +/// Thin Dapper wrapper: every call automatically uses the scoped connection, enlists in the active +/// transaction, applies the configured command timeout and honours the CancellationToken. +/// Dapper sets OracleCommand.BindByName = true, so :Name parameters bind by name, not position. +/// +public abstract class OracleRepositoryBase(IDbSession session, ILogger logger) +{ + protected IDbSession Session { get; } = session; + + private CommandDefinition Command(string sql, object? param, CancellationToken ct) + { + if (logger.IsEnabled(LogLevel.Debug)) + logger.LogDebug("Oracle SQL: {Sql}", sql); + + return new CommandDefinition(sql, param, Session.Transaction, Session.CommandTimeoutSeconds, + cancellationToken: ct); + } + + protected async Task> QueryAsync(string sql, object? param = null, CancellationToken ct = default) + { + var connection = await Session.GetConnectionAsync(ct); + var rows = await connection.QueryAsync(Command(sql, param, ct)); + return rows.AsList(); + } + + protected async Task QuerySingleOrDefaultAsync(string sql, object? param = null, CancellationToken ct = default) + { + var connection = await Session.GetConnectionAsync(ct); + return await connection.QuerySingleOrDefaultAsync(Command(sql, param, ct)); + } + + /// First row or default (use with an ORDER BY for determinism). + protected async Task QueryFirstAsync(string sql, object? param = null, CancellationToken ct = default) + { + var connection = await Session.GetConnectionAsync(ct); + return await connection.QueryFirstOrDefaultAsync(Command(sql, param, ct)); + } + + protected async Task ExecuteScalarAsync(string sql, object? param = null, CancellationToken ct = default) + { + var connection = await Session.GetConnectionAsync(ct); + return (await connection.ExecuteScalarAsync(Command(sql, param, ct)))!; + } + + protected async Task ExecuteAsync(string sql, object? param = null, CancellationToken ct = default) + { + var connection = await Session.GetConnectionAsync(ct); + return await connection.ExecuteAsync(Command(sql, param, ct)); + } +} diff --git a/src/NTP.Infrastructure/Persistence/OracleSql.cs b/src/NTP.Infrastructure/Persistence/OracleSql.cs new file mode 100644 index 0000000..5e8b1b0 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/OracleSql.cs @@ -0,0 +1,42 @@ +using Oracle.ManagedDataAccess.Types; + +namespace NTP.Infrastructure.Persistence; + +/// SQL helpers that are safe on Oracle 11g (no OFFSET/FETCH, no IDENTITY, no BOOLEAN in SQL). +public static class OracleSql +{ + /// + /// Wraps a query in the classic 11g ROWNUM pagination pattern. + /// MUST contain a deterministic ORDER BY + /// (include the primary key as a tie-breaker) or pages will overlap/skip rows. + /// Requires bind variables :MinRow (exclusive) and :MaxRow (inclusive). + /// + public static string Paginate(string innerSqlWithOrderBy) => $""" + SELECT * FROM ( + SELECT q__.*, ROWNUM AS RN__ + FROM ( {innerSqlWithOrderBy} ) q__ + WHERE ROWNUM <= :MaxRow + ) + WHERE RN__ > :MinRow + """; + + /// Wraps a query (without ORDER BY) in SELECT COUNT(*). + public static string Count(string innerSqlWithoutOrderBy) => + $"SELECT COUNT(*) FROM ( {innerSqlWithoutOrderBy} )"; + + /// Converts a .NET bool to Oracle NUMBER(1). ODP.NET 21.x cannot bind bool directly. + public static int ToNumber(bool value) => value ? 1 : 0; + + /// Escapes LIKE wildcards; use with LIKE :p ESCAPE '\'. + public static string EscapeLike(string value) => + value.Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_"); + + /// Converts an output-parameter value (OracleDecimal or .NET numeric) to long. + public static long ToInt64(object? value) => value switch + { + OracleDecimal od when !od.IsNull => od.ToInt64(), + null or DBNull => throw new InvalidOperationException("Output parameter returned NULL."), + OracleDecimal => throw new InvalidOperationException("Output parameter returned NULL."), + _ => Convert.ToInt64(value) + }; +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Access/PermissionRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Access/PermissionRepository.cs new file mode 100644 index 0000000..6b86f8f --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Access/PermissionRepository.cs @@ -0,0 +1,29 @@ +using Microsoft.Extensions.Logging; +using NTP.Application.Access; +using Oracle.ManagedDataAccess.Client; + +namespace NTP.Infrastructure.Persistence.Repositories.Access; + +/// +/// GRAINS_SCREEN_PERMISSIONS (ROLECODE, RESOURCE_KEY) on the primary NAFITHTCS schema; DDL and seed in +/// db/grains-screen-permissions.sql. Returns null while the table does not exist (ORA-00942) so the built-in +/// defaults apply. +/// +internal sealed class PermissionRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IPermissionRepository +{ + public async Task?> GetAllowedAsync(string roleCode, CancellationToken ct = default) + { + try + { + return await QueryAsync( + "SELECT resource_key FROM GRAINS_SCREEN_PERMISSIONS WHERE UPPER(rolecode) = UPPER(:RoleCode)", + new { RoleCode = roleCode }, ct); + } + catch (OracleException ex) when (ex.Number == 942) + { + logger.LogWarning("GRAINS_SCREEN_PERMISSIONS does not exist; using the built-in permission defaults. Run db/grains-screen-permissions.sql."); + return null; + } + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/AuthRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/AuthRepository.cs new file mode 100644 index 0000000..172114f --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/AuthRepository.cs @@ -0,0 +1,174 @@ +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Auth; + +namespace NTP.Infrastructure.Persistence.Repositories; + +/// +/// SQL ported from signon.cfc / info.cfc / logs.cfc / Application.cfc. Uses TWO connections (docs/schema): +/// NTP schema (this base: NTPUSERS, COMPANIES, ROLES, GROUPS, LOGS) and primary NAFITHTCS (Primary: UTT, LOCATIONS, LOCATIONS_IPS, INVALID_ACCESS_LOG). +/// +internal sealed class AuthRepository(INtpDbSession session, IDbSession primarySession, ILogger logger) + : NtpRepositoryBase(session, logger), IAuthRepository +{ + private PrimaryAccess Primary { get; } = new(primarySession, logger); + + /// Dapper helpers on the primary NAFITHTCS connection (UTT, LOCATIONS, LOCATIONS_IPS, INVALID_ACCESS_LOG). + private sealed class PrimaryAccess(IDbSession s, ILogger l) : OracleRepositoryBase(s, l) + { + public Task> ListAsync(string sql, object? p, CancellationToken ct) => QueryAsync(sql, p, ct); + public Task FirstAsync(string sql, object? p, CancellationToken ct) => QueryFirstAsync(sql, p, ct); + public Task ScalarAsync(string sql, object? p, CancellationToken ct) => ExecuteScalarAsync(sql, p, ct); + public Task ExecAsync(string sql, object? p, CancellationToken ct) => ExecuteAsync(sql, p, ct); + } + + public Task FindActiveUserByPasswordAsync(string login, string domain, + IReadOnlyList passwordCandidates, bool requireActiveCompany, CancellationToken ct = default) + { + var p = new DynamicParameters(); + p.Add("Login", login); + p.Add("Domain", domain); + + var pwdParams = new List(); + for (var i = 0; i < passwordCandidates.Count; i++) + { + p.Add($"Pwd{i}", passwordCandidates[i]); + pwdParams.Add($":Pwd{i}"); + } + + var sql = new StringBuilder(); + if (requireActiveCompany) + sql.Append(""" + SELECT u.ID, u.ROLECODE, TO_CHAR(u.EMPNO) AS EMPNO, u.LOCATIONID + FROM NTPUSERS u, COMPANIES c + WHERE upper(u.LOGIN) = upper(:Login) + AND u.PASSWORD IN ( + """).Append(string.Join(',', pwdParams)).Append(""" + ) + AND upper(u.DOMAINNAME) = upper(:Domain) + AND u.STATUS = 1 + AND u.COMPANYID = c.ID + AND c.STATUS = 1 + ORDER BY u.ID + """); + else + sql.Append(""" + SELECT ID, ROLECODE, TO_CHAR(EMPNO) AS EMPNO, LOCATIONID + FROM NTPUSERS + WHERE upper(LOGIN) = upper(:Login) + AND PASSWORD IN ( + """).Append(string.Join(',', pwdParams)).Append(""" + ) + AND upper(DOMAINNAME) = upper(:Domain) + AND STATUS = 1 + ORDER BY ID + """); + + return QueryFirstAsync(sql.ToString(), p, ct); + } + + public async Task HasActiveBoothAsync(string login, CancellationToken ct = default) => + await Primary.ScalarAsync(""" + SELECT COUNT(*) FROM UTT + WHERE LOWER(USERID) = LOWER(:Login) AND STATUS = 'ACTIVE' AND DOMAIN = 'ASEZA' + """, new { Login = login }, ct) > 0; + + public Task GetProfileAsync(string login, string domain, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT t.ID, t.DOMAINNAME, t.FIRSTNAME AS NAME, t.ROLECODE, TO_CHAR(t.EMPNO) AS EMPNO, + t.LOCATIONID, t.COMPANYID, TO_CHAR(t.RESET_PASSWORD) AS RESETPASSWORD, + c.NAME AS COMPANYNAME, c.DESCRIPTION AS COMPANYCODE + FROM NTPUSERS t, COMPANIES c + WHERE lower(t.LOGIN) = lower(:Login) + AND upper(t.DOMAINNAME) = upper(:Domain) + AND t.COMPANYID = c.ID + AND t.STATUS = 1 + ORDER BY t.ID + """, new { Login = login, Domain = domain }, ct); + + public Task GetRoleNameAsync(string roleCode, CancellationToken ct = default) => + QueryFirstAsync("SELECT NAME FROM ROLES WHERE lower(CODE) = lower(:Code) ORDER BY CODE", + new { Code = roleCode }, ct); + + public Task GetHierarchyAsync(long userDbId, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT t.COMPANYID, g.ID AS GROUPID, g.STAKEHOLDERID + FROM NTPUSERS t, GROUPS g + WHERE g.NAME = t.ROLECODE + AND t.ID = :UserId + AND g.STATUS = 1 + AND t.STATUS = 1 + ORDER BY g.ID + """, new { UserId = userDbId }, ct); + + public Task GetLocationAsync(long locationId, string? domain, CancellationToken ct = default) => + domain is null + ? Primary.FirstAsync("SELECT TYPE, NAME FROM LOCATIONS WHERE ID = :Id ORDER BY ID", new { Id = locationId }, ct) + : Primary.FirstAsync("SELECT TYPE, NAME FROM LOCATIONS WHERE ID = :Id AND DOMAIN = :Domain ORDER BY ID", + new { Id = locationId, Domain = domain }, ct); + + public async Task IsActiveWithRoleAsync(string login, string roleCode, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM NTPUSERS + WHERE ROLECODE = :Role AND upper(LOGIN) = upper(:Login) AND STATUS = 1 + """, new { Role = roleCode, Login = login }, ct) > 0; + + public Task UpdatePasswordAsync(string login, string domain, string newPassword, string updatedBy, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE NTPUSERS + SET PASSWORD = :Pwd, LASTUPDATEDATE = SYSDATE, UPDATEDBY = :UpdatedBy + WHERE lower(LOGIN) = lower(:Login) + AND upper(DOMAINNAME) = upper(:Domain) + AND STATUS = 1 + """, new { Pwd = newPassword, UpdatedBy = updatedBy, Login = login, Domain = domain }, ct); + + public async Task> GetLocationIpsAsync(string locationId, CancellationToken ct = default) => + await Primary.ListAsync("SELECT IP_ADDRESS FROM LOCATIONS_IPS WHERE LOCATION_ID = :Loc ORDER BY IP_ADDRESS", + new { Loc = locationId }, ct); + + public Task GetLocationForIpAsync(string ip, CancellationToken ct = default) => + Primary.FirstAsync("SELECT TO_CHAR(LOCATION_ID) FROM LOCATIONS_IPS WHERE IP_ADDRESS = :Ip ORDER BY LOCATION_ID", + new { Ip = ip }, ct); + + public async Task InsertInvalidAccessLogAsync(InvalidAccessEntry e, CancellationToken ct = default) + { + // Legacy uses a positional INSERT (no column list); here the columns are listed explicitly (docs/schema/NAFITHTCS.md): + // id, user id, date, location, role, valid ips, remote ip, remote ip location, user agent, reason, app. + var id = await Primary.ScalarAsync("SELECT SEQ_INVALID_ACCESS_LOG.NEXTVAL FROM DUAL", null, ct); + await Primary.ExecAsync(""" + INSERT INTO INVALID_ACCESS_LOG (ID, USER_ID, CREATION_DATE, USER_LOCATION_ID, ROLE_CODE, USER_IP_ADDRESS, + CURRENT_IP_ADDRESS, CURRENT_LOCATION_ID, BROWSER, REASON_ID, SOURCE_APP) + VALUES (:Id, :UserId, SYSDATE, :LocationId, :Role, :ValidIps, :RemoteIp, :RemoteLocation, :UserAgent, :Reason, 'NTP') + """, new + { + Id = id, + UserId = e.UserDbId, + LocationId = e.LocationId, + Role = Cut(e.RoleCode, 15), + ValidIps = Cut(e.ValidIps, 50), + RemoteIp = Cut(e.RemoteIp, 50), + RemoteLocation = e.RemoteIpLocationId, + UserAgent = Cut(e.UserAgent, 300), + Reason = e.ReasonId + }, ct); + } + + /// Truncates to the real column length (docs/schema) so a long User-Agent / IPv6 address cannot fail the audit insert with ORA-12899. + private static string? Cut(string? s, int max) => s is { Length: var n } && n > max ? s[..max] : s; + + public Task InsertLogAsync(AuditLogEntry e, CancellationToken ct = default) => + // logs.addLog -> db.addDBRecordNOORM('LOGS') => ID from seq_LOGS.nextval; REFERENCEID/APPTYPE left empty (NULL). + ExecuteAsync(""" + INSERT INTO LOGS (ID, DONEBY, IPADDRESS, DONEBYROLE, LOGTYPE, DONEBYNAME, BROWSER) + VALUES (SEQ_LOGS.NEXTVAL, :DoneBy, :Ip, :Role, :LogType, :Name, :Browser) + """, new + { + DoneBy = e.DoneBy, + Ip = Cut(e.Ip, 15), // LOGS.IPADDRESS is VARCHAR2(15) + Role = e.DoneByRole, + LogType = e.LogType, + Name = e.DoneByName, + Browser = Cut(e.Browser, 900) + }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/BillingRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/BillingRepository.cs new file mode 100644 index 0000000..475c7c6 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/BillingRepository.cs @@ -0,0 +1,174 @@ +using System.Data; +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; +using NTP.Domain.Grains.Orders; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Orders; + +/// Port of Invoice.cfc SQL (GRAINS_BILLING, GRAINS_WAGE, GRAINS_FINE, events-based weights). +internal sealed class BillingRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IBillingRepository +{ + public Task GetPermitBillingInfoAsync(long pn, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT p.pn AS Pn, + p.companycode AS Scac, + getcompanynamefromscac(p.companycode, 62) AS CompanyName, + p.shipmentmode AS CargoType, + p.tn AS Tn, + p.originaddressid AS Origin, + (SELECT MIN(e.eventdate) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'LTW') AS LoadDate, + NVL((SELECT MIN(e.weight) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'LTW'), 0) AS Ltw, + NVL((SELECT MIN(e.weight) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'LGW'), 0) AS Lgw, + p.destinationaddressid AS Destination, + NVL((SELECT MIN(e.eventdate) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'DTW'), + (SELECT MIN(e.eventdate) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'LTW') + 1) AS DischargeDate, + NVL((SELECT MIN(e.weight) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'DTW'), 0) AS Dtw, + NVL((SELECT MIN(e.weight) FROM events e WHERE e.permitid = p.id AND e.eventtype = 'DGW'), 0) AS Dgw, + i.lastInvoice AS LastInvoice + FROM permits p, + (SELECT DISTINCT FIRST_VALUE(t.invoicenumber) OVER (PARTITION BY t.scac ORDER BY t.id DESC) lastInvoice, scac + FROM GRAINS_BILLING t) i + WHERE p.domain = 'GN' + AND p.shipmentstatuscode = 'CLOSE' + AND i.scac(+) = p.companycode + AND p.pn = :Pn + """, new { Pn = pn.ToString() }, ct); + + public Task GetWageRateAsync(long destination, DateTime loadDate, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT w.wage AS Wage + FROM GRAINS_WAGE w + WHERE w.locationid = :Dest + AND :LoadDate BETWEEN w.startdate AND w.enddate + ORDER BY w.startdate DESC + """, new { Dest = destination, LoadDate = loadDate.Date }, ct); + + public Task GetFineRateAsync(DateTime loadDate, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT f.allowance AS Allowance, f.fine AS Fine + FROM grains_fine f + WHERE f.cargotype = :FineCargo + AND :LoadDate BETWEEN f.startdate AND f.enddate + ORDER BY f.startdate DESC + """, new { FineCargo = GrainsOrderConstants.FineCargoTypeId, LoadDate = loadDate.Date }, ct); + + // Mirrors db.cfc addDBRecordNOORM: ID comes from seq_
.nextval. + public async Task InsertAsync(NewGrainsBilling b, CancellationToken ct = default) + { + var p = new DynamicParameters(new + { + b.Pn, + b.SerialNo, + b.Tn, + b.CargoType, + b.Destination, + LoadDate = b.LoadDate.Date, + DischargeDate = b.DischargeDate.Date, + b.Dtw, + b.Dgw, + b.Dnw, + b.Ltw, + b.Lgw, + b.Lnw, + b.Scac, + b.InvoiceNumber, + b.Origin, + b.Price, + b.FinePrice, + b.FinalCost, + b.LoseFine + }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + + await ExecuteAsync(""" + INSERT INTO GRAINS_BILLING + (ID, PN, SERIALNO, TN, CARGOTYPE, DESTINATION, LOADDATE, DISCHARGEDATE, DTW, DGW, DNW, LTW, LGW, LNW, + SCAC, INVOICENUMBER, ORIGIN, PRICE, FINEPRICE, FINALCOST, LOSEFINE) + VALUES + (seq_GRAINS_BILLING.NEXTVAL, :Pn, :SerialNo, :Tn, :CargoType, :Destination, :LoadDate, :DischargeDate, :Dtw, :Dgw, :Dnw, :Ltw, :Lgw, :Lnw, + :Scac, :InvoiceNumber, :Origin, :Price, :FinePrice, :FinalCost, :LoseFine) + RETURNING ID INTO :NewId + """, p, ct); + return OracleSql.ToInt64(p.Get("NewId")); + } + + public async Task> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct = default) + { + var sql = new StringBuilder(""" + SELECT t.id AS Id, + ctp.name AS CargoType, + getcompanynamefromscac(t.scac, 62) AS Scac, + t.pn AS Pn, + t.tn AS Tn, + t.loaddate AS LoadDate, + loc.name AS Destination, + t.dischargedate AS DischargeDate, + t.lnw AS Lnw, + t.dnw AS Dnw, + t.price AS Price, + t.fineprice AS FinePrice + FROM GRAINS_BILLING t, + (SELECT * FROM CARGOTYPE WHERE domain = 'GN') ctp, + (SELECT * FROM LOCATIONS l WHERE l.domain = 'GN' AND l.type = 'EX' AND l.area IS NULL AND l.status = '1') loc + WHERE t.cargotype = ctp.id + AND t.destination = loc.id + """); + var p = new DynamicParameters(); + if (!string.IsNullOrWhiteSpace(query.Tn)) { sql.Append(" AND t.tn = :Tn"); p.Add("Tn", query.Tn.Trim()); } + if (query.Pn.HasValue) { sql.Append(" AND t.pn = :Pn"); p.Add("Pn", query.Pn.Value.ToString()); } + if (query.Scac.HasValue) { sql.Append(" AND t.scac = :Scac"); p.Add("Scac", query.Scac.Value.ToString()); } + + var baseSql = sql.ToString(); + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY t.pn, t.id"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } +} + +/// Port of Invoice.cfc getInvoiceGrid (legacy datasource GNB, assumed to be the same schema). +internal sealed class InvoiceRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IInvoiceRepository +{ + public async Task> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct = default) + { + var sql = new StringBuilder(""" + SELECT i.invoicenumber AS InvoiceNumber, + i.id AS Id, + i.statuscode AS StatusCode, + COUNT(*) AS Cnt, + ntc.name AS CompanyName, + i.scac AS Scac, + TO_CHAR(i.invoicedate, 'yyyy/mm/dd') AS InvoiceDate + FROM INVOICE i, ntp_tenders_companies ntc, GRAINS_BILLING gb + WHERE i.scac = ntc.scac + AND gb.scac = i.scac + AND gb.invoicenumber = i.invoicenumber + AND i.statuscode NOT IN ('DELETED', 'ACTIVE') + AND i.domain = 'GN' + """); + var p = new DynamicParameters(); + if (invoiceNumber.HasValue) { sql.Append(" AND i.invoicenumber = :InvoiceNumber"); p.Add("InvoiceNumber", invoiceNumber.Value.ToString()); } + sql.Append(""" + + GROUP BY i.invoicenumber, i.id, i.statuscode, ntc.name, i.scac, TO_CHAR(i.invoicedate, 'yyyy/mm/dd') + """); + + var baseSql = sql.ToString(); + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync( + OracleSql.Paginate(baseSql + " ORDER BY TO_CHAR(i.invoicedate, 'yyyy/mm/dd'), i.invoicenumber, i.id"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/OrderLookupRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/OrderLookupRepository.cs new file mode 100644 index 0000000..ba2caad --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/OrderLookupRepository.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Orders; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Orders; + +/// Dropdown sources of the orders slice (CARGOTYPE, LOCATIONS, NTP_TENDERS_COMPANIES). +internal sealed class OrderLookupRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IOrderLookupRepository +{ + private sealed class OptionRow + { + public long Id { get; set; } + public string? Name { get; set; } + } + + private sealed class CompanyRow + { + public long Scac { get; set; } + public string? Label { get; set; } + } + + private async Task> OptionsAsync(string sql, object? p, CancellationToken ct) => + (await QueryAsync(sql, p, ct)).Select(r => new LookupOptionDto(r.Id, r.Name)).ToList(); + + public Task> GetCargoTypesAsync(CancellationToken ct = default) => + OptionsAsync("SELECT id AS Id, name AS Name FROM CARGOTYPE WHERE domain = 'GN' ORDER BY id", null, ct); + + public Task> GetLocationsAsync(string type, CancellationToken ct = default) => + OptionsAsync("SELECT id AS Id, name AS Name FROM LOCATIONS WHERE domain = 'GN' AND type = :Type AND status = '1' ORDER BY name, id", + new { Type = type }, ct); + + public Task> GetBillingDestinationsAsync(CancellationToken ct = default) => + OptionsAsync(""" + SELECT id AS Id, name AS Name FROM LOCATIONS t + WHERE t.domain = 'GN' AND t.type = 'EX' AND t.area IS NULL AND t.status = '1' + ORDER BY name, id + """, null, ct); + + public Task> GetPackedDestinationsAsync(CancellationToken ct = default) => + OptionsAsync(""" + SELECT t.id AS Id, t.name AS Name FROM LOCATIONS t + WHERE t.domain = 'GN' AND t.status = '1' AND t.gn_type = 'PCKD' AND t.type = 'EX' + ORDER BY t.sortorder, t.id + """, null, ct); + + public async Task> GetCompaniesAsync(CancellationToken ct = default) => + (await QueryAsync(""" + SELECT t.scac AS Scac, + t.scac || '-' || getcompanynamefromscac(t.scac, 62) AS Label + FROM NTP_TENDERS_COMPANIES t + WHERE t.statuscode = 'ACTIVE' + ORDER BY DECODE(t.scac, 327, 1, t.scac) + """, null, ct)).Select(r => new CompanyOptionDto(r.Scac, r.Label)).ToList(); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/QuotaRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/QuotaRepository.cs new file mode 100644 index 0000000..3865a45 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/QuotaRepository.cs @@ -0,0 +1,78 @@ +using System.Data; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Orders; + +/// Port of grains.cfc getQuotaList / editQuota SQL (DESTINATIONS, DESTINATION_QUOTA). +internal sealed class QuotaRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IQuotaRepository +{ + private sealed class ActiveRow + { + public long Id { get; set; } + public int Quota { get; set; } + public int? DoneQuota { get; set; } + } + + public async Task> GetListAsync(DateTime date, PageRequest page, CancellationToken ct = default) + { + const string baseSql = """ + SELECT d.id AS DestinationId, + d.name AS Name, + q.quota AS Quota, + q.donequota AS DoneQuota, + q.createdby AS CreatedBy, + q.creationdate AS CreationDate + FROM DESTINATIONS d, + (SELECT t.destinationid destid, t.quota, t.createdby, t.creationdate, t.donequota + FROM DESTINATION_QUOTA t + WHERE t.isactive = 1 + AND t.quotadate >= :Day AND t.quotadate < :Day + 1) q + WHERE d.id = q.destid(+) + AND d.domain = 'GN' + """; + var p = new DynamicParameters(); + p.Add("Day", date.Date, DbType.DateTime); + + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY d.name, d.id"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task DestinationExistsAsync(long destinationId, CancellationToken ct = default) => + await ExecuteScalarAsync( + "SELECT COUNT(*) FROM DESTINATIONS WHERE id = :Id AND domain = 'GN' AND ROWNUM = 1", new { Id = destinationId }, ct) > 0; + + public async Task GetActiveAsync(long destinationId, DateTime date, CancellationToken ct = default) + { + var row = await QueryFirstAsync(""" + SELECT id AS Id, quota AS Quota, donequota AS DoneQuota + FROM DESTINATION_QUOTA + WHERE destinationid = :Dest AND isactive = 1 + AND quotadate >= :Day AND quotadate < :Day + 1 + ORDER BY id DESC + """, new { Dest = destinationId, Day = date.Date }, ct); + return row is null ? null : new ActiveQuota(row.Id, row.Quota, row.DoneQuota ?? 0); + } + + public Task DeactivateAsync(long destinationId, DateTime date, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE destination_quota + SET isactive = 0, updatedby = :UserId, lastupdatedate = SYSDATE + WHERE destinationid = :Dest AND isactive = 1 + AND quotadate >= :Day AND quotadate < :Day + 1 + """, new { UserId = userId, Dest = destinationId, Day = date.Date }, ct); + + public Task InsertAsync(long destinationId, DateTime date, int quota, string userId, int doneQuota, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO destination_quota (id, quotadate, destinationid, quota, createdby, donequota) + VALUES (seq_destination_quota.NEXTVAL, :Day, :Dest, :Quota, :UserId, :Done) + """, new { Day = date.Date, Dest = destinationId, Quota = quota, UserId = userId, Done = doneQuota }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/TenderOrderRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/TenderOrderRepository.cs new file mode 100644 index 0000000..3c15953 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/TenderOrderRepository.cs @@ -0,0 +1,126 @@ +using System.Data; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; +using NTP.Domain.Grains.Orders; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Orders; + +/// Dapper port of tenderOrder.cfc SQL (GRAINSTENDERORDER). Bind variables only. +internal sealed class TenderOrderRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), ITenderOrderRepository +{ + private sealed class HeaderRow + { + public string? StatusCode { get; set; } + public DateTime OrderDate { get; set; } + } + + public async Task> SearchAsync(DateTime? orderDate, PageRequest page, CancellationToken ct = default) + { + // The legacy join also pulled the STATUS table without a domain filter (it could duplicate rows and its + // description was never shown), so it is left out. + var baseSql = """ + SELECT t.id AS Id, + t.orderdate AS OrderDate, + t.mobile_shift AS MobileShift, + t.quantity AS Quantity, + t.ct AS Ct, + t.statuscode AS StatusCode, + ctp.name AS CargoType, + ld.name AS Location, + dst.name AS Destination, + t.type AS Type, + t.mobile_show AS MobileShow, + (SELECT COUNT(*) FROM permits p + WHERE p.scrn = TO_CHAR(t.id) AND p.domain = 'GN' AND p.isactive = 'Y') AS UsedQuota + FROM GRAINSTENDERORDER t, locations ld, locations dst, cargotype ctp + WHERE t.location = ld.id + AND t.destenation = dst.id + AND t.cargotype = ctp.id + AND ld.type = 'EN' + AND dst.type = 'EX' + AND dst.status = '1' + AND ld.status = '1' + AND dst.domain = 'GN' + AND ld.domain = 'GN' + AND t.statuscode <> 'DELETED' + """; + + var p = new DynamicParameters(); + var sql = baseSql; + if (orderDate.HasValue) + { + sql += " AND t.orderdate >= :OrderDate AND t.orderdate < :OrderDate + 1"; + p.Add("OrderDate", orderDate.Value.Date, DbType.DateTime); + } + + var total = await ExecuteScalarAsync(OracleSql.Count(sql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync( + OracleSql.Paginate(sql + " ORDER BY t.orderdate DESC, t.id DESC"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task InsertAsync(NewTenderOrder o, CancellationToken ct = default) + { + var p = new DynamicParameters(new + { + o.CargoType, + o.Location, + o.Destination, + OrderDate = o.OrderDate.Date, + o.Quantity, + o.MobileShift, + o.Type, + o.Ct, + CreatedBy = o.CreatedBy + }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + + await ExecuteAsync(""" + INSERT INTO GRAINSTENDERORDER + (ID, CARGOTYPE, LOCATION, DESTENATION, ORDERDATE, SHIFT, QUANTITY, STATUSCODE, CREATETIMESTAMP, CREATEUSERID, + LASTUPDATETIMESTAMP, LASTUPDATEUSERID, MOBILE_SHIFT, TYPE, CT) + VALUES + (seq_ntp_GRAINSTENDERORDER.NEXTVAL, :CargoType, :Location, :Destination, :OrderDate, 1, :Quantity, 'ACTIVE', SYSDATE, :CreatedBy, + NULL, NULL, :MobileShift, :Type, :Ct) + RETURNING ID INTO :NewId + """, p, ct); + return OracleSql.ToInt64(p.Get("NewId")); + } + + public async Task<(string? StatusCode, DateTime OrderDate)?> GetHeaderAsync(long id, CancellationToken ct = default) + { + var row = await QueryFirstAsync( + "SELECT statuscode AS StatusCode, orderdate AS OrderDate FROM GRAINSTENDERORDER WHERE id = :Id", + new { Id = id }, ct); + return row is null ? null : (row.StatusCode, row.OrderDate); + } + + public async Task HasDistributedPermitsAsync(long id, CancellationToken ct = default) + { + var count = await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM permits p + WHERE p.domain = 'GN' + AND p.scrn = TO_CHAR(:Id) + AND p.shipmentstatuscode IN ('REQST', 'PLND') + AND ROWNUM = 1 + """, new { Id = id }, ct); + return count > 0; + } + + public Task MarkDeletedAsync(long id, CancellationToken ct = default) => + ExecuteAsync("UPDATE GRAINSTENDERORDER SET statuscode = 'DELETED' WHERE id = :Id", new { Id = id }, ct); + + public Task SetMobileShowAsync(long id, bool show, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE GRAINSTENDERORDER + SET mobile_show = :Show, lastupdatetimestamp = SYSDATE, lastupdateuserid = :UserId + WHERE id = :Id + """, new { Show = OracleSql.ToNumber(show), UserId = userId, Id = id }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/WeightsAndReportsRepositories.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/WeightsAndReportsRepositories.cs new file mode 100644 index 0000000..3389e85 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Orders/WeightsAndReportsRepositories.cs @@ -0,0 +1,139 @@ +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Orders; +using NTP.Domain.Grains.Orders; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Orders; + +/// Port of grains.cfc permitAutoComplete / saveGrainsWeights SQL (GRAINS_PERMITS_WEIGHTS). +internal sealed class GrainsWeightRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IGrainsWeightRepository +{ + public Task GetPermitAsync(long pn, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT id AS Id, shipmentstatuscode AS ShipmentStatusCode, tn AS Tn, trn AS Trn, drvr AS Drvr + FROM permits + WHERE pn = :Pn + AND shipmentstatuscode IN ('CLOSE', 'RESD', 'ACTRL') + AND companycode = :Company + AND domain = 'GN' + ORDER BY id DESC + """, new { Pn = pn.ToString(), Company = GrainsOrderConstants.IndividualsScac.ToString() }, ct); + + public Task GetWeightsAsync(long permitId, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT id AS Id, empty_weight AS EmptyWeight, gross_weight AS GrossWeight, document_number AS DocumentNumber + FROM GRAINS_PERMITS_WEIGHTS + WHERE permit_id = :PermitId + ORDER BY id DESC + """, new { PermitId = permitId.ToString() }, ct); + + public Task UpdateWeightsAsync(long weightsId, string empty, string gross, string document, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE GRAINS_PERMITS_WEIGHTS + SET empty_weight = :Empty, gross_weight = :Gross, document_number = :Doc, + update_date = SYSDATE, update_by = :UserId + WHERE id = :Id + """, new { Empty = empty, Gross = gross, Doc = document, UserId = userId, Id = weightsId }, ct); + + // Positional insert exactly like legacy (the create-date/user column names are not visible in the CFC). + public Task InsertWeightsAsync(long permitId, string empty, string gross, string document, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO GRAINS_PERMITS_WEIGHTS + VALUES (seq_GRAINS_PERMITS_WEIGHTS.NEXTVAL, :Empty, :Gross, :Doc, :PermitId, SYSDATE, :UserId, NULL, NULL) + """, new { Empty = empty, Gross = gross, Doc = document, PermitId = permitId.ToString(), UserId = userId }, ct); +} + +/// Port of grains.cfc getCompDest / saveCompDest SQL (GRAINS_COMPANIES_LOCATION). +internal sealed class CompanyDestinationRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), ICompanyDestinationRepository +{ + public async Task> GetLocationIdsAsync(long scac, CancellationToken ct = default) => + await QueryAsync( + "SELECT locationid FROM GRAINS_COMPANIES_LOCATION WHERE scac = :Scac ORDER BY locationid", + new { Scac = scac.ToString() }, ct); + + public async Task ReplaceAsync(long scac, IReadOnlyCollection scopeLocationIds, IReadOnlyCollection newLocationIds, + string userId, CancellationToken ct = default) + { + if (scopeLocationIds.Count > 0) + { + await ExecuteAsync( + // No parentheses around the list: Dapper adds them when it expands the collection ("IN ((a,b))" is ORA-00907). + "DELETE FROM GRAINS_COMPANIES_LOCATION WHERE scac = :Scac AND locationid IN :Scope", + new { Scac = scac.ToString(), Scope = scopeLocationIds.Select(x => x.ToString()).ToList() }, ct); + } + + foreach (var locationId in newLocationIds) + { + // Legacy passed 5 positional values (id, scac, locationid, sysdate, userid), but the QA table has only + // ID, SCAC, LOCATIONID (docs/schema/NAFITHTCS.md, confirmed live), so the extra values are dropped. + // NVL added for an empty table. userId is intentionally unused (no audit columns exist). + await ExecuteAsync(""" + INSERT INTO GRAINS_COMPANIES_LOCATION (id, scac, locationid) + VALUES ((SELECT NVL(MAX(id), 0) + 1 FROM GRAINS_COMPANIES_LOCATION), :Scac, :LocationId) + """, new { Scac = scac.ToString(), LocationId = locationId.ToString() }, ct); + } + } +} + +/// SQL of tenderOrderReport_xls.cfm and FinancialBilling.cfm. +internal sealed class OrderReportRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IOrderReportRepository +{ + private const string BillingColumns = """ + t.id AS Id, t.cargotype AS CargoType, t.companyname AS CompanyName, t.pn AS Pn, t.tn AS Tn, + t.loaddate AS LoadDate, t.name AS Name, t.dischargedate AS DischargeDate, t.lnw AS Lnw, t.dnw AS Dnw, + t.price AS Price, t.fineprice AS FinePrice, t.serialno AS SerialNo, t.origin AS Origin, + t.finalcost AS FinalCost, t.losefine AS LoseFine, t.invoicenumber AS InvoiceNumber, t.scac AS Scac, + NVL(t.otherfine, 0) AS OtherFine, NVL(t.demurragefine, 0) AS DemurrageFine + """; + + public async Task> GetTenderTypeTotalsAsync(DateTime orderDate, CancellationToken ct = default) => + await QueryAsync(""" + SELECT t.type AS Type, SUM(t.quantity) AS Quantity + FROM GRAINSTENDERORDER t + WHERE t.ct IN ('BULK', 'BULK_GALLAB') + AND t.orderdate >= :Day AND t.orderdate < :Day + 1 + AND t.statuscode = 'ACTIVE' + GROUP BY t.type + ORDER BY t.type + """, new { Day = orderDate.Date }, ct); + + public async Task> GetTenderDestinationTotalsAsync(DateTime orderDate, CancellationToken ct = default) => + await QueryAsync(""" + SELECT getlocationname(t.destenation, 'GN') AS Destination, t.type AS Type, SUM(t.quantity) AS Quantity + FROM GRAINSTENDERORDER t + WHERE t.ct IN ('BULK', 'BULK_GALLAB') + AND t.orderdate >= :Day AND t.orderdate < :Day + 1 + AND t.statuscode = 'ACTIVE' + GROUP BY t.type, getlocationname(t.destenation, 'GN') + """, new { Day = orderDate.Date }, ct); + + public async Task> GetFinancialBillingPageAsync( + long scac, long invoiceNumber, PageRequest page, CancellationToken ct = default) + { + var baseSql = $"SELECT {BillingColumns} FROM billing1 t WHERE t.scac = :Scac AND t.invoicenumber = :Inv"; + var p = new DynamicParameters(new { Scac = scac, Inv = invoiceNumber }); + + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync( + OracleSql.Paginate(baseSql + " ORDER BY t.name, t.serialno, t.id"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public Task> GetFinancialBillingAsync(long scac, long invoiceNumber, CancellationToken ct = default) => + QueryAsync( + $"SELECT {BillingColumns} FROM billing1 t WHERE t.scac = :Scac AND t.invoicenumber = :Inv ORDER BY t.name, t.serialno, t.id", + new { Scac = scac, Inv = invoiceNumber }, ct); + + public async Task> GetInvoiceNumbersAsync(long scac, CancellationToken ct = default) => + await QueryAsync( + "SELECT DISTINCT invoicenumber FROM GRAINS_BILLING WHERE scac = :Scac AND invoicenumber IS NOT NULL ORDER BY invoicenumber DESC", + new { Scac = scac.ToString() }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DestinationRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DestinationRepository.cs new file mode 100644 index 0000000..28624e2 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DestinationRepository.cs @@ -0,0 +1,351 @@ +using System.Globalization; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Permits; +using NTP.Domain.Grains.Permits; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits; + +/// +/// Port of grains.cfc assignDestination / setDestToPermit / getOrderDates / getAllowedDestinationsByDate / getDestenation / +/// getAllowedCargo / getOrderDetails / ActivateOrder / activateOrders.cfm / getCompDest / saveCompDest / getgrainsdest / +/// savegrainsdest / getCompanies / searchDestination and the activateGrainsDestination job. +/// QA note: GRAINS_COMPANIES_LOCATION only has the columns ID, SCAC, LOCATIONID (legacy also wrote creation date / user). +/// +internal sealed class DestinationRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IDestinationRepository +{ + private const string WindowPredicate = """ + SYSDATE BETWEEN o.orderdate + DECODE(o.shift, 1, :F1, :F2) / 24 AND o.orderdate + DECODE(o.shift, 1, :L1, :L2) / 24 + """; + + private static object W(ShiftWindow w) => new { F1 = w.Shift1First, L1 = w.Shift1Last, F2 = w.Shift2First, L2 = w.Shift2Last }; + + private static DynamicParameters WindowParams(ShiftWindow w, object? extra = null) + { + var p = new DynamicParameters(W(w)); + if (extra is not null) p.AddDynamicParams(extra); + return p; + } + + // ------------------------------------------------------------------------------------------------ lookups + + public Task> GetGrainsLocationsAsync(CancellationToken ct = default) => + QueryAsync("SELECT id AS Id, name AS Name FROM LOCATIONS WHERE domain = 'GN' AND status = 1 ORDER BY sortorder, name", null, ct); + + public Task GetGrainsLocationNameAsync(string locationId, CancellationToken ct = default) => + QueryFirstAsync("SELECT MIN(name) FROM LOCATIONS WHERE domain = 'GN' AND TO_CHAR(id) = :Id", new { Id = locationId }, ct); + + public Task> GetPermitFilterDestinationsAsync(CancellationToken ct = default) => + QueryAsync("SELECT id AS Id, name AS Name FROM LOCATIONS WHERE domain = 'GN' AND type = 'EX' ORDER BY name, id", null, ct); + + public Task> GetLocationsByTypeAsync(string type, CancellationToken ct = default) => + QueryAsync("SELECT id AS Id, name AS Name FROM LOCATIONS WHERE domain = 'GN' AND status = 1 AND type = :Type ORDER BY sortorder, name", + new { Type = type }, ct); + + public Task> GetCargoTypesAsync(CancellationToken ct = default) => + QueryAsync("SELECT id AS Id, name AS Name FROM CARGOTYPE WHERE domain = 'GN' ORDER BY sortorder, name", null, ct); + + private Task> GnTypeAsync(string gnType, CancellationToken ct) => QueryAsync(""" + SELECT t.id AS Id, t.name AS Name FROM LOCATIONS t + WHERE t.domain = 'GN' AND t.status = 1 AND t.gn_type = :GnType AND t.type = 'EX' + ORDER BY t.sortorder + """, new { GnType = gnType }, ct); + + public async Task GetLocationGroupsAsync(CancellationToken ct = default) => new() + { + Packed = await GnTypeAsync("PCKD", ct), + Bulk = await GnTypeAsync("BULK", ct), + BulkGallab = await GnTypeAsync("BULK_GALLAB", ct) + }; + + public Task> GetCompaniesAsync(CancellationToken ct = default) => QueryAsync(""" + SELECT t.scac AS Scac, t.scac || '-' || getcompanynamefromscac(t.scac, 62) AS CompanyCode + FROM NTP_TENDERS_COMPANIES t + WHERE t.statuscode = 'ACTIVE' + ORDER BY DECODE(t.scac, 327, 1, t.scac) + """, null, ct); + + public Task> GetCompanyLocationsAsync(long scac, CancellationToken ct = default) => + QueryAsync("SELECT locationid FROM GRAINS_COMPANIES_LOCATION WHERE scac = :Scac ORDER BY id", new { Scac = scac }, ct); + + public Task> GetCompanyLocationItemsAsync(long scac, CancellationToken ct = default) => + QueryAsync(""" + SELECT n.locationid AS Id, l.name AS Name FROM GRAINS_COMPANIES_LOCATION n, LOCATIONS l + WHERE n.scac = :Scac AND l.id = n.locationid AND l.domain = 'GN' + """, new { Scac = scac }, ct); + + public async Task ReplaceCompanyLocationsAsync(long scac, IReadOnlyList locations, string userId, CancellationToken ct = default) + { + await ExecuteAsync("DELETE FROM GRAINS_COMPANIES_LOCATION WHERE scac = :Scac", new { Scac = scac }, ct); + foreach (var loc in locations) + await ExecuteAsync(""" + INSERT INTO GRAINS_COMPANIES_LOCATION (id, scac, locationid) + VALUES ((SELECT NVL(MAX(id), 0) + 1 FROM GRAINS_COMPANIES_LOCATION), :Scac, :Loc) + """, new { Scac = scac, Loc = loc }, ct); + } + + public async Task> GetTruckDestinationsAsync(string tn, CancellationToken ct = default) + { + var rows = await QueryAsync(""" + SELECT t.destination FROM NTP_COMPANY_DISTINATION t WHERE t.statuscode = 'ACTIVE' AND TO_CHAR(t.tn) = :Tn + """, new { Tn = tn }, ct); + return rows.SelectMany(r => (r ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + .Select(x => long.TryParse(x, out var v) ? v : (long?)null).Where(x => x.HasValue).Select(x => x!.Value).Distinct().ToList(); + } + + public Task GetLocationNameAsync(long id, CancellationToken ct = default) => + QueryFirstAsync("SELECT name FROM LOCATIONS WHERE id = :Id AND domain = 'GN'", new { Id = id }, ct); + + public Task GetCargoTypeNameAsync(long id, CancellationToken ct = default) => + QueryFirstAsync("SELECT name FROM CARGOTYPE WHERE id = :Id", new { Id = id }, ct); + + public Task> GetOrderDatesAsync(CancellationToken ct = default) => + QueryAsync("SELECT DISTINCT t.orderdate FROM GN_MANUAL_ORDER t ORDER BY t.orderdate", null, ct); + + // ------------------------------------------------------------------------------------------------ orders + + private sealed class OrderDb + { + public long Id { get; set; } + public DateTime? OrderDate { get; set; } + public long? Shift { get; set; } + public string? Ct { get; set; } + public string? Type { get; set; } + public long? Destination { get; set; } + public long? CargoType { get; set; } + public long? Location { get; set; } + } + + private const string OrderSelect = """ + SELECT o.id AS Id, o.orderdate AS OrderDate, TO_NUMBER(o.shift) AS Shift, o.ct AS Ct, o.type AS Type, + TO_NUMBER(o.destenation) AS Destination, TO_NUMBER(o.cargotype) AS CargoType, TO_NUMBER(o.location) AS Location + FROM GRAINSTENDERORDER o WHERE o.id = :Id + """; + + private static OrderForPermitRow? ToRow(OrderDb? r) => r is null ? null : new OrderForPermitRow + { + Id = r.Id, OrderDate = r.OrderDate, Shift = r.Shift, Ct = r.Ct, Type = r.Type, Destination = r.Destination, CargoType = r.CargoType, + Location = r.Location + }; + + public async Task GetOrderAsync(long orderId, CancellationToken ct = default) => + ToRow(await QueryFirstAsync(OrderSelect, new { Id = orderId }, ct)); + + public Task GetManualOrderAsync(long orderId, CancellationToken ct = default) => GetOrderAsync(orderId, ct); + + public async Task GetOrderDetailsAsync(long orderId, CancellationToken ct = default) + { + var o = await QueryFirstAsync(OrderSelect, new { Id = orderId }, ct); + if (o is null) return null; + return new OrderDetailsDto + { + CargoTypeCode = o.CargoType, + CargoType = OrderLabels.CargoGroup(o.CargoType, o.CargoType?.ToString(CultureInfo.InvariantCulture) ?? string.Empty), + Location = OrderLabels.Location(o.Location, o.Location?.ToString(CultureInfo.InvariantCulture) ?? string.Empty), + LocationCode = o.Location, + MobileShift = OrderLabels.MobileShift(await GetMobileShiftAsync(orderId, ct)), + OrderDate = o.OrderDate?.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), + Ct = o.Ct, + CtCaption = OrderLabels.OrderType(o.Ct) + }; + } + + private async Task GetMobileShiftAsync(long orderId, CancellationToken ct) => + await QueryFirstAsync("SELECT TO_NUMBER(mobile_shift) FROM GRAINSTENDERORDER WHERE id = :Id", new { Id = orderId }, ct); + + private sealed class AllowedDb + { + public long OrderId { get; set; } + public string? Name { get; set; } + public long? Dest { get; set; } + public DateTime? OrderDate { get; set; } + } + + public async Task> GetAllowedDestinationsAsync(string pn, DateTime orderDate, IReadOnlyList allowed, + bool companyBranch, bool packed, CancellationToken ct = default) + { + var comp = packed ? string.Empty : companyBranch ? " AND t.comptype = 'COMP'" : " AND t.comptype = 'AHALE'"; + var rows = await QueryAsync($""" + SELECT gg.orderid AS OrderId, gg.name AS Name, TO_NUMBER(gg.dest) AS Dest, gg.orderdate AS OrderDate FROM ( + SELECT t.destenation AS dest, t.id AS orderid, t.orderdate AS orderdate, + l.name || ' - ' || DECODE(t.ordertype, 'BULK', N'سائب', 'BULK_GALLAB', N'سائب قلاب', 'PCKD', N'مشول') || ' - ' || + DECODE(t.shift, 1, N'صباحي', 2, N'مسائي', 3, N'ليلي') AS name, + CASE WHEN getGN_HeadType(p.tn) = 'Trella' AND t.ordertype = 'BULK_GALLAB' THEN '0' ELSE '1' END AS isvalidorder + FROM GN_MANUAL_ORDER t, PERMITS p, LOCATIONS l + WHERE t.orderdate = :OrderDate{comp} + AND t.ct = p.tt AND TO_CHAR(p.pn) = :Pn AND p.domain = 'GN' AND l.id = t.destenation + AND t.destenation IN :Allowed AND l.domain = 'GN' AND p.isactive = 'Y') gg + WHERE gg.isvalidorder = '1' + """, new { OrderDate = orderDate.Date, Pn = pn, Allowed = allowed.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray() }, ct); + return rows.Select(r => new AllowedDestinationDto + { + OrderId = r.OrderId, Name = r.Name, Dest = r.Dest, OrderDate = r.OrderDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + }).ToList(); + } + + public async Task> GetAllowedCargoAsync(PermitRow permit, long badiyaScac, CancellationToken ct = default) + { + if (permit.CompanyCode == badiyaScac) + return await QueryAsync(""" + SELECT l.id AS Location, ct.id AS Ct, + (SELECT NVL(SUM(t.availablequantitiy), 0) FROM GN_NEXT_ORDER t, NTP_COMPANY_DISTINATION d + WHERE l.id = t.origin AND ct.id = t.cargotype AND d.statuscode = 'ACTIVE' AND d.domain = 'GN' + AND t.destenation = d.destination AND TO_CHAR(d.tn) = :Tn) AS Q + FROM LOCATIONS l, CARGOTYPE ct + WHERE l.domain = 'GN' AND l.status = 1 AND l.type = 'EN' AND ct.domain = 'GN' + """, new { Tn = permit.Tn }, ct); + return await QueryAsync(""" + SELECT l.id AS Location, ct.id AS Ct, + (SELECT NVL(SUM(t.availablequantitiy), 0) FROM GN_NEXT_ORDER t, GRAINS_COMPANIES_LOCATION d + WHERE l.id = t.origin AND ct.id = t.cargotype AND t.destenation = d.locationid AND d.scac = :Scac) AS Q + FROM LOCATIONS l, CARGOTYPE ct + WHERE l.domain = 'GN' AND l.status = 1 AND l.type = 'EN' AND ct.domain = 'GN' + """, new { Scac = permit.CompanyCode }, ct); + } + + public Task> GetOrdersForPermitDateAsync(string pn, DateTime orderDate, CancellationToken ct = default) => + QueryAsync(""" + WITH tt AS ( + SELECT p.pn, NVL(CASE WHEN INSTR(ct.code, '.') > 0 THEN SUBSTR(ct.code, 1, INSTR(ct.code, '.') - 1) ELSE ct.code END, '%') ctype + FROM CARGOTYPE ct, GRAINSTENDERORDER o, PERMITS p + WHERE p.domain = 'GN' AND p.scrn = TO_CHAR(o.id(+)) AND o.cargotype = TO_CHAR(ct.id(+))), + pe AS ( + SELECT MAX(e.eventdate) eventdate, p.pn + FROM EVENTS e, PERMITS p + WHERE p.domain = 'GN' AND e.eventtype = 'ASSIGNDEST' AND p.id = e.permitid + GROUP BY p.pn) + SELECT o.id AS Id, N'رقم الطلبية' || ':' || o.id || ' ' || N'نوع الحمولة' || ':' || ct.name || '/' || l.name AS DestName + FROM GRAINSTENDERORDER o, CARGOTYPE ct, LOCATIONS l, pe, tt + WHERE o.orderdate = :OrderDate AND ct.code LIKE tt.ctype || '.%' AND o.cargotype = TO_CHAR(ct.id) + AND o.destenation = TO_CHAR(l.id) AND l.domain = 'GN' AND pe.pn = tt.pn AND TO_CHAR(pe.pn) = :Pn + ORDER BY o.id + """, new { OrderDate = orderDate.Date, Pn = pn }, ct); + + // ------------------------------------------------------------------------------------------------ assignment + + public Task> GetTruckPermitsForAssignmentAsync(string tn, CancellationToken ct = default) => + QueryAsync(""" + SELECT p.id AS Id, p.tn AS Tn, p.shipmentstatuscode AS ShipmentStatusCode, p.companycode AS CompanyCode, + p.trackingno AS TrackingNo, + CASE WHEN REGEXP_LIKE(TRIM(p.scrn), '^[0-9]+$') THEN TO_NUMBER(TRIM(p.scrn)) END AS Scrn + FROM PERMITS p + WHERE p.domain = 'GN' AND p.tn = :Tn AND p.shipmentstatuscode IN ('ACCPT','RESD','ACTRL') + ORDER BY p.id DESC + """, new { Tn = tn }, ct); + + public Task GetLastAsrnAsync(string tn, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT t.asrn FROM PERMITS t WHERE t.tn = :Tn AND t.domain = 'ASEZA' AND t.shipmentmode = 'GRNS' ORDER BY t.id DESC + """, new { Tn = tn }, ct); + + public async Task> GetTenderOrderCandidatesAsync(string tn, IReadOnlyList locations, + long[]? cargoGroup, long? location, ShiftWindow window, CancellationToken ct = default) + { + var p = WindowParams(window, new { Tn = tn, Locs = locations.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray() }); + var extra = string.Empty; + if (cargoGroup is { Length: > 0 } && location is not null) + { + extra = " AND o.cargotype IN :Cargos AND o.location = :Loc"; + p.Add("Cargos", cargoGroup.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray()); + p.Add("Loc", location.Value.ToString(CultureInfo.InvariantCulture)); + } + return await QueryAsync($""" + SELECT Id, Destenation, CargoType, Quantity FROM ( + SELECT o.id AS Id, TO_NUMBER(o.destenation) AS Destenation, TO_NUMBER(o.cargotype) AS CargoType, o.quantity AS Quantity, + (SELECT COUNT(*) FROM PERMITS p WHERE p.domain = 'GN' AND p.tn = :Tn AND p.destinationaddressid = TO_NUMBER(o.destenation) + AND p.shipmentstatuscode = 'CLOSE') AS cnt, + DBMS_RANDOM.VALUE AS rnd + FROM GRAINSTENDERORDER o + WHERE o.statuscode = 'ACTIVE' AND {WindowPredicate} + AND o.destenation IN :Locs + AND o.quantity > (SELECT COUNT(*) FROM PERMITS p WHERE p.domain = 'GN' AND p.scrn = TO_CHAR(o.id)){extra} + ORDER BY cnt, rnd) + """, p, ct); + } + + public Task CountAssignedTrucksAsync(long orderId, CancellationToken ct = default) => ExecuteScalarAsync(""" + SELECT COUNT(id) FROM PERMITS p WHERE p.crn = TO_CHAR(:Id) AND p.domain = 'GN' AND p.isactive = 'Y' + """, new { Id = orderId }, ct); + + public Task SetPermitDestinationAsync(long permitId, long originId, long destinationId, long cargoType, long orderId, string userId, + CancellationToken ct = default) => ExecuteAsync(""" + UPDATE PERMITS p + SET p.originaddressid = :Origin, p.destinationaddressid = :Dest, p.shipmentmode = TO_CHAR(:Cargo), p.crn = TO_CHAR(:OrderId), + p.updatedby = :UserId, p.lastupdatedate = SYSDATE + WHERE p.id = :Id + """, new { Origin = originId, Dest = destinationId, Cargo = cargoType, OrderId = orderId, UserId = userId, Id = permitId }, ct); + + public async Task HasAssignDestEventAsync(string tn, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM PERMITS p + WHERE p.tn = :Tn AND p.domain = 'GN' AND p.shipmentstatuscode NOT IN ('CLOSE','RVKD','RJCTD') + AND EXISTS (SELECT 1 FROM EVENTS e WHERE e.eventtype = 'ASSIGNDEST' AND e.permitid = p.id AND e.domain = 'GN') + """, new { Tn = tn }, ct) > 0; + + private sealed class AssignedRow + { + public string? LocationName { get; set; } + public long? OriginAddressId { get; set; } + } + + public async Task<(string? Dest, long? Origin)> GetAssignedDestinationAsync(string tn, CancellationToken ct = default) + { + var r = await QueryFirstAsync(""" + SELECT getlocationname(t.destinationaddressid, 'GN') AS LocationName, t.originaddressid AS OriginAddressId + FROM PERMITS t + WHERE t.tn = :Tn AND t.shipmentstatuscode IN ('RESD','ACTRL') AND t.domain = 'GN' + ORDER BY t.id DESC + """, new { Tn = tn }, ct); + return (r?.LocationName, r?.OriginAddressId); + } + + public Task AssignByPnAsync(long permitId, long destId, long shipmentMode, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE PERMITS SET destinationaddressid = :Dest, originaddressid = :Dest, shipmentmode = TO_CHAR(:Cargo) WHERE id = :Id + """, new { Dest = destId, Cargo = shipmentMode, Id = permitId }, ct); + + // ------------------------------------------------------------------------------------------------ activation of today's orders + + public Task> GetActivationRowsAsync(ShiftWindow window, CancellationToken ct = default) => + QueryAsync($""" + SELECT l.id AS LocId, ct.id AS CtId, l.name AS Loc, ct.name AS Ct, + (SELECT NVL(SUM(o.quantity), 0) FROM GRAINSTENDERORDER o + WHERE {WindowPredicate} AND o.statuscode IN ('ACTIVE','INACTIVE') + AND o.location = TO_CHAR(l.id) AND o.cargotype = TO_CHAR(ct.id)) AS Total, + (SELECT COUNT(*) FROM PERMITS p, GRAINSTENDERORDER o + WHERE p.domain = 'GN' AND p.crn = TO_CHAR(o.id) AND {WindowPredicate} AND o.statuscode IN ('ACTIVE','INACTIVE') + AND o.location = TO_CHAR(l.id) AND o.cargotype = TO_CHAR(ct.id)) AS Used, + (SELECT MAX(o.statuscode) FROM GRAINSTENDERORDER o + WHERE {WindowPredicate} AND o.statuscode IN ('ACTIVE','INACTIVE') + AND o.location = TO_CHAR(l.id) AND o.cargotype = TO_CHAR(ct.id)) AS StatusCode + FROM LOCATIONS l, CARGOTYPE ct + WHERE l.domain = 'GN' AND l.type = 'EN' AND l.status = 1 AND ct.domain = 'GN' + ORDER BY 1, 2 + """, W(window), ct); + + public Task> GetCurrentWindowOrdersAsync(ShiftWindow window, CancellationToken ct = default) => + QueryAsync($""" + SELECT o.id AS Id, TO_NUMBER(o.location) AS Location, TO_NUMBER(o.cargotype) AS CargoType + FROM GRAINSTENDERORDER o + WHERE {WindowPredicate} AND o.statuscode IN ('ACTIVE','INACTIVE') + """, W(window), ct); + + public Task SetOrdersStatusAsync(IReadOnlyList ids, string status, string userId, CancellationToken ct = default) => + ids.Count == 0 ? Task.CompletedTask : ExecuteAsync(""" + UPDATE GRAINSTENDERORDER SET statuscode = :Status, lastupdatetimestamp = SYSDATE, lastupdateuserid = :UserId WHERE id IN :Ids + """, new { Status = status, UserId = userId, Ids = ids.ToArray() }, ct); + + // ------------------------------------------------------------------------------------------------ activateGrainsDestination job + + public async Task ActivatePendingCompanyDestinationsAsync(string actor, CancellationToken ct = default) + { + await ExecuteAsync(""" + UPDATE NTP_COMPANY_DISTINATION SET statuscode = 'INACTIVE', lastupdatetimestamp = SYSDATE, lastupdateuserid = :Actor + WHERE statuscode = 'ACTIVE' + AND tn IN (SELECT t.tn FROM NTP_COMPANY_DISTINATION t WHERE t.statuscode = 'PENDING' AND t.createtimestamp < SYSDATE - 3) + """, new { Actor = actor }, ct); + return await ExecuteAsync(""" + UPDATE NTP_COMPANY_DISTINATION SET statuscode = 'ACTIVE', lastupdatetimestamp = SYSDATE, lastupdateuserid = :Actor + WHERE statuscode = 'PENDING' AND createtimestamp < SYSDATE - 3 + """, new { Actor = actor }, ct); + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DistributionRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DistributionRepository.cs new file mode 100644 index 0000000..903bffa --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/DistributionRepository.cs @@ -0,0 +1,535 @@ +using System.Globalization; +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Permits; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits; + +/// +/// Port of the SQL of grains.cfc distributePackedBulk / prepareDBData / releasePermit / procssOpenPermit* / procssCompanyOpenPermit / +/// getDistributedOrderGrid / distributedOrder.cfm / searchTruckDistribution / getBLDistributedPermit, RevokeAllREQST.cfm, +/// checkForGabanEvents.cfm, GrainsDAO.getCallingDriverFile and permitsFactory.getTripCount. +/// +internal sealed class DistributionRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IDistributionRepository +{ + private const string WindowPredicate = """ + SYSDATE BETWEEN t.orderdate + DECODE(t.shift, 1, :F1, :F2) / 24 AND t.orderdate + DECODE(t.shift, 1, :L1, :L2) / 24 + """; + + private static object W(ShiftWindow w) => new { F1 = w.Shift1First, L1 = w.Shift1Last, F2 = w.Shift2First, L2 = w.Shift2Last }; + + // ------------------------------------------------------------------------------------------------ distributePackedBulk + + public async Task GetOrderTotalsAsync(string distributionCode, string queueType, bool packed, CancellationToken ct = default) + { + var sql = packed + ? "SELECT NVL(SUM(total_owners), 0) AS TotalOwners, NVL(SUM(total_comps), 0) AS TotalComps, NVL(SUM(allquantity), 0) AS AllQuantity FROM GN_TOTAL_ORDER_BY_CATEGORY t WHERE t.ct = 'PCKD'" + : "SELECT NVL(SUM(total_owners), 0) AS TotalOwners, NVL(SUM(total_comps), 0) AS TotalComps, NVL(SUM(allquantity), 0) AS AllQuantity FROM GN_TOTAL_ORDER_BY_CATEGORY t WHERE t.ct = :Code AND t.type = :Type"; + return (await QueryFirstAsync(sql, new { Code = distributionCode, Type = queueType }, ct)) ?? new OrderTotalsRow(); + } + + public async Task GetUsedOrdersAsync(string distributionCode, string queueType, bool packed, CancellationToken ct = default) + { + var sql = packed + ? "SELECT NVL(SUM(used_owners), 0) AS UsedOwners, NVL(SUM(used_comps), 0) AS UsedComps FROM GN_USED_ORDER_BY_CATEGORY t WHERE t.ct = 'PCKD'" + : "SELECT NVL(SUM(used_owners), 0) AS UsedOwners, NVL(SUM(used_comps), 0) AS UsedComps FROM GN_USED_ORDER_BY_CATEGORY t WHERE t.ct = :Code AND t.type = :Type"; + return await QueryFirstAsync(sql, new { Code = distributionCode, Type = queueType }, ct); + } + + /// prepareDBData: expire blacklist rows, reset the OPEN permits' allowed-destination counters, normalise the company destinations. + public async Task PrepareDataAsync(string cargoType, long badiyaScac, CancellationToken ct = default) + { + // pending distribution rows of blacklist entries that expire now are deleted first (the legacy read the ids before the update) + await ExecuteAsync(""" + UPDATE TRUCK_DISTRIBUTION_LOG SET statuscode = 'DELETED', updatedate = SYSDATE + WHERE blacklistid IN (SELECT id FROM GRAINSBLACKLIST t WHERE t.statuscode = 'OPEN' AND t.expirydate < SYSDATE) + AND statuscode = 'PENDING' + """, null, ct); + await ExecuteAsync(""" + UPDATE GRAINSBLACKLIST t SET statuscode = 'EXPIRED', lastupdateuser = 'SYSTEM', lastupdatedate = SYSDATE + WHERE t.statuscode = 'OPEN' AND t.expirydate < SYSDATE + """, null, ct); + + await ExecuteAsync(""" + UPDATE PERMITS p SET firms = NULL, scrn = NULL, crn = NULL, destinationaddressid = NULL + WHERE p.domain = 'GN' AND p.shipmentstatuscode = 'OPEN' AND p.creationdate > TO_DATE('01/01/2020', 'dd/mm/yyyy') + """, null, ct); + + // company destinations stored as a comma list are split into one ACTIVE row per destination + var multi = await QueryAsync(""" + SELECT id AS Id, tn AS Tn, destination AS Destination, createuserid AS CreateUserId, statuscode AS StatusCode + FROM NTP_COMPANY_DISTINATION t WHERE t.statuscode = 'ACTIVE' AND t.destination LIKE '%,%' + """, null, ct); + if (multi.Count > 0) + { + await ExecuteAsync("UPDATE NTP_COMPANY_DISTINATION SET statuscode = 'ACTIVE1' WHERE id IN :Ids", new { Ids = multi.Select(m => m.Id).ToArray() }, ct); + foreach (var m in multi) + foreach (var d in (m.Destination ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + await ExecuteAsync(""" + INSERT INTO NTP_COMPANY_DISTINATION (id, tn, statuscode, destination, createuserid, createtimestamp, domain) + VALUES (SEQ_NTP_COMPANY_DISTINATION.NEXTVAL, :Tn, :Status, :Dest, :UserName, SYSDATE, 'GN') + """, new { m.Tn, Status = m.StatusCode, Dest = d, UserName = m.CreateUserId }, ct); + } + + // duplicates of the same truck + destination keep only the newest ACTIVE row + await ExecuteAsync(""" + UPDATE NTP_COMPANY_DISTINATION SET statuscode = 'ACTIVE1' + WHERE id IN (SELECT id FROM NTP_COMPANY_DISTINATION + WHERE tn IN (SELECT tn FROM NTP_COMPANY_DISTINATION t WHERE t.statuscode = 'ACTIVE' + GROUP BY tn, t.destination HAVING COUNT(*) > 1) + AND statuscode = 'ACTIVE' + MINUS + SELECT id FROM NTP_COMPANY_DISTINATION + WHERE id IN (SELECT MAX(id) FROM NTP_COMPANY_DISTINATION t WHERE t.statuscode = 'ACTIVE' GROUP BY tn, t.destination) + AND statuscode = 'ACTIVE') + """, null, ct); + await ExecuteAsync(""" + DELETE FROM GRAINS_COMPANIES_LOCATION + WHERE id IN (SELECT id FROM GRAINS_COMPANIES_LOCATION + WHERE scac IN (SELECT scac FROM GRAINS_COMPANIES_LOCATION t GROUP BY scac, t.locationid HAVING COUNT(*) > 1) + MINUS + SELECT id FROM GRAINS_COMPANIES_LOCATION + WHERE id IN (SELECT MAX(id) FROM GRAINS_COMPANIES_LOCATION t GROUP BY scac, t.locationid)) + """, null, ct); + + await ExecuteAsync(""" + MERGE INTO PERMITS p + USING (SELECT p.id, SUM(ngo.availablequantitiy) AS allowedDestinations + FROM PERMITS p, NTP_COMPANY_DISTINATION tdest, GN_NEXT_ORDER ngo, + (SELECT entityid FROM GRAINSBLACKLIST WHERE entitytype = 'PERMIT' AND statuscode = 'OPEN') bl + WHERE p.domain = 'GN' AND TO_CHAR(p.tn) = TO_CHAR(tdest.tn) AND tdest.domain = 'GN' + AND p.creationdate > TO_DATE('01/01/2020', 'dd/mm/yyyy') AND tdest.statuscode = 'ACTIVE' + AND tdest.destination = ngo.destenation AND p.shipmentstatuscode = 'OPEN' + AND ngo.ct_old = :Tt AND ngo.ct_old = p.tt AND p.companycode = :Badiya + AND p.id = bl.entityid(+) AND bl.entityid IS NULL AND p.isactive = 'Y' + GROUP BY p.id + UNION ALL + SELECT p.id, SUM(ngo.availablequantitiy) AS allowedDestinations + FROM PERMITS p, GRAINS_COMPANIES_LOCATION tdest, GN_NEXT_ORDER ngo, + (SELECT entityid FROM GRAINSBLACKLIST WHERE entitytype = 'PERMIT' AND statuscode = 'OPEN') bl + WHERE p.domain = 'GN' AND p.companycode = tdest.scac AND p.creationdate > TO_DATE('01/01/2020', 'dd/mm/yyyy') + AND TO_CHAR(tdest.locationid) = ngo.destenation AND p.shipmentstatuscode = 'OPEN' AND p.companycode <> :Badiya + AND ngo.ct_old = :Tt AND ngo.ct_old = p.tt AND p.id = bl.entityid(+) AND p.isactive = 'Y' AND bl.entityid IS NULL + GROUP BY p.id) a + ON (p.id = a.id AND p.tt = :Tt) + WHEN MATCHED THEN UPDATE SET firms = a.allowedDestinations + """, new { Tt = cargoType, Badiya = badiyaScac }, ct); + } + + private sealed class MultiDest + { + public long Id { get; set; } + public long Tn { get; set; } + public string? Destination { get; set; } + public string? CreateUserId { get; set; } + public string? StatusCode { get; set; } + } + + public async Task> GetCompanyShareAsync(string code, string? type, bool gallabCompany, long start, long queueAvailable, + CancellationToken ct = default) + { + if (queueAvailable <= 0) return []; + var typeSql = string.IsNullOrEmpty(type) ? string.Empty : " AND t.type = :Type"; + var gallabSql = gallabCompany ? " AND c.gallab = 1" : string.Empty; + var rows = await QueryAsync($""" + WITH q AS ( + SELECT t.id, t.scac, t.counter, t.code, RANK() OVER (ORDER BY t.counter, t.id) r + FROM GRAINS_COMPANIES_QUEUE t, NTP_TENDERS_COMPANIES c + WHERE c.scac = t.scac AND c.statuscode = 'ACTIVE' AND t.code = :Code{typeSql}{gallabSql}) + SELECT COUNT(*) AS Cnt, scac AS Scac FROM q + WHERE r BETWEEN :StartRank AND :StopRank + GROUP BY scac + ORDER BY scac + """, new { Code = code, Type = type, StartRank = start, StopRank = queueAvailable + start - 1 }, ct); + return rows.Take((int)Math.Min(queueAvailable, int.MaxValue)).ToList(); + } + + public async Task> GetCompanyQueuePermitsAsync(IReadOnlyList shares, string distributionCode, + string permitCargoType, bool gallabCompany, bool bulkGallab, long badiyaScac, CancellationToken ct = default) + { + if (shares.Count == 0) return []; + var p = new DynamicParameters(); + p.Add("Dist", distributionCode); + p.Add("Ct", permitCargoType); + p.Add("Badiya", badiyaScac); + p.Add("QCode", gallabCompany ? "GALLAB" : permitCargoType); + p.Add("BlCategory", "DELAY_" + distributionCode); + + var sb = new StringBuilder("SELECT sp.id AS Id, cq.qid AS Qid, sp.scac AS Scac, TO_CHAR(sp.pn) AS Pn, sp.tn AS Tn FROM ("); + for (var i = 0; i < shares.Count; i++) + { + var s = shares[i]; + if (i > 0) sb.Append(" UNION ALL "); + p.Add($"Scac{i}", s.Scac); + p.Add($"Cnt{i}", s.Cnt); + var tripper = bulkGallab && s.Scac == badiyaScac ? " AND getgn_headtype(p.tn) = 'Tripper'" : string.Empty; + var blacklist = s.Scac != badiyaScac + ? " AND p.companycode NOT IN (SELECT entityid FROM GRAINSBLACKLIST WHERE category = :BlCategory AND statuscode = 'OPEN')" + : " AND p.id NOT IN (SELECT entityid FROM GRAINSBLACKLIST WHERE statuscode = 'OPEN' AND entityid = p.id)"; + sb.Append($""" + SELECT * FROM ( + SELECT RANK() OVER (ORDER BY p.pn) r, p.id, p.pn, p.companycode AS scac, p.tn, p.firms AS alloweddestinations + FROM PERMITS p, + (SELECT MAX(id) id, tn FROM PERMITS p2 + WHERE p2.domain = 'GN' AND p2.isactive = 'Y' AND p2.tt NOT IN (:Dist) + AND p2.shipmentstatuscode NOT IN ('OPEN','CLOSE','RVKD') GROUP BY tn) pp + WHERE p.domain = 'GN' AND p.shipmentstatuscode = 'OPEN' AND p.tn = pp.tn(+) AND pp.id IS NULL + AND p.companycode = :Scac{i} AND p.isactive = 'Y'{tripper}{blacklist} + AND p.tt = :Ct AND TO_NUMBER(p.firms) > 0) + WHERE r <= :Cnt{i} + """); + } + sb.Append(""" + ) sp, + (SELECT t.id AS qid, t.scac, t.counter, t.code, + RANK() OVER (ORDER BY t.counter, t.id) r, RANK() OVER (PARTITION BY t.scac ORDER BY t.counter, t.id) rcomp + FROM GRAINS_COMPANIES_QUEUE t WHERE t.code = :QCode) cq + WHERE cq.scac = sp.scac AND cq.rcomp = sp.r + ORDER BY TO_NUMBER(sp.alloweddestinations), DECODE(sp.scac, :Badiya, 1, 0), sp.pn + """); + return await QueryAsync(sb.ToString(), p, ct); + } + + public Task IncrementQueueCounterAsync(long queueId, CancellationToken ct = default) => + ExecuteAsync("UPDATE GRAINS_COMPANIES_QUEUE SET counter = counter + 1 WHERE id = :Id", new { Id = queueId }, ct); + + public Task IncrementCompanyQueueAsync(long scac, string code, string type, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE GRAINS_COMPANIES_QUEUE SET counter = counter + 1 WHERE id IN ( + SELECT id FROM ( + SELECT t.id, RANK() OVER (ORDER BY t.counter, t.id) r FROM GRAINS_COMPANIES_QUEUE t + WHERE scac = :Scac AND code = :Code AND type = :Type) + WHERE r = 1) + """, new { Scac = scac, Code = code, Type = type }, ct); + + public Task SetTrackingNoAsync(string pn, long queueId, CancellationToken ct = default) => ExecuteAsync( + "UPDATE PERMITS SET trackingno = :Q WHERE TO_CHAR(pn) = :Pn AND domain = 'GN'", new { Q = queueId, Pn = pn }, ct); + + public Task GetOwnerDistributionDataAsync(string tn, long badiyaScac, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT ct.name AS Name, TO_CHAR(g.orderdate, 'dd/mm/yyyy') AS OrderDate, + DECODE(g.mobile_shift, 1, N'الشفت الصباحي', 2, N'الشفت المسائي', 3, N'الشفت الليلي') AS Shift, l.name AS Location + FROM PERMITS p, GRAINSTENDERORDER g, CARGOTYPE ct, LOCATIONS l + WHERE p.domain = 'GN' AND p.shipmentstatuscode = 'REQST' AND g.id = p.scrn AND TO_CHAR(ct.id) = g.cargotype + AND TO_CHAR(l.id) = g.location AND l.domain = 'GN' AND p.companycode = :Badiya AND p.tn = :Tn + ORDER BY p.id DESC + """, new { Badiya = badiyaScac, Tn = tn }, ct); + + // ------------------------------------------------------------------------------------------------ releasePermit + + private sealed class PermitLite + { + public long Id { get; set; } + public string? Pn { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Tt { get; set; } + public string? ShipmentStatusCode { get; set; } + public long? CompanyCode { get; set; } + public long? TrackingNo { get; set; } + public long? Firms { get; set; } + public string? DrvrMobile { get; set; } + + public PermitRow ToRow() => new() + { + Id = Id, Pn = Pn, Tn = Tn, Trn = Trn, Tt = Tt, ShipmentStatusCode = ShipmentStatusCode, CompanyCode = CompanyCode, + TrackingNo = TrackingNo, Firms = Firms, DrvrMobile = DrvrMobile + }; + } + + private const string LiteSelect = """ + SELECT p.id AS Id, TO_CHAR(p.pn) AS Pn, p.tn AS Tn, p.trn AS Trn, p.tt AS Tt, p.shipmentstatuscode AS ShipmentStatusCode, + p.companycode AS CompanyCode, p.trackingno AS TrackingNo, + CASE WHEN REGEXP_LIKE(TRIM(p.firms), '^[0-9]+$') THEN TO_NUMBER(TRIM(p.firms)) END AS Firms, p.drvrmobile AS DrvrMobile + FROM PERMITS p + """; + + public async Task GetOpenPermitWithFirmsAsync(string pn, long scac, CancellationToken ct = default) => + (await QueryFirstAsync(LiteSelect + " WHERE p.domain = 'GN' AND p.shipmentstatuscode = 'OPEN' AND TO_CHAR(p.pn) = :Pn AND p.companycode = :Scac AND p.firms IS NOT NULL", + new { Pn = pn, Scac = scac }, ct))?.ToRow(); + + public async Task> GetAllowedLocationsForReleaseAsync(PermitRow permit, long scac, long badiyaScac, CancellationToken ct = default) + { + if (scac == badiyaScac) + { + var rows = await QueryAsync("SELECT t.destination FROM NTP_COMPANY_DISTINATION t WHERE TO_CHAR(t.tn) = :Tn AND t.statuscode = 'ACTIVE'", + new { Tn = permit.Tn }, ct); + return rows.SelectMany(r => (r ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + .Select(x => long.TryParse(x, out var v) ? v : (long?)null).Where(x => x.HasValue).Select(x => x!.Value).Distinct().ToList(); + } + return await QueryAsync("SELECT locationid FROM GRAINS_COMPANIES_LOCATION WHERE scac = :Scac", new { Scac = scac }, ct); + } + + public Task GetNextOrderAsync(IReadOnlyList locations, string cargoCode, string? queueType, CancellationToken ct = default) + { + var typeSql = string.IsNullOrEmpty(queueType) ? string.Empty : " AND t.type = :Type"; + return QueryFirstAsync($""" + SELECT id AS Id, TO_NUMBER(destenation) AS Destenation FROM ( + SELECT t.id, t.destenation FROM GN_NEXT_ORDER t + WHERE t.destenation IN :Locs AND t.ct = :Ct{typeSql} + ORDER BY t.rand) + WHERE ROWNUM = 1 + """, new { Locs = locations.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray(), Ct = cargoCode, Type = queueType }, ct); + } + + public Task SetRequestedWithOrderAsync(long permitId, long orderId, CancellationToken ct = default) => ExecuteAsync( + "UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST', p.scrn = TO_CHAR(:OrderRef) WHERE p.id = :Id", new { OrderRef = orderId, Id = permitId }, ct); + + public Task UpdateLastPermitAsync(long orderId, long badiyaScac, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE GRAINSTENDERORDER t + SET t.lastpermit = (SELECT MAX(id) FROM PERMITS WHERE domain = 'GN' AND scrn = TO_CHAR(t.id) AND isactive = 'Y' + AND companycode = :Badiya AND notes IS NULL) + WHERE t.id = :Id + """, new { Badiya = badiyaScac, Id = orderId }, ct); + + public Task SetLastPermitAsync(long orderId, long permitId, CancellationToken ct = default) => + ExecuteAsync("UPDATE GRAINSTENDERORDER o SET o.lastpermit = :Pid WHERE o.id = :Id", new { Pid = permitId, Id = orderId }, ct); + + public Task DeletePendingDistributionAsync(long permitId, string tn, long? orderId, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE TRUCK_DISTRIBUTION_LOG SET statuscode = 'DELETED', notes = N'إعادة توزيع', updatedate = SYSDATE + WHERE permitid = :Pid AND tn = :Tn AND (:OrderId IS NULL OR orderid = :OrderId) AND statuscode = 'PENDING' + """, new { Pid = permitId, Tn = tn, OrderId = orderId }, ct); + + public Task InsertDistributionLogAsync(long permitId, long orderId, DateTime orderDate, string tn, string notes, long? cargoType, + CancellationToken ct = default) => ExecuteAsync(""" + INSERT INTO TRUCK_DISTRIBUTION_LOG (id, permitid, orderid, orderdate, creationdate, tn, statuscode, notes, cargotype) + VALUES (SEQ_TRUCK_DISTRIBUTION_LOG.NEXTVAL, :Pid, :Oid, :OrderDate, SYSDATE, :Tn, 'PENDING', :Notes, :Cargo) + """, new { Pid = permitId, Oid = orderId, OrderDate = orderDate.Date, Tn = tn, Notes = notes, Cargo = cargoType }, ct); + + // ------------------------------------------------------------------------------------------------ procssOpenPermit* + + public async Task GetFirstOpenPermitByTnAsync(string tn, string? cargoType, CancellationToken ct = default) + { + var typeSql = string.IsNullOrEmpty(cargoType) ? string.Empty : " AND p.tt = :Tt"; + return (await QueryFirstAsync(LiteSelect + $" WHERE p.domain = 'GN' AND p.shipmentstatuscode = 'OPEN' AND p.tn = :Tn{typeSql} ORDER BY p.id", + new { Tn = tn, Tt = cargoType }, ct))?.ToRow(); + } + + public Task> GetNextOrdersForTruckAsync(string tn, CancellationToken ct = default) => + long.TryParse(tn, out var number) + ? QueryAsync(""" + WITH d AS ( + SELECT COUNT(*) cnt, p.destinationaddressid dest FROM PERMITS p + WHERE p.domain = 'GN' AND p.shipmentstatuscode = 'CLOSE' AND TO_NUMBER(p.tn) = :Tn + GROUP BY p.destinationaddressid) + SELECT t.id AS Id, TO_NUMBER(t.destenation) AS Destenation + FROM GN_NEXT_ORDER t, d + WHERE TO_NUMBER(t.destenation) = d.dest(+) AND t.id IS NOT NULL + AND TO_NUMBER(t.destenation) IN (SELECT column_value FROM TABLE(split(joinstrings(CURSOR( + SELECT c.destination FROM NTP_COMPANY_DISTINATION c WHERE c.statuscode = 'ACTIVE' AND c.tn = :Tn))))) + ORDER BY d.cnt NULLS FIRST, t.rand NULLS LAST + """, new { Tn = number }, ct) + : Task.FromResult>([]); + + public async Task IsLocationAllowedForCompanyAsync(long scac, long location, CancellationToken ct = default) => + await ExecuteScalarAsync("SELECT COUNT(*) FROM GRAINS_COMPANIES_LOCATION t WHERE t.scac = :Scac AND t.locationid = :Loc", + new { Scac = scac, Loc = location }, ct) > 0; + + public Task SetRequestedAsync(long permitId, CancellationToken ct = default) => + ExecuteAsync("UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST' WHERE p.id = :Id", new { Id = permitId }, ct); + + public async Task GetOrderForManualAsync(long orderId, CancellationToken ct = default) + { + var r = await QueryFirstAsync(""" + SELECT o.id AS Id, o.orderdate AS OrderDate, TO_NUMBER(o.shift) AS Shift, o.ct AS Ct, o.type AS Type, + TO_NUMBER(o.destenation) AS Destination, TO_NUMBER(o.cargotype) AS CargoType, TO_NUMBER(o.location) AS Location + FROM GRAINSTENDERORDER o WHERE o.id = :Id + """, new { Id = orderId }, ct); + return r; + } + + public Task PickQueueIdAsync(long scac, string code, string? type, CancellationToken ct = default) + { + var typeSql = string.IsNullOrEmpty(type) ? string.Empty : " AND t.type = :Type"; + return QueryFirstAsync($""" + SELECT id FROM ( + SELECT t.id, RANK() OVER (ORDER BY t.counter, t.id) ranking FROM GRAINS_COMPANIES_QUEUE t + WHERE t.scac = :Scac AND t.code = :Code{typeSql}) + WHERE ranking = 1 ORDER BY 1 + """, new { Scac = scac, Code = code, Type = type }, ct); + } + + public Task SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE PERMITS p SET p.shipmentstatuscode = 'REQST', p.scrn = TO_CHAR(:OrderRef), p.notes = 'MANUAL_DEST', p.trackingno = :Q WHERE p.id = :Id + """, new { OrderRef = orderId, Q = queueId, Id = permitId }, ct); + + public async Task> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default) => + (await QueryAsync(LiteSelect + " WHERE p.domain = 'GN' AND p.shipmentstatuscode = 'OPEN' AND p.companycode <> :Badiya ORDER BY p.pn", + new { Badiya = badiyaScac }, ct)).Select(r => r.ToRow()).ToList(); + + public Task GetAnyNextOrderAsync(CancellationToken ct = default) => QueryFirstAsync(""" + SELECT id AS Id, TO_NUMBER(destenation) AS Destenation FROM (SELECT t.id, t.destenation FROM GN_NEXT_ORDER t ORDER BY t.rand) WHERE ROWNUM = 1 + """, null, ct); + + // ------------------------------------------------------------------------------------------------ grids / inquiries + + public Task> GetDistributedSummaryAsync(CancellationToken ct = default) => + QueryAsync(""" + SELECT p.companycode AS CompanyCode, getcompanynamefromscac(p.companycode, 62) AS Comp, COUNT(*) AS Cnt + FROM PERMITS p WHERE p.domain = 'GN' AND p.shipmentstatuscode IN ('REQST','PLND','ACCPT') + GROUP BY p.companycode ORDER BY Cnt DESC + """, null, ct); + + public Task> GetDistributionPivotAsync(CancellationToken ct = default) => + QueryAsync(""" + SELECT companycode AS CompanyCode, company AS Company, silos AS Silos, direct AS Direct, packed AS Packed FROM ( + SELECT p.companycode, getcompanynamefromscac(p.companycode, 62) AS company, + DECODE(o.location || '-' || o.cargotype, '205-38', 1, '205-39', 1, '205-40', 2, '205-41', 2, '210-38', 3, '210-39', 3) AS ct + FROM PERMITS p, GRAINSTENDERORDER o + WHERE p.domain = 'GN' AND p.shipmentstatuscode IN ('REQST','PLND','ACCPT') AND p.scrn = TO_CHAR(o.id)) + PIVOT (COUNT(ct) FOR ct IN (1 AS silos, 3 AS direct, 2 AS packed)) + ORDER BY 3 DESC + """, null, ct); + + public async Task> GetTruckPermitStatusesAsync(string tn, CancellationToken ct = default) + { + var rows = await QueryAsync(""" + SELECT p.id AS Id, p.shipmentstatuscode AS Status, p.companycode AS Company, + CASE WHEN REGEXP_LIKE(TRIM(p.scrn), '^[0-9]+$') THEN TO_NUMBER(TRIM(p.scrn)) END AS Scrn + FROM PERMITS p, STATUS s + WHERE p.domain = 'GN' AND p.tn = :Tn AND p.shipmentstatuscode = s.code AND s.domain = 'GN' + ORDER BY p.id + """, new { Tn = tn }, ct); + return rows.Select(r => (r.Id, r.Status, r.Company, r.Scrn)).ToList(); + } + + private sealed class StatusRow + { + public long Id { get; set; } + public string? Status { get; set; } + public long? Company { get; set; } + public long? Scrn { get; set; } + } + + public Task GetTruckLatestStatusCaptionAsync(string tn, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT s.description FROM PERMITS p, STATUS s + WHERE p.domain = 'GN' AND p.tn = :Tn AND p.shipmentstatuscode = s.code AND s.domain = 'GN' ORDER BY p.id DESC + """, new { Tn = tn }, ct); + + public Task GetTruckLatestCompanyAsync(string tn, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT p.companycode FROM PERMITS p, STATUS s + WHERE p.domain = 'GN' AND p.tn = :Tn AND p.shipmentstatuscode = s.code AND s.domain = 'GN' ORDER BY p.id DESC + """, new { Tn = tn }, ct); + + public Task> GetActiveOrdersInWindowAsync(ShiftWindow window, CancellationToken ct = default) => + QueryAsync($""" + SELECT t.id AS Id, TO_NUMBER(t.destenation) AS Destenation, t.quantity AS Quantity FROM GRAINSTENDERORDER t + WHERE t.statuscode = 'ACTIVE' AND {WindowPredicate} ORDER BY t.id + """, W(window), ct); + + public async Task> GetLocationNamesAsync(IReadOnlyList ids, CancellationToken ct = default) + { + if (ids.Count == 0) return []; + var rows = await QueryAsync("SELECT id AS Id, name AS Name FROM LOCATIONS WHERE domain = 'GN' AND id IN :Ids", + new { Ids = ids.Distinct().ToArray() }, ct); + return rows.Select(r => (r.Id, r.Name)).ToList(); + } + + public Task> GetBlacklistedDistributionsAsync(string tn, CancellationToken ct = default) => + QueryAsync(""" + SELECT t.blacklistid AS BlacklistId, TO_CHAR(p.pn) || ' - ' || c.name || ' - ' || t.notes AS Text, t.cargotype AS CargoType + FROM TRUCK_DISTRIBUTION_LOG t, CARGOTYPE c, PERMITS p + WHERE t.tn = :Tn AND t.blacklistid IS NOT NULL AND t.statuscode = 'PENDING' AND c.id = t.cargotype AND t.permitid = p.id + ORDER BY t.id + """, new { Tn = tn }, ct); + + public async Task GetTripCountAsync(string tn, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + WITH con AS ( + SELECT COUNT(DISTINCT p.id) + NVL(MAX((SELECT number_of_trips FROM MOT_TN_ABROAD_TRIPS t WHERE t.tn = p.tn)), 0) tncount, p.tn + FROM PERMITS p, CARGORELEASESPERMITS crp, CARGORELEASES c + WHERE (p.shipmentmode = 'FUCON' OR (p.shipmentmode = 'BROMINE' AND p.inbondtypecode = 'IMPT')) + AND p.tn = :Tn AND p.trnat = 'jo' AND p.domain = 'ASEZA' AND p.isactive = 'Y' + AND p.destinationaddressid IN ('20','30','60') AND p.recorddate > TO_DATE('01/' || TO_CHAR(SYSDATE, 'mm/yyyy'), 'dd/mm/yyyy') + AND (c.dest_centre NOT IN (234) OR c.dest_centre IS NULL) + AND p.shipmentstatuscode IN ('RESD','ACCPT','ACTWT','ACTRL','CLRPR','CLOSE') + AND c.id = crp.crid AND p.id = crp.permitid + GROUP BY p.tn), + crg AS ( + SELECT COUNT(DISTINCT p.id) tncount, p.tn FROM PERMITS p + WHERE p.tt IN ('trucktype.general.cargo','trucktype.heavy.equipment') AND p.tn = :Tn AND p.trnat = 'jo' + AND p.domain = 'ASEZA' AND p.destinationaddressid IN ('20','30','60') + AND p.creationdate > TO_DATE('01/' || TO_CHAR(SYSDATE, 'mm/yyyy'), 'dd/mm/yyyy') + AND p.shipmentstatuscode IN ('RESD','ACCPT','ACTWT','ACTRL','CLRPR','CLOSE') + GROUP BY p.tn) + SELECT NVL((SELECT NVL(con.tncount, 0) + NVL(crg.tncount, 0) FROM con FULL OUTER JOIN crg ON con.tn = crg.tn), 0) FROM DUAL + """, new { Tn = tn }, ct); + + // ------------------------------------------------------------------------------------------------ admin / maintenance + + public async Task> GetRequestedPermitsBelowOrderAsync(long scrnBelow, long badiyaScac, CancellationToken ct = default) => + (await QueryAsync(LiteSelect + """ + WHERE p.domain = 'GN' AND p.shipmentstatuscode IN ('REQST','PLND') + AND CASE WHEN REGEXP_LIKE(TRIM(p.scrn), '^[0-9]+$') THEN TO_NUMBER(TRIM(p.scrn)) END < :Below + AND p.companycode <> :Badiya + """, new { Below = scrnBelow, Badiya = badiyaScac }, ct)).Select(r => r.ToRow()).ToList(); + + public Task ResetPermitToOpenAsync(long permitId, string userId, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE PERMITS SET shipmentstatuscode = 'OPEN', scrn = NULL, updatedby = :UserId, lastupdatedate = SYSDATE WHERE id = :Id + """, new { UserId = userId, Id = permitId }, ct); + + public Task> GetUnloadedPermitsAsync(int shiftOneFirstHour, CancellationToken ct = default) => + QueryAsync(""" + SELECT DISTINCT p.id AS Id, p.shipmentstatuscode AS ShipmentStatusCode + FROM PERMITS p, EVENTS e, GRAINSTENDERORDER o + WHERE p.id = e.permitid AND p.shipmentstatuscode IN ('REQST','ACCPT','RESD') AND p.domain = 'GN' AND e.domain = 'GN' + AND p.scrn = TO_CHAR(o.id) AND TRUNC(o.orderdate) = TRUNC(SYSDATE) - 1 + AND p.id NOT IN (SELECT ev.permitid FROM EVENTS ev + WHERE ev.eventtype = 'ASSIGNDEST' AND ev.permitid IS NOT NULL + AND ev.eventdate BETWEEN (TRUNC(SYSDATE) - 1) + :First / 24 AND TRUNC(SYSDATE) + :First / 24) + """, new { First = shiftOneFirstHour }, ct); + + public Task SetStatusOpenAsync(IReadOnlyList ids, CancellationToken ct = default) => + ids.Count == 0 ? Task.CompletedTask : ExecuteAsync("UPDATE PERMITS SET shipmentstatuscode = 'OPEN' WHERE id IN :Ids", new { Ids = ids.ToArray() }, ct); + + // ------------------------------------------------------------------------------------------------ auto call + + public Task> GetCallingDriverRowsAsync(AutoCallRequest f, DateTime? tenderDate, CancellationToken ct = default) + { + var p = new DynamicParameters(); + var sb = new StringBuilder(""" + SELECT DISTINCT t.tn AS Name, + '0' || (SELECT DISTINCT FIRST_VALUE(tn.phonenumber) OVER (ORDER BY id DESC) FROM NTP_TRUCKS tn + WHERE t.tn = tn.tn AND tn.domain = 'GN' AND tn.statuscode IN ('OPEN','ACCPT')) AS Phone, + 'C:\\' || SUBSTR(TRIM(t.tn), 1, 1) || '.wav' AS Code1, + 'C:\\' || SUBSTR(TRIM(t.tn), 2, 1) || '.wav' AS Code2, + 'C:\\' || SUBSTR(TRIM(t.tn), 3, 1) || '.wav' AS Number1, + 'C:\\' || NVL(SUBSTR(TRIM(t.tn), 4, 1), 'E') || '.wav' AS Number2, + 'C:\\' || NVL(SUBSTR(TRIM(t.tn), 5, 1), 'E') || '.wav' AS Number3, + 'C:\\' || NVL(SUBSTR(TRIM(t.tn), 6, 1), 'E') || '.wav' AS Number4, + 'C:\\' || NVL(SUBSTR(TRIM(t.tn), 7, 1), 'E') || '.wav' AS Number5, + 'C:\\GN' || o.cargotype || '.wav' AS Item, + 'C:\\GN' || '.wav' AS FromDist, + 'C:\\' || NVL(TO_CHAR(o.location), 'E') || '.wav' AS Origin, + 'C:\\d' || TRIM(TO_CHAR((o.orderdate + 1), 'D')) || '.wav' AS Week, + 'C:\\' || DECODE(SUBSTR(TRIM(TO_CHAR(o.orderdate, 'dd')), 0, 1), '0', SUBSTR(TRIM(TO_CHAR(o.orderdate, 'dd')), 2, 1), + TRIM(TO_CHAR(o.orderdate, 'dd'))) || '.wav' AS Day, + 'C:\\m' || DECODE(SUBSTR(TRIM(TO_CHAR(o.orderdate, 'mm')), 0, 1), '0', SUBSTR(TRIM(TO_CHAR(o.orderdate, 'mm')), 2, 1), + TRIM(TO_CHAR(o.orderdate, 'mm'))) || '.wav' AS Month, + t.id AS Id, TO_NUMBER(o.mobile_shift) AS MobileShift + FROM PERMITS t, GRAINSTENDERORDER o, (SELECT * FROM STATUS WHERE domain = 'GN') status, CARGOTYPE ct + WHERE o.id = t.scrn AND t.domain = 'GN' AND t.isactive = 'Y' AND o.cargotype = TO_CHAR(ct.id) + AND t.shipmentstatuscode = status.code(+) AND t.shipmentstatuscode IN ('REQST') + """); + if (tenderDate is not null) { sb.Append(" AND o.orderdate = :TenderDate"); p.Add("TenderDate", tenderDate.Value.Date, System.Data.DbType.DateTime); } + if (!string.IsNullOrWhiteSpace(f.Tn)) { sb.Append(" AND t.tn = :Tn"); p.Add("Tn", f.Tn); } else sb.Append(" AND t.tn IS NOT NULL"); + if (!string.IsNullOrWhiteSpace(f.ShipmentStatusCode)) { sb.Append(" AND t.shipmentstatuscode = :Status"); p.Add("Status", f.ShipmentStatusCode); } + if (!string.IsNullOrWhiteSpace(f.DestAddressId)) { sb.Append(" AND o.destenation = :Dest"); p.Add("Dest", f.DestAddressId); } + if (long.TryParse(f.CompanyCode, out var company)) { sb.Append(" AND t.companycode = :Company"); p.Add("Company", company); } + if (!string.IsNullOrWhiteSpace(f.ShipmentMode)) { sb.Append(" AND t.tt LIKE :ShipMode || '%'"); p.Add("ShipMode", f.ShipmentMode); } + sb.Append(""" + AND NOT EXISTS ( + SELECT id FROM ( + SELECT RANK() OVER (PARTITION BY ee.permitid ORDER BY ee.id DESC) ranking, ee.* + FROM EVENTS ee + WHERE ee.permitid IN (SELECT e.permitid FROM EVENTS e WHERE e.eventtype IN ('PHACCPT')) + AND ee.eventtype IN ('PHRJCT','PHACCPT')) + WHERE ranking = 1 AND eventtype IN ('PHACCPT') AND permitid = t.id) + """); + return QueryAsync(sb.ToString(), p, ct); + } + + public Task GetPermitIdByPnAsync(string pn, CancellationToken ct = default) => + QueryFirstAsync("SELECT id FROM PERMITS WHERE TO_CHAR(pn) = :Pn ORDER BY id", new { Pn = pn }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitRepository.cs new file mode 100644 index 0000000..e12f406 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PermitRepository.cs @@ -0,0 +1,415 @@ +using System.Data; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Permits; +using NTP.Domain.Grains.Permits; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits; + +/// +/// Port of grains.cfc getGNPermits / getGNList / getPermitInfo / getTNinfo / getTRNinfo / getDRVRinfo / submitOrder / updateOrder / +/// Accept / revoke / RevokeAcceptedOrder / getAllEvents / validatePermitReferences / deleteGnOrder / RevokeGnPermit / +/// activateGNOrder / closePermit / saveGrainsWeights / permitAutoComplete SQL. Every value is a bind variable. +/// +internal sealed class PermitRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IPermitRepository +{ + // SCRN / CRN / FIRMS are NVARCHAR2 in PERMITS; legacy compares them with numbers, so expose them safely as numbers. + private const string NumOrNull = "CASE WHEN REGEXP_LIKE(TRIM({0}), '^[0-9]+$') THEN TO_NUMBER(TRIM({0})) END"; + + private static string Num(string column) => string.Format(NumOrNull, column); + + private static readonly string PermitSelect = $""" + SELECT p.id AS Id, TO_CHAR(p.pn) AS Pn, p.tn AS Tn, p.trn AS Trn, p.nnpn AS Nnpn, p.drvr AS Drvr, p.dln AS Dln, + p.dled AS DledText, p.tt AS Tt, p.shipmentstatuscode AS ShipmentStatusCode, p.companycode AS CompanyCode, + {Num("p.scrn")} AS Scrn, {Num("p.crn")} AS Crn, p.trackingno AS TrackingNo, p.tripcounter AS TripCounter, + p.inbondtypecode AS InbondTypeCode, p.originaddressid AS OriginAddressId, p.destinationaddressid AS DestinationAddressId, + p.shipmentmode AS ShipmentMode, p.isactive AS IsActive, p.notes AS Notes, {Num("p.firms")} AS Firms, + p.drvrmobile AS DrvrMobile, p.creationdate AS CreationDate + FROM PERMITS p + """; + + private sealed class PermitDb + { + public long Id { get; set; } + public string? Pn { get; set; } + public string? Tn { get; set; } + public string? Trn { get; set; } + public string? Nnpn { get; set; } + public string? Drvr { get; set; } + public string? Dln { get; set; } + public string? DledText { get; set; } + public string? Tt { get; set; } + public string? ShipmentStatusCode { get; set; } + public long? CompanyCode { get; set; } + public long? Scrn { get; set; } + public long? Crn { get; set; } + public long? TrackingNo { get; set; } + public long? TripCounter { get; set; } + public string? InbondTypeCode { get; set; } + public long? OriginAddressId { get; set; } + public long? DestinationAddressId { get; set; } + public string? ShipmentMode { get; set; } + public string? IsActive { get; set; } + public string? Notes { get; set; } + public long? Firms { get; set; } + public string? DrvrMobile { get; set; } + public DateTime? CreationDate { get; set; } + + public PermitRow ToRow() => new() + { + Id = Id, Pn = Pn, Tn = Tn, Trn = Trn, Nnpn = Nnpn, Drvr = Drvr, Dln = Dln, Dled = PermitDates.ParseLegacy(DledText), Tt = Tt, + ShipmentStatusCode = ShipmentStatusCode, CompanyCode = CompanyCode, Scrn = Scrn, Crn = Crn, TrackingNo = TrackingNo, + TripCounter = TripCounter, InbondTypeCode = InbondTypeCode, OriginAddressId = OriginAddressId, + DestinationAddressId = DestinationAddressId, ShipmentMode = ShipmentMode, IsActive = IsActive, Notes = Notes, Firms = Firms, + DrvrMobile = DrvrMobile, CreationDate = CreationDate + }; + } + + // ------------------------------------------------------------------------------------------------ lists + + public async Task> SearchAsync(PermitSearchCriteria c, PageRequest page, CancellationToken ct = default) + { + var p = new DynamicParameters(); + var where = new System.Text.StringBuilder(""" + WHERE t.domain = 'GN' + AND t.shipmentstatuscode IN ('REQST','PLND','OPEN','ACCPT','RESD','ACTRL','CLOSE','RVKD','CLRPR') + AND t.creationdate > TO_DATE('01/01/2020', 'dd/mm/yyyy') + """); + if (c.CompanyCode is not null) { where.Append(" AND t.companycode = :CompanyCode"); p.Add("CompanyCode", c.CompanyCode.Value); } + if (!string.IsNullOrEmpty(c.Tn)) { where.Append(" AND t.tn = :Tn"); p.Add("Tn", c.Tn); } + if (!string.IsNullOrEmpty(c.Pn)) { where.Append(" AND TO_CHAR(t.pn) = :Pn"); p.Add("Pn", c.Pn); } + if (!string.IsNullOrEmpty(c.Status)) + { + where.Append(" AND t.shipmentstatuscode = :Status"); + p.Add("Status", c.Status); + if (c.Status is not ("OPEN" or "RVKD")) + // legacy joined the tender order and the cargo type for every status except OPEN / RVKD + where.Append(""" + AND EXISTS (SELECT 1 FROM grainstenderorder o, cargotype ct + WHERE TO_CHAR(o.id) = t.scrn AND o.cargotype = TO_CHAR(ct.id)) + """); + } + if (c.DestAddressId is not null) { where.Append(" AND t.destinationaddressid = :Dest"); p.Add("Dest", c.DestAddressId.Value); } + if (c.TenderOrderDate is not null) + { + where.Append(" AND t.scrn IN (SELECT TO_CHAR(x.id) FROM grainstenderorder x WHERE x.orderdate = :TenderDate)"); + p.Add("TenderDate", c.TenderOrderDate.Value.Date, DbType.DateTime); + } + if (!string.IsNullOrEmpty(c.ShipmentMode)) + { + // legacy: listgetat(t.tt, 1, '.') = value (first dot-separated element of TT) + where.Append(" AND CASE WHEN INSTR(t.tt, '.') > 0 THEN SUBSTR(t.tt, 1, INSTR(t.tt, '.') - 1) ELSE t.tt END = :ShipMode"); + p.Add("ShipMode", c.ShipmentMode); + } + if (c.CreationDate is not null) + { + where.Append(" AND TRUNC(t.creationdate) = :CreationDate"); + p.Add("CreationDate", c.CreationDate.Value.Date, DbType.DateTime); + } + var whereSql = where.ToString(); + + var baseSql = $""" + SELECT DISTINCT t.id AS Id, TO_CHAR(t.pn) AS Pn, t.tn AS Tn, t.trn AS Trn, TO_CHAR(t.trackingno) AS TrackingNo, + t.creationdate AS CreationDate, + (SELECT MIN(ll.name) FROM locations ll WHERE ll.id = t.destinationaddressid AND ll.domain = 'GN') AS DestinationName, + t.drvr AS Drvr, + getcompanynamefromscac(t.companycode, 62) AS CompName, + getstatuscaption(t.shipmentstatuscode, 'GN', NULL) AS StatusCaption, + t.shipmentstatuscode AS ShipmentStatusCode, t.companycode AS CompanyCode, + DECODE(t.companycode, 327, TO_CHAR(t.creationdate, 'dd/mm/yyyy') || '-' || t.tripcounter, NULL) AS QueueNo + FROM PERMITS t + {whereSql} + """; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY Pn, Id"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task> SearchGateListAsync(GatePermitQuery q, string domain, long? companyCode, bool restrictToCompany, + PageRequest page, CancellationToken ct = default) + { + // getGNList. NOTE: legacy joins ROUTINGLEGS/DESTINATIONS on PERMITS.CURRENTSTOP/FINALDESTINATION; those columns do not exist + // in the QA PERMITS table (see docs/schema), so the final destination is taken from DESTINATIONADDRESSID (LOCATIONS). + var p = new DynamicParameters(); + p.Add("Domain", domain); + var where = new System.Text.StringBuilder(""" + WHERE t.isactive = 'Y' AND t.domain = :Domain AND s.domain = :Domain AND s.isactive = 1 + AND t.shipmentstatuscode = s.code + """); + if (restrictToCompany) { where.Append(" AND t.companycode = :CompanyCode"); p.Add("CompanyCode", companyCode ?? -1); } + if (!string.IsNullOrEmpty(q.Tn)) { where.Append(" AND t.tn = :Tn"); p.Add("Tn", q.Tn); } + if (!string.IsNullOrEmpty(q.Trn)) { where.Append(" AND t.trn = :Trn"); p.Add("Trn", q.Trn); } + if (!string.IsNullOrEmpty(q.Pn)) { where.Append(" AND TO_CHAR(t.pn) = :Pn"); p.Add("Pn", q.Pn); } + + var baseSql = $""" + SELECT DISTINCT t.id AS Id, t.trn || '/' || t.tn || '/' || t.pn AS PermNo, t.tn AS Tn, t.drvr AS Drvr, + t.shipmentmode AS ShipmentMode, t.shipmentstatuscode AS ShipmentStatusCode, s.description AS StatusName, + t.companycode AS CompanyCode, t.createdby AS CreatedBy, + TO_CHAR(t.lastupdatedate, 'HH24:mi yyyy/mm/dd') AS LastUpdateDate, + (SELECT MIN(d.name) FROM locations d WHERE d.id = t.destinationaddressid AND d.domain = :Domain) AS FinalDestination + FROM PERMITS t, STATUS s + {where} + """; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY Id DESC"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task GetAsync(long id, CancellationToken ct = default) => + (await QueryFirstAsync(PermitSelect + " WHERE p.id = :Id AND p.domain = 'GN'", new { Id = id }, ct))?.ToRow(); + + public async Task GetByPnAsync(string pn, CancellationToken ct = default) => + (await QueryFirstAsync(PermitSelect + " WHERE TO_CHAR(p.pn) = :Pn ORDER BY p.id DESC", new { Pn = pn }, ct))?.ToRow(); + + public Task GetInfoAsync(long id, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT TO_CHAR(p.pn) AS Pn, p.tn AS Tn, p.trn AS Trn, p.nnpn AS Nnpn, p.shipmentstatuscode AS ShipmentStatusCode, p.tt AS Tt, + p.inbondtypecode AS InbondTypeCode, getcargotypename(o.cargotype, 'GN') AS CargoTypeName, + DECODE(p.companycode, 327, TO_CHAR(p.creationdate, 'dd/mm/yyyy') || '-' || p.tripcounter, NULL) AS QueueNo, + TO_NUMBER(o.mobile_shift) AS MobileShift, p.companycode AS CompanyCode, + getcompanynamefromscac(p.companycode, 62) AS CompanyName, + getstatuscaption(p.shipmentstatuscode, 'GN', NULL) AS StatusCaption, o.id AS OrderId + FROM PERMITS p, GRAINSTENDERORDER o + WHERE p.id = :Id AND p.scrn = TO_CHAR(o.id(+)) AND p.domain = 'GN' + """, new { Id = id }, ct); + + private sealed class EventDb + { + public DateTime? EventDate { get; set; } + public string? EventType { get; set; } + public string? DoneBy { get; set; } + public string? CurrentStatusCode { get; set; } + public string? CurrentStatus { get; set; } + public decimal? Weight { get; set; } + public string? Remarks { get; set; } + } + + public async Task> GetEventsAsync(long permitId, CancellationToken ct = default) + { + var rows = await QueryAsync(""" + SELECT t.eventdate AS EventDate, t.eventtype AS EventType, t.doneby AS DoneBy, t.currentstatus AS CurrentStatusCode, + getstatuscaption(t.currentstatus, 'GN', NULL) AS CurrentStatus, t.weight AS Weight, t.remarks AS Remarks + FROM EVENTS t + WHERE t.permitid = :Id + ORDER BY t.eventdate, t.id + """, new { Id = permitId }, ct); + return rows.Select(r => new PermitEventDto + { + EventDate = r.EventDate, EventType = r.EventType, EventCaption = PermitEventCaptions.Caption(r.EventType, r.CurrentStatusCode), + DoneBy = r.DoneBy, CurrentStatusCode = r.CurrentStatusCode, CurrentStatus = r.CurrentStatus, Weight = r.Weight, Remarks = r.Remarks + }).ToList(); + } + + // ------------------------------------------------------------------------------------------------ truck / trailer / driver + + public Task GetTruckInfoAsync(string tn, long? companyCode, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT t.tn AS Tn, t.chasesnumber AS ChasesNumber, t.reg_date AS RegDate, k.descreption AS Axials + FROM NTP_TRUCKS t, TRUCKKINDS k + WHERE t.tn = :Tn AND t.domain = 'GN' AND t.axials = TO_CHAR(k.id) + AND (:Company IS NULL OR t.tcscac = :Company) + AND t.statuscode NOT IN ('RVKD') + ORDER BY t.id DESC + """, new { Tn = tn, Company = companyCode }, ct); + + public Task GetTrailerInfoAsync(string trn, long? companyCode, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT t.tn AS Tn, t.chasesnumber AS ChasesNumber, t.reg_date AS RegDate, k.descreption AS Axials + FROM NTP_TRAILERS t, TRUCKKINDS k + WHERE t.tn = TRIM(:Trn) AND t.axials = TO_CHAR(k.id) AND t.domain = 'GN' + AND (:Company IS NULL OR t.tcscac = :Company) + AND t.statuscode NOT IN ('RVKD') + ORDER BY t.id DESC + """, new { Trn = trn, Company = companyCode }, ct); + + public async Task GetTrailerScacAsync(string trn, CancellationToken ct = default) => + (await QueryFirstAsync(""" + SELECT tcscac FROM NTP_TRAILERS + WHERE tn = TRIM(:Trn) AND domain = 'GN' AND statuscode IN ('OPEN','ACCPT') + ORDER BY tcscac DESC + """, new { Trn = trn }, ct)); + + public Task GetDriverInfoAsync(string nnpn, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT nnpn AS Nnpn, name AS Name, TO_CHAR(dln) AS Dln, dled AS Dled + FROM NTP_DRIVERS + WHERE nnpn = :Nnpn AND domain = 'GN' AND statuscode NOT IN ('RVKD') + ORDER BY id DESC + """, new { Nnpn = nnpn }, ct); + + public Task GetTruckRegistrationAsync(string tn, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT tcscac AS TcsCac, headtype AS HeadType, statuscode AS StatusCode + FROM NTP_TRUCKS + WHERE tn = TRIM(:Tn) AND domain = 'GN' AND statuscode IN ('OPEN','ACCPT') + ORDER BY tcscac DESC + """, new { Tn = tn }, ct); + + public async Task DriverIsRegisteredAsync(string nnpn, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM NTP_DRIVERS + WHERE nnpn = TRIM(:Nnpn) AND domain = 'GN' AND statuscode IN ('OPEN','ACCPT') + """, new { Nnpn = nnpn }, ct) > 0; + + public Task GetTruckStatusAsync(long scac, string tn, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT statuscode FROM NTP_TRUCKS + WHERE tcscac = :Scac AND tn = :Tn AND statuscode NOT IN ('RVKD') AND domain = 'GN' + ORDER BY id DESC + """, new { Scac = scac, Tn = tn }, ct); + + public Task GetTrailerStatusAsync(string trn, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT statuscode FROM NTP_TRAILERS + WHERE tn = :Trn AND statuscode NOT IN ('RVKD') AND domain = 'GN' + ORDER BY id DESC + """, new { Trn = trn }, ct); + + public Task GetDriverStatusAsync(string nnpn, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT statuscode FROM NTP_DRIVERS + WHERE nnpn = :Nnpn AND statuscode NOT IN ('RVKD') + ORDER BY id DESC + """, new { Nnpn = nnpn }, ct); + + public Task> GetMotTruckAsync(long scac, string tn, CancellationToken ct = default) => + QueryAsync(""" + SELECT TO_CHAR(t.ownershipcode) AS OwnershipCode, tt.code AS TruckTypeCode + FROM MOT_TRUCKS t, MOT_ENTITYSPECS s, MOTTRUCKTYPE tt + WHERE t.id = s.tnid AND s.specid = tt.id AND t.status = 1 AND s.status = 1 + AND t.tcscac = :Scac AND TO_CHAR(t.tn) = :Tn + """, new { Scac = scac, Tn = tn }, ct); + + public Task FindActiveConflictAsync(string column, string value, long excludePermitId, CancellationToken ct = default) + { + // column comes from the service as one of TN / TRN / NNPN; map it to a fixed fragment (never concatenate input). + var sql = column.ToUpperInvariant() switch + { + "TN" => "t.tn = :Value", + "TRN" => "t.trn = :Value", + "NNPN" => "t.nnpn = :Value", + _ => throw new ArgumentException("Unsupported column", nameof(column)) + }; + return QueryFirstAsync($""" + SELECT t.id AS Id, TO_CHAR(t.pn) AS Pn FROM PERMITS t + WHERE {sql} AND t.domain = 'GN' + AND t.shipmentstatuscode IN ('REQST','PLND','ACCPT','RESD','ACTRL') + AND t.isactive = 'Y' AND t.id <> :Id + """, new { Value = value, Id = excludePermitId }, ct); + } + + public Task GetPermitOrderAsync(long permitId, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT t.id AS Id, o.id AS Scrn, o.ct AS Ct + FROM PERMITS t, GRAINSTENDERORDER o + WHERE t.scrn = TO_CHAR(o.id) AND t.domain = 'GN' + AND t.shipmentstatuscode IN ('REQST','PLND','ACCPT','RESD','ACTRL') + AND t.isactive = 'Y' AND t.id = :Id + """, new { Id = permitId }, ct); + + // ------------------------------------------------------------------------------------------------ order lifecycle writes + + public async Task SubmitAsync(long id, SubmitOrderRequest r, DateTime? dled, string userId, CancellationToken ct = default) + { + await ExecuteAsync(""" + UPDATE PERMITS + SET nnpn = :Nnpn, tn = :Tn, trn = :Trn, shipmentstatuscode = 'PLND', cat = '6', dln = :Dln, dled = :Dled, + drvr = :Name, updatedby = :UserId, lastupdatedate = SYSDATE + WHERE id = :Id + """, new { Nnpn = r.Nnpn, Tn = r.Tn, Trn = r.Trn, Dln = r.Dln, Dled = DledText(dled, r.Dled), Name = r.Name, UserId = userId, Id = id }, ct); + await ExecuteAsync("UPDATE PERMITS SET inbondtypecode = :OpType WHERE id = :Id", new { OpType = r.OpType, Id = id }, ct); + } + + public Task UpdateOrderAsync(long id, UpdateOrderRequest r, DateTime? dled, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE PERMITS + SET nnpn = :Nnpn, tn = :Tn, trn = :Trn, dln = :Dln, dled = :Dled, drvr = :Name, updatedby = :UserId, lastupdatedate = SYSDATE + WHERE id = :Id + """, new { Nnpn = r.Nnpn, Tn = r.Tn, Trn = r.Trn, Dln = r.Dln, Dled = DledText(dled, r.Dled), Name = r.Name, UserId = userId, Id = id }, ct); + + /// Legacy stored the date text posted by the form (dd\mm\yyyy as produced by getDRVRinfo). + private static string? DledText(DateTime? parsed, string? raw) => + parsed is { } d ? d.ToString("dd'\\'MM'\\'yyyy", System.Globalization.CultureInfo.InvariantCulture) : raw; + + public Task SetStatusAsync(long id, string newStatus, string userId, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE PERMITS SET shipmentstatuscode = :Status, updatedby = :UserId, lastupdatedate = SYSDATE WHERE id = :Id + """, new { Status = newStatus, UserId = userId, Id = id }, ct); + + public Task ResetTruckValidationAsync(string tn, string userId, CancellationToken ct = default) + { + if (!long.TryParse(tn, out var number)) return Task.CompletedTask; + return ExecuteAsync(""" + UPDATE GRAINS_TRUCKS_VALIDATION SET status = 0, updatedby = :UserId, updatedtimestamp = SYSDATE + WHERE tn = :Tn AND status = 1 + """, new { UserId = userId, Tn = number }, ct); + } + + public Task ResetToOpenAsync(long id, string userId, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE PERMITS SET shipmentstatuscode = 'OPEN', scrn = NULL, updatedby = :UserId, lastupdatedate = SYSDATE, trackingno = NULL + WHERE id = :Id + """, new { UserId = userId, Id = id }, ct); + + public Task RevokeNextOpenPermitsAsync(long permitId, string userId, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE PERMITS n SET isactive = 'N', shipmentstatuscode = 'RVKD', updatedby = :UserId, lastupdatedate = SYSDATE, trackingno = NULL + WHERE n.id > :Id AND n.domain = 'GN' AND n.shipmentstatuscode = 'OPEN' + AND n.tn = (SELECT c.tn FROM PERMITS c WHERE c.id = :Id) + AND n.tt = (SELECT c.tt FROM PERMITS c WHERE c.id = :Id) + """, new { UserId = userId, Id = permitId }, ct); + + public Task FindOpenConflictForReactivationAsync(PermitRow permit, CancellationToken ct = default) => + // legacy compared NNPN with the TRN column (typo); the intent (same driver) is ported. + QueryFirstAsync(""" + SELECT t.id AS Id, TO_CHAR(t.pn) AS Pn FROM PERMITS t + WHERE t.domain = 'GN' AND t.shipmentstatuscode IN ('OPEN','REQST','PLND') AND t.tt = :Tt AND t.tn = :Tn AND t.isactive = 'Y' + AND (:Trn IS NULL OR t.trn = :Trn) AND (:Nnpn IS NULL OR t.nnpn = :Nnpn) + """, new { Tt = permit.Tt, Tn = permit.Tn, Trn = Nullable(permit.Trn), Nnpn = Nullable(permit.Nnpn) }, ct); + + private static string? Nullable(string? s) => string.IsNullOrEmpty(s) ? null : s; + + public async Task FindClosablePermitAsync(string pn, CancellationToken ct = default) => + (await QueryFirstAsync(PermitSelect + """ + WHERE p.domain = 'GN' AND TO_CHAR(p.pn) = :Pn + AND EXISTS (SELECT 1 FROM EVENTS e WHERE e.permitid = p.id AND e.eventtype = 'ASSIGNDEST') + AND p.shipmentstatuscode IN ('ACTRL','CLPRL','ACCPT','RESD','CLRPR') + ORDER BY p.id DESC + """, new { Pn = pn }, ct))?.ToRow(); + + // ------------------------------------------------------------------------------------------------ stored weights + + public async Task GetStoredWeightsAsync(string pn, long badiyaScac, CancellationToken ct = default) + { + var p = await QueryFirstAsync<(long Id, string? Tn, string? Trn, string? Drvr)>(""" + SELECT id AS Id, tn AS Tn, trn AS Trn, drvr AS Drvr FROM PERMITS + WHERE TO_CHAR(pn) = :Pn AND shipmentstatuscode IN ('CLOSE','RESD','ACTRL') AND companycode = :Scac AND domain = 'GN' + """, new { Pn = pn, Scac = badiyaScac }, ct); + if (p.Id == 0) return null; + var w = await QueryFirstAsync(""" + SELECT TO_CHAR(empty_weight) AS EmptyWeight, TO_CHAR(gross_weight) AS GrossWeight, TO_CHAR(document_number) AS DocumentNumber + FROM GRAINS_PERMITS_WEIGHTS WHERE permit_id = :Id ORDER BY id DESC + """, new { Id = p.Id }, ct) ?? new StoredWeightsDto(); + w.Tn = p.Tn; w.Trn = p.Trn; w.Drvr = p.Drvr; + return w; + } + + public async Task GetStoredWeightsIdAsync(long permitId, CancellationToken ct = default) => + await QueryFirstAsync("SELECT id FROM GRAINS_PERMITS_WEIGHTS WHERE permit_id = :Id ORDER BY id DESC", new { Id = permitId }, ct); + + public Task UpsertStoredWeightsAsync(long permitId, long? existingId, SaveWeightsRequest r, string userId, CancellationToken ct = default) => + existingId is long id + ? ExecuteAsync(""" + UPDATE GRAINS_PERMITS_WEIGHTS + SET empty_weight = :Empty, gross_weight = :Gross, document_number = :Doc, update_date = SYSDATE, update_by = :UserId + WHERE id = :Id + """, new { Empty = r.EmptyWeight.Trim(), Gross = r.GrossWeight.Trim(), Doc = r.DocumentNumber.Trim(), UserId = userId, Id = id }, ct) + : ExecuteAsync(""" + INSERT INTO GRAINS_PERMITS_WEIGHTS (id, empty_weight, gross_weight, document_number, permit_id, creation_date, created_by) + VALUES (seq_GRAINS_PERMITS_WEIGHTS.NEXTVAL, :Empty, :Gross, :Doc, :Pid, SYSDATE, :UserId) + """, new { Empty = r.EmptyWeight.Trim(), Gross = r.GrossWeight.Trim(), Doc = r.DocumentNumber.Trim(), Pid = permitId, UserId = userId }, ct); + + /// GrainsDAO.logActivation (ACTIVATIONLOG). + public Task LogActivationAsync(string type, string userId, string roleCode, string json, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO ACTIVATIONLOG (id, actiondate, type, doneby, donebyrole, activationdata) + VALUES (seq_ACTIVATIONLOG.NEXTVAL, SYSDATE, :Type, :UserId, :Role, :Json) + """, new { Type = type, UserId = userId, Role = roleCode, Json = json }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PhoneEventRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PhoneEventRepository.cs new file mode 100644 index 0000000..61d7b32 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/PhoneEventRepository.cs @@ -0,0 +1,119 @@ +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Permits; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits; + +/// Port of the SQL of grains.cfc addPhoneAcceptEvent / addPhoneRejectEvent / BL_addToBlacklist (TRUCK_DISTRIBUTION_LOG, GRAINSBLACKLIST, GRAINS_COMPANIES_QUEUE). +internal sealed class PhoneEventRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IPhoneEventRepository +{ + public async Task HasClosedDistributionAsync(long permitId, long orderId, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM TRUCK_DISTRIBUTION_LOG WHERE statuscode = 'CLOSE' AND permitid = :Pid AND orderid = :Oid + """, new { Pid = permitId, Oid = orderId }, ct) > 0; + + public Task CloseDistributionAsync(long permitId, long orderId, string notes, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE TRUCK_DISTRIBUTION_LOG SET statuscode = 'CLOSE', updatedate = SYSDATE, notes = :Notes, isblocked = 0 + WHERE permitid = :Pid AND orderid = :Oid AND statuscode = 'PENDING' + """, new { Notes = Trunc(notes, 500), Pid = permitId, Oid = orderId }, ct); + + public Task GetTruckPhoneAsync(string tn, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT TO_CHAR(phonenumber) FROM NTP_TRUCKS + WHERE tn = :Tn AND domain = 'GN' AND statuscode NOT IN ('RVKD') + ORDER BY id DESC + """, new { Tn = tn }, ct); + + public async Task InsertBlacklistAsync(NewBlacklistEntry e, string lastUpdateUser, CancellationToken ct = default) + { + var id = await ExecuteScalarAsync("SELECT SEQ_GRAINSBLACKLIST.NEXTVAL FROM DUAL", null, ct); + await ExecuteAsync(""" + INSERT INTO GRAINSBLACKLIST (id, category, entitytype, entityid, createdby, expirydate, statuscode, remarks, lastupdateuser, lastupdatedate) + VALUES (:Id, :Category, :EntityType, :EntityId, :CreatedBy, :Expiry, 'OPEN', :Remarks, :LastUser, SYSDATE) + """, new + { + Id = id, e.Category, e.EntityType, e.EntityId, e.CreatedBy, Expiry = e.ExpiryDate, Remarks = Trunc(e.Remarks, 500), + LastUser = lastUpdateUser + }, ct); + return id; + } + + public Task DecrementQueueCounterAsync(long queueId, CancellationToken ct = default) => + ExecuteAsync("UPDATE GRAINS_COMPANIES_QUEUE SET counter = counter - 1 WHERE id = :Id", new { Id = queueId }, ct); + + public async Task<(string? Code, string? Type)> GetQueueInfoAsync(long queueId, CancellationToken ct = default) + { + var r = await QueryFirstAsync("SELECT code AS Code, type AS Type FROM GRAINS_COMPANIES_QUEUE WHERE id = :Id", + new { Id = queueId }, ct); + return (r?.Code, r?.Type); + } + + private sealed class QueueInfo + { + public string? Code { get; set; } + public string? Type { get; set; } + } + + public Task DecrementCompanyBulkQueueAsync(long scac, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE GRAINS_COMPANIES_QUEUE SET counter = counter - 1 WHERE id IN ( + SELECT id FROM ( + SELECT t.id, RANK() OVER (ORDER BY t.counter DESC, t.id DESC) r + FROM GRAINS_COMPANIES_QUEUE t + WHERE scac = :Scac AND code = 'BULK' AND type = 'COMP' AND counter < 1000) + WHERE r = 1) + """, new { Scac = scac }, ct); + + public async Task GetOrderDateDiffDaysAsync(long orderId, CancellationToken ct = default) => + (double)await ExecuteScalarAsync( + // SYSDATE - date is a NUMBER with ~38 digits, more than .NET decimal holds (InvalidCastException): round to 6 decimals + "SELECT NVL((SELECT ROUND(SYSDATE - orderdate, 6) FROM GRAINSTENDERORDER WHERE id = :Id), 0) FROM DUAL", new { Id = orderId }, ct); + + public Task GetClosedDistributionAsync(long permitId, long orderId, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT id AS Id, orderdate AS OrderDate, permitid AS PermitId, cargotype AS CargoType, tn AS Tn + FROM TRUCK_DISTRIBUTION_LOG + WHERE permitid = :Pid AND statuscode = 'CLOSE' AND orderid = :Oid + ORDER BY id DESC + """, new { Pid = permitId, Oid = orderId }, ct); + + public async Task PostponeApprovedDistributionAsync(DistributionLogRow current, long permitId, long orderId, long blacklistId, string note, + CancellationToken ct = default) + { + await ExecuteAsync(""" + UPDATE TRUCK_DISTRIBUTION_LOG + SET updatedate = SYSDATE, statuscode = 'DELETED', notes = :Note, blacklistid = :Bl, isblocked = 0 + WHERE id = :Id + """, new { Note = Trunc(note, 500), Bl = blacklistId, Id = current.Id }, ct); + await ExecuteAsync(""" + INSERT INTO TRUCK_DISTRIBUTION_LOG (id, permitid, orderid, orderdate, creationdate, tn, statuscode, notes, cargotype, blacklistid) + VALUES (SEQ_TRUCK_DISTRIBUTION_LOG.NEXTVAL, :Pid, :Oid, :OrderDate, SYSDATE, :Tn, 'PENDING', :Note, :Cargo, :Bl) + """, new { Pid = permitId, Oid = orderId, OrderDate = current.OrderDate, Tn = current.Tn, Note = Trunc(note, 500), Cargo = current.CargoType, Bl = blacklistId }, ct); + } + + public Task MarkDistributionRevokedAsync(long id, long blacklistId, string note, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE TRUCK_DISTRIBUTION_LOG + SET updatedate = SYSDATE, statuscode = 'RVKD', notes = :Note, blacklistid = :Bl, isblocked = 0 + WHERE id = :Id + """, new { Note = Trunc(note, 500), Bl = blacklistId, Id = id }, ct); + + public Task MarkPendingDistributionAsync(long permitId, long blacklistId, string note, bool revoke, CancellationToken ct = default) => + revoke + ? ExecuteAsync(""" + UPDATE TRUCK_DISTRIBUTION_LOG + SET updatedate = SYSDATE, statuscode = 'RVKD', notes = :Note, blacklistid = :Bl, isblocked = 0 + WHERE permitid = :Pid AND statuscode = 'PENDING' + """, new { Note = Trunc(note, 500), Bl = blacklistId, Pid = permitId }, ct) + : ExecuteAsync(""" + UPDATE TRUCK_DISTRIBUTION_LOG + SET updatedate = SYSDATE, notes = :Note, blacklistid = :Bl, isblocked = 0 + WHERE permitid = :Pid AND statuscode = 'PENDING' + """, new { Note = Trunc(note, 500), Bl = blacklistId, Pid = permitId }, ct); + + public async Task HasPhoneEventTodayAsync(long permitId, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM EVENTS + WHERE eventtype IN ('PHRJCT','PHACCPT') AND permitid = :Pid AND TRUNC(eventdate) = TRUNC(SYSDATE) + """, new { Pid = permitId }, ct) > 0; + + private static string Trunc(string s, int max) => s.Length <= max ? s : s[..max]; +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/QueueRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/QueueRepository.cs new file mode 100644 index 0000000..f5fb61e --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/QueueRepository.cs @@ -0,0 +1,259 @@ +using System.Data; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Permits; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits; + +/// +/// Port of grains.cfc getGNQueueList / AddToQueue (ws.cfc createPermitRecord) / getTrailerNumber / checkTrucks / getGNFormData / +/// updateGNForm / getRoutingTemplate / getORIGINADDRESS / insertPermitStop / getDestination / getCANInfo / checkWSError and the +/// parseGrainsPermits job queries. +/// QA schema gaps (docs/schema, verified against the DB): PERMITS has no FINALDESTINATION column and the tables DESTINATIONS, +/// DESTINATION_QUOTA and PERMITSTOPS do not exist, so the TCS permit (createPermit.cfm) statements that use them cannot run on QA. +/// +internal sealed class QueueRepository(IDbSession session, INtpDbSession ntpSession, ILogger logger) + : OracleRepositoryBase(session, logger), IQueueRepository +{ + /// CLEARING_AGENTS and PETROLEUMERRORMSG belong to the NTP schema (legacy queries without a datasource use the default NTP one). + private sealed class NtpAccess(INtpDbSession s, ILogger l) : NtpRepositoryBase(s, l) + { + public Task FirstAsync(string sql, object? p, CancellationToken ct) => QueryFirstAsync(sql, p, ct); + public Task> ListAsync(string sql, object? p, CancellationToken ct) => QueryAsync(sql, p, ct); + } + + private readonly NtpAccess _ntp = new(ntpSession, logger); + + public async Task> ListAsync(QueueSearchQuery q, PageRequest page, CancellationToken ct = default) + { + var p = new DynamicParameters(); + var where = new System.Text.StringBuilder(" WHERE t.shipmentstatuscode = 'QUED'"); + if (!string.IsNullOrEmpty(q.Tn)) { where.Append(" AND t.tn = :Tn"); p.Add("Tn", q.Tn); } + if (!string.IsNullOrEmpty(q.Pn)) { where.Append(" AND TO_CHAR(t.pn) = :Pn"); p.Add("Pn", q.Pn); } + var baseSql = "SELECT t.id AS Id, t.tn AS Tn, TO_CHAR(t.pn) AS Pn, t.creationdate AS CreationDate FROM PERMITS t" + where; + + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY CreationDate, Pn, Id"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public Task GetActiveTruckScacAsync(string tn, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT t.tcscac FROM NTP_TRUCKS t + WHERE t.tn = :Tn AND t.domain = 'GN' AND t.statuscode IN ('OPEN','ACCPT') + ORDER BY t.id DESC + """, new { Tn = tn }, ct); + + public async Task HasActivePermitAsync(string tn, string tt, bool includeRequestedPlanned, CancellationToken ct = default) + { + var sql = includeRequestedPlanned + ? "SELECT COUNT(*) FROM PERMITS t WHERE t.tn = :Tn AND t.shipmentstatuscode IN ('REQST','PLND','OPEN') AND t.domain = 'GN' AND t.tt = :Tt AND ROWNUM = 1" + : "SELECT COUNT(*) FROM PERMITS t WHERE t.tn = :Tn AND t.shipmentstatuscode IN ('OPEN') AND t.domain = 'GN' AND t.tt = :Tt AND ROWNUM = 1"; + return await ExecuteScalarAsync(sql, new { Tn = tn, Tt = tt }, ct) > 0; + } + + public Task NextTrackingSequenceAsync(bool owner, CancellationToken ct = default) => ExecuteScalarAsync( + owner ? "SELECT SEQ_GRAINS_TRACKINGNO_OWN.NEXTVAL FROM DUAL" : "SELECT SEQ_GRAINS_TRACKINGNO_CO.NEXTVAL FROM DUAL", null, ct); + + public Task NextTripCounterAsync(string tt, long badiyaScac, CancellationToken ct = default) => ExecuteScalarAsync(""" + SELECT NVL(MAX(tripcounter), 0) + 1 FROM PERMITS p + WHERE domain = 'GN' AND tt = :Tt AND creationdate > TRUNC(SYSDATE) AND p.companycode = :Scac + """, new { Tt = tt, Scac = badiyaScac }, ct); + + public Task GetTenderCountAsync(CancellationToken ct = default) => + ExecuteScalarAsync("SELECT NVL(MAX(id), 0) FROM NTP_TENDER t WHERE domain = 'GN'", null, ct); + + public async Task InsertPermitAsync(string pn, string? tn, long scac, string status, string tt, long? tripCounter, CancellationToken ct = default) + { + var d = new DynamicParameters(new { Pn = pn, Tn = tn, CompanyCode = scac, StatusCode = status, Tt = tt, TripCounter = tripCounter }); + d.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + await ExecuteAsync(""" + INSERT INTO PERMITS (id, pn, tn, companycode, shipmentstatuscode, domain, tt, tripcounter) + VALUES (SEQ_PERMITS.NEXTVAL, TO_NUMBER(:Pn), :Tn, :CompanyCode, :StatusCode, 'GN', :Tt, :TripCounter) + RETURNING id INTO :NewId + """, d, ct); + return OracleSql.ToInt64(d.Get("NewId")); + } + + public Task GetTrailerNumberAsync(string tn, string[] allowedStatuses, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT tr.tn FROM NTP_TRAILERS tr + WHERE tr.tn_id IN (SELECT id FROM NTP_TRUCKS WHERE tn = :Tn AND domain = 'GN' AND statuscode IN :Statuses) + ORDER BY tr.id DESC + """, new { Tn = tn, Statuses = allowedStatuses }, ct); + + // ------------------------------------------------------------------------------------------------ fleet turn check + + public Task CountFleetAsync(long scac, CancellationToken ct = default) => ExecuteScalarAsync(""" + SELECT COUNT(p.id) FROM NTP_TRUCKS p WHERE p.domain = 'GN' AND p.statuscode IN ('OPEN','ACCPT') AND p.tcscac = :Scac + """, new { Scac = scac }, ct); + + public Task CountActiveValidationsAsync(long scac, CancellationToken ct = default) => ExecuteScalarAsync( + "SELECT COUNT(id) FROM GRAINS_TRUCKS_VALIDATION WHERE scac = :Scac AND status = 1", new { Scac = scac }, ct); + + public async Task ValidationExistsAsync(long scac, long tn, CancellationToken ct = default) => + await ExecuteScalarAsync("SELECT COUNT(*) FROM GRAINS_TRUCKS_VALIDATION WHERE tn = :Tn AND status = 1 AND scac = :Scac", + new { Tn = tn, Scac = scac }, ct) > 0; + + public Task InsertValidationAsync(long scac, long tn, string userId, CancellationToken ct = default) => ExecuteAsync(""" + INSERT INTO GRAINS_TRUCKS_VALIDATION (id, scac, tn, status, createdby) + VALUES (SEQ_GRAINS_TRUCKS_VALIDATION.NEXTVAL, :Scac, :Tn, 1, :UserId) + """, new { Scac = scac, Tn = tn, UserId = userId }, ct); + + public Task ClearValidationsAsync(long scac, CancellationToken ct = default) => + ExecuteAsync("UPDATE GRAINS_TRUCKS_VALIDATION SET status = 0 WHERE status = 1 AND scac = :Scac", new { Scac = scac }, ct); + + // ------------------------------------------------------------------------------------------------ seeding of OPEN permits (parseGrainsPermits) + + public Task> GetCompanyQueueSharesAsync(string code, long excludeScac, CancellationToken ct = default) => + QueryAsync(""" + SELECT t.scac AS Scac, COUNT(t.id) AS CompanyShare + FROM GRAINS_COMPANIES_QUEUE t + WHERE t.code = :Code AND t.scac != :Scac + GROUP BY t.scac + ORDER BY t.scac + """, new { Code = code, Scac = excludeScac }, ct); + + public Task CountOpenPermitsAsync(long scac, string tt, CancellationToken ct = default) => ExecuteScalarAsync(""" + SELECT COUNT(*) FROM PERMITS t + WHERE t.domain = 'GN' AND t.shipmentstatuscode = 'OPEN' AND t.companycode = :Scac AND t.tt = :Tt + """, new { Scac = scac, Tt = tt }, ct); + + // ------------------------------------------------------------------------------------------------ TCS permit (createPermit.cfm) + + public Task PickRandomQuotaDestinationAsync(CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT id AS DestId, name AS DestName FROM ( + SELECT d.id, d.name FROM DESTINATIONS d, DESTINATION_QUOTA q + WHERE d.domain = 'GN' AND d.id = q.destinationid AND q.isactive = 1 + AND TRUNC(q.quotadate) = TRUNC(SYSDATE) AND q.quota - q.donequota > 0 + ORDER BY DBMS_RANDOM.VALUE) + WHERE ROWNUM = 1 + """, null, ct); + + private sealed class FormDb + { + public string? Tn { get; set; } + public string? TrnAt { get; set; } + public string? Trn { get; set; } + public string? Tt { get; set; } + public string? Drvr { get; set; } + public string? Cat { get; set; } + public string? Dln { get; set; } + public string? DledText { get; set; } + public string? Nat { get; set; } + public string? Nnpn { get; set; } + public long? RoutingTemplateId { get; set; } + public long? OriginAddressId { get; set; } + public long? DestinationAddressId { get; set; } + public string? Firms { get; set; } + public string? Asrn { get; set; } + public string? Can { get; set; } + public string? CanName { get; set; } + } + + public async Task GetFormDataAsync(long permitId, string domain, CancellationToken ct = default) + { + // getGNFormData: TN of the QUED permit, then getTruckInfo = the truck's latest permit whose status is non-active. + var tn = await QueryFirstAsync("SELECT tn FROM PERMITS WHERE id = :Id", new { Id = permitId }, ct); + if (string.IsNullOrEmpty(tn)) return null; + var r = await QueryFirstAsync(""" + SELECT p.trnat AS TrnAt, p.trn AS Trn, p.tt AS Tt, p.drvr AS Drvr, p.cat AS Cat, p.dln AS Dln, p.dled AS DledText, + p.nat AS Nat, p.nnpn AS Nnpn, p.routingtemplateid AS RoutingTemplateId, p.originaddressid AS OriginAddressId, + p.destinationaddressid AS DestinationAddressId, p.firms AS Firms, p.asrn AS Asrn, TO_CHAR(p.can) AS Can, + NULL AS CanName + FROM PERMITS p + WHERE p.tn = :Tn + AND p.shipmentstatuscode IN (SELECT code FROM STATUS WHERE isactive = 0 AND domain = :Domain) + ORDER BY p.id DESC + """, new { Tn = tn, Domain = domain }, ct); + var canName = long.TryParse(r?.Can, out var canId) ? await GetClearingAgentNameAsync(canId, ct) : null; + return new TcsFormDataDto + { + Tn = tn, TrnAt = r?.TrnAt, Trn = r?.Trn, Tt = r?.Tt, Drvr = r?.Drvr, Cat = r?.Cat, Dln = r?.Dln, + Dled = PermitDates.ParseLegacy(r?.DledText), Nat = r?.Nat, Nnpn = r?.Nnpn, RoutingTemplateId = r?.RoutingTemplateId, + OriginAddressId = r?.OriginAddressId, DestinationAddressId = r?.DestinationAddressId, Firms = r?.Firms, Asrn = r?.Asrn, + Can = r?.Can, CanName = canName + }; + } + + public Task> GetRoutingTemplatesAsync(long origin, long destination, string shipmentMode, string firms, + string domain, CancellationToken ct = default) => QueryAsync(""" + SELECT t.id AS Id, routdetails(t.id, :Domain) AS RouteName + FROM ROUTING t + WHERE t.orgaddressid = :Origin AND t.destaddressid = :Dest AND t.shipmentmode = :ShipMode AND t.defaultlane = :Firms + AND t.domain = :Domain + ORDER BY t.disporder + """, new { Origin = origin, Dest = destination, ShipMode = shipmentMode, Firms = firms, Domain = domain }, ct); + + public Task> GetOriginAddressesAsync(long routing, string domain, CancellationToken ct = default) => + routing > 0 + ? QueryAsync(""" + SELECT l.id AS Id, l.name AS Name FROM ROUTING r, LOCATIONS l + WHERE r.domain = 'PH' AND l.domain = :Domain AND r.destaddressid = l.id AND r.id = :Routing + """, new { Domain = domain, Routing = routing }, ct) + : QueryAsync("SELECT l.id AS Id, l.name AS Name FROM LOCATIONS l WHERE l.domain = :Domain AND l.type = 'EN' ORDER BY l.name", + new { Domain = domain }, ct); + + public Task> GetPhRoutesAsync(CancellationToken ct = default) => QueryAsync(""" + SELECT r.id AS Id, routdetails(r.id, 'PH') AS RouteName FROM ROUTING r WHERE r.domain = 'PH' ORDER BY r.disporder + """, null, ct); + + public Task GetPhRouteAsync(long routing, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT r.orgaddressid AS OrgAddressId, r.destaddressid AS DestAddressId, r.defaultlane AS DefaultLane + FROM ROUTING r WHERE r.id = :Id AND r.domain = 'PH' + """, new { Id = routing }, ct); + + public Task GetClearingAgentNameAsync(long can, CancellationToken ct = default) => + _ntp.FirstAsync("SELECT name FROM CLEARING_AGENTS WHERE id = TO_CHAR(:Id) AND ROWNUM = 1", new { Id = can }, ct); + + public async Task GetPetroleumErrorTextAsync(IReadOnlyList codes, CancellationToken ct = default) + { + if (codes.Count == 0) return string.Empty; + var rows = await _ntp.ListAsync("SELECT description FROM PETROLEUMERRORMSG WHERE langid = 0 AND code IN :Codes", + new { Codes = codes.ToArray() }, ct); + return string.Join("
", rows).Trim(); + } + + public Task UpdateTcsPermitAsync(long permitId, TcsPermitUpdate u, CancellationToken ct = default) + { + var f = u.Form; + // FINALDESTINATION is not a column of the QA PERMITS table (see class remarks) and HEADREGTYPE / TRAILREGTYPE come from the + // waybill web service (ws.getHeadInfo / getTrailInfo), which is not part of this repository; both are left out. + return ExecuteAsync(""" + UPDATE PERMITS + SET tn = :Tn, trnat = :TrnAt, trn = :Trn, tt = :Tt, asrn = :Asrn, can = :Can, nnpn = :Nnpn, drvr = :Drvr, dln = :Dln, + cat = :Cat, dled = :Dled, nat = :Nat, shipmentmode = :ShipMode, inbondtypecode = :Inbond, firms = :Firms, + originaddressid = :Origin, destinationaddressid = :Dest, routingtemplateid = :Template, + pn = TO_NUMBER(:Pn), shipmentstatuscode = :Status, companycode = :Company, updatedby = :UserId, lastupdatedate = SYSDATE + WHERE id = :Id + """, new + { + f.Tn, f.TrnAt, f.Trn, f.Tt, f.Asrn, Can = long.TryParse(f.Can, out var can) ? can : (long?)null, f.Nnpn, f.Drvr, f.Dln, f.Cat, + Dled = f.Dled, f.Nat, ShipMode = f.ShipmentMode, Inbond = f.InbondTypeCode, f.Firms, Origin = f.OriginAddressId, + Dest = f.DestinationAddressId, Template = f.RoutingTemplateId, Pn = u.Pn, Status = u.StatusCode, Company = u.CompanyCode, + UserId = u.UserId, Id = permitId + }, ct); + } + + public Task GetPermitCreationDateAsync(long permitId, CancellationToken ct = default) => + QueryFirstAsync("SELECT creationdate FROM PERMITS WHERE id = :Id", new { Id = permitId }, ct); + + public Task> GetRoutingLegsAsync(long routeId, CancellationToken ct = default) => + QueryAsync("SELECT locationid AS LocationId, sortorder AS SortOrder FROM ROUTINGLEGS WHERE routeid = :Id ORDER BY sortorder", + new { Id = routeId }, ct); + + public Task InsertPermitStopAsync(long permitId, string domain, long? orgId, long destId, long sortOrder, DateTime? orgDepartDate, + CancellationToken ct = default) => ExecuteAsync(""" + INSERT INTO PERMITSTOPS (id, permitid, domain, orgid, destid, orgdepartdate, sortorder) + VALUES (SEQ_PERMITSTOPS.NEXTVAL, :PermitId, :Domain, :OrgId, :DestId, :Depart, :Sort) + """, new { PermitId = permitId, Domain = domain, OrgId = orgId, DestId = destId, Depart = orgDepartDate, Sort = sortOrder }, ct); + + public Task IncrementDoneQuotaAsync(long destinationId, CancellationToken ct = default) => ExecuteAsync(""" + UPDATE DESTINATION_QUOTA SET donequota = donequota + 1 + WHERE destinationid = :Dest AND isactive = 1 AND TRUNC(quotadate) = TRUNC(SYSDATE) + """, new { Dest = destinationId }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/WeighbridgeRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/WeighbridgeRepository.cs new file mode 100644 index 0000000..d5ebeec --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Permits/WeighbridgeRepository.cs @@ -0,0 +1,247 @@ +using System.Globalization; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Permits; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Permits; + +/// +/// SQL of grains.cfc getTruckInfoFromTN / EN_WeightBridge / EX_WeightBridge / getTruckWaybridgeEvent / getlocTruckNum and of the +/// jobs getWeighbridgeEvents.cfm / getAqabaWeighbridgeEvents.cfm (WEIGHBRIDGE_RAW_DATA). +/// +internal sealed class WeighbridgeRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IWeighbridgeRepository +{ + public Task GetPermitByTruckAndStatusAsync(string tn, string status, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT id AS Id, drvr AS Drvr, tn AS Tn, TO_CHAR(pn) AS Pn, shipmentstatuscode AS ShipmentStatusCode + FROM PERMITS WHERE tn = :Tn AND shipmentstatuscode = :Status AND domain = 'GN' ORDER BY id DESC + """, new { Tn = tn, Status = status }, ct); + + public Task GetLatestLoadingTareAsync(long permitId, CancellationToken ct = default) => QueryFirstAsync(""" + SELECT t.weight FROM EVENTS t + WHERE t.prevstatus = 'RESD' AND t.domain = 'GN' AND t.permitid = :Pid AND t.eventtype = 'LTW' + AND t.eventdate = (SELECT MAX(e.eventdate) FROM EVENTS e WHERE e.permitid = :Pid AND e.domain = 'GN' AND e.eventtype = 'LTW') + ORDER BY t.id DESC + """, new { Pid = permitId }, ct); + + public Task GetWeighbridgePermitAsync(string tn, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT p.id AS Id, p.shipmentstatuscode AS ShipmentStatusCode, NVL(p.originaddressid, TO_NUMBER(o.location)) AS OriginAddressId, + p.destinationaddressid AS DestinationAddressId + FROM PERMITS p, GRAINSTENDERORDER o + WHERE p.domain = 'GN' AND p.scrn = TO_CHAR(o.id(+)) AND p.tn = :Tn AND p.shipmentstatuscode IN ('ACCPT','RESD','ACTRL','CLRPR') + ORDER BY p.id DESC + """, new { Tn = tn }, ct); + + public Task InsertEventAsync(WeighbridgeEventInsert e, CancellationToken ct = default) => ExecuteAsync(""" + INSERT INTO EVENTS (id, permitid, eventdate, eventtype, prevstatus, currentstatus, doneby, locationid, domain, updatedtype, remarks, weight) + VALUES (SEQ_EVENTS.NEXTVAL, :PermitId, :EventDate, :EventType, :Prev, :Curr, :DoneBy, :LocationId, 'GN', :UpdatedType, NULL, :Weight) + """, new { e.PermitId, e.EventDate, e.EventType, Prev = e.PrevStatus, Curr = e.CurrentStatus, e.DoneBy, e.LocationId, e.UpdatedType, e.Weight }, ct); + + public Task UpdateStatusByTruckAsync(string tn, string[] fromStatuses, string newStatus, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE PERMITS SET shipmentstatuscode = :New, updatedby = :UserId, lastupdatedate = SYSDATE + WHERE tn = :Tn AND domain = 'GN' AND shipmentstatuscode IN :FromStatuses + """, new { New = newStatus, UserId = userId, Tn = tn, FromStatuses = fromStatuses }, ct); + + public Task LogIntegrationCallAsync(string ipAddress, string tn, string argsJson, CancellationToken ct = default) => ExecuteAsync(""" + INSERT INTO GN_TCS_INTEGRATION (id, ipaddress, tn, eventdate, args) VALUES (seq_GN_TCS_INTEGRATION.NEXTVAL, :Ip, :Tn, SYSDATE, :Args) + """, new { Ip = ipAddress, Tn = tn, Args = argsJson }, ct); + + public Task GetLocationTypeAsync(long locationId, string domain, CancellationToken ct = default) => + QueryFirstAsync("SELECT type FROM LOCATIONS WHERE domain = :Domain AND id = :Id AND status = 1", new { Domain = domain, Id = locationId }, ct); + + public async Task GetWaybridgeEventAsync(string tn, string? locationType, CancellationToken ct = default) + { + var permitId = await QueryFirstAsync(""" + SELECT id FROM PERMITS WHERE domain = 'GN' AND tn = :Tn AND shipmentstatuscode IN ('ACCPT','RESD','ACTRL','CLPRL','CLRPR') ORDER BY id DESC + """, new { Tn = tn }, ct); + if (permitId is null) return null; + var filter = locationType switch + { + "EN" => " AND e.eventtype = 'LTW' AND p.shipmentstatuscode IN ('ACCPT','RESD')", + "EX" => " AND e.eventtype = 'DTW' AND p.shipmentstatuscode IN ('ACTRL','CLPRL','CLRPR')", + _ => string.Empty + }; + var weight = await QueryFirstAsync($""" + SELECT e.weight FROM EVENTS e, PERMITS p WHERE e.permitid = :Pid AND p.id = e.permitid{filter} ORDER BY e.eventdate DESC + """, new { Pid = permitId }, ct); + return new WaybridgeEventDto { Tn = tn, Weight = weight }; + } + + public Task> GetLocationTruckCountsAsync(CancellationToken ct = default) => + QueryAsync(""" + SELECT NVL((SELECT MIN(name) FROM LOCATIONS WHERE id = t.destinationaddressid AND domain = 'GN'), N'مواقع التحميل') AS Loc, COUNT(*) AS Cnt + FROM PERMITS t WHERE t.domain = 'GN' AND t.shipmentstatuscode IN ('ACTRL','ACCPT','RESD') + GROUP BY t.shipmentstatuscode, t.destinationaddressid ORDER BY 2 DESC + """, null, ct); + + // ------------------------------------------------------------------------------------------------ raw data (jobs) + + private sealed class LastRaw + { + public long LocationId { get; set; } + public DateTime? TimeOut { get; set; } + } + + public async Task> GetLastRawTimesAsync(long[] locationIds, CancellationToken ct = default) + { + var rows = await QueryAsync(""" + SELECT locationid AS LocationId, MAX(cargo_time_out) AS TimeOut FROM WEIGHBRIDGE_RAW_DATA WHERE locationid IN :Ids GROUP BY locationid + """, new { Ids = locationIds }, ct); + return rows.ToDictionary(r => r.LocationId, r => r.TimeOut); + } + + public Task InsertRawRowAsync(ExternalCargoRow r, string normalizedTruckNo, CancellationToken ct = default) => ExecuteAsync(""" + INSERT INTO WEIGHBRIDGE_RAW_DATA (locationid, cargo_key, cargo_state, cargo_time_in, cargo_weight_in, cargo_time_out, cargo_weight_out, + cargo_weight_net, cargo_type, cargo_type_txt, cargo_driver_name, cargo_truck_no, cargo_source, permitid) + VALUES (:LocationId, :Key, :State, :TimeIn, :WeightIn, :TimeOut, :WeightOut, :WeightNet, :CType, :CTypeTxt, :Driver, :TruckNo, :Source, NULL) + """, new + { + r.LocationId, Key = r.CargoKey, State = r.CargoState, TimeIn = r.CargoTimeIn, WeightIn = r.CargoWeightIn, TimeOut = r.CargoTimeOut, + WeightOut = r.CargoWeightOut, WeightNet = r.CargoWeightNet, CType = r.CargoType, CTypeTxt = r.CargoTypeTxt, Driver = r.CargoDriverName, + TruckNo = normalizedTruckNo, Source = r.CargoSource + }, ct); + + public Task> GetUnprocessedRawRowsAsync(bool aqaba, CancellationToken ct = default) + { + var filter = aqaba ? "t.cargo_weight_net < 0 AND t.locationid = 205" : "t.cargo_weight_net > 0 AND t.locationid <> 205"; + var order = aqaba ? "t.cargo_time_out" : "t.cargo_time_out DESC"; + return QueryAsync($""" + SELECT ROWIDTOCHAR(t.rowid) AS "RowId", t.locationid AS LocationId, t.cargo_truck_no AS CargoTruckNo, t.cargo_weight_in AS CargoWeightIn, + t.cargo_weight_out AS CargoWeightOut, t.cargo_weight_net AS CargoWeightNet, + TO_CHAR(t.cargo_time_in, 'yyyymmddHH24miss') AS GinTime, TO_CHAR(t.cargo_time_out, 'yyyymmddHH24miss') AS GoutTime + FROM WEIGHBRIDGE_RAW_DATA t WHERE t.permitid IS NULL AND {filter} ORDER BY {order} + """, null, ct); + } + + public Task FindPermitForRawAsync(string tn, string[] statuses, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT id AS Id, shipmentstatuscode AS ShipmentStatusCode FROM PERMITS t + WHERE t.tn = :Tn AND domain = 'GN' AND t.shipmentstatuscode IN :Statuses ORDER BY id DESC + """, new { Tn = tn, Statuses = statuses }, ct); + + /// getPermitNumber (job-local function): the permit whose ASSIGNDEST period covers the weighbridge entry time + 2h. + public Task FindPermitByAssignedDestinationAsync(string tn, string ginTime, string tt, string[] excludedEventTypes, + CancellationToken ct = default) => QueryFirstAsync(""" + WITH p1 AS ( + SELECT p.id, p.tn, p.pn, e.eventdate, p.shipmentstatuscode, RANK() OVER (PARTITION BY p.tn ORDER BY p.id, e.id) r + FROM PERMITS p, EVENTS e + WHERE p.domain = 'GN' AND p.tt = :Tt AND e.permitid = p.id AND p.tn = :Tn AND e.domain = 'GN' AND e.eventtype = 'ASSIGNDEST' + AND p.shipmentstatuscode IN ('RESD','ACTRL','CLRPR','CLOSE')), + p2 AS ( + SELECT p.id, p.tn, e.eventdate, RANK() OVER (PARTITION BY p.tn ORDER BY p.id, e.id) r + FROM PERMITS p, EVENTS e + WHERE p.domain = 'GN' AND p.tt = :Tt AND e.permitid = p.id AND p.tn = :Tn AND e.domain = 'GN' AND e.eventtype = 'ASSIGNDEST' + AND p.shipmentstatuscode IN ('RESD','ACTRL','CLRPR','CLOSE')) + SELECT p1.id AS Id, p1.shipmentstatuscode AS ShipmentStatusCode + FROM p1, p2 + WHERE p2.tn(+) = p1.tn AND p2.r(+) = p1.r + 1 + AND TO_DATE(:GinTime, 'yyyymmddHH24miss') + 2 / 24 BETWEEN p1.eventdate AND NVL(p2.eventdate, SYSDATE) + AND NOT EXISTS (SELECT 1 FROM EVENTS e WHERE e.permitid = p1.id AND e.eventtype IN :Excluded) + ORDER BY p1.id DESC + """, new { Tn = tn, Tt = tt, GinTime = ginTime, Excluded = excludedEventTypes }, ct); + + public Task MarkRawRowAsync(string rowId, long permitId, CancellationToken ct = default) => + ExecuteAsync("UPDATE WEIGHBRIDGE_RAW_DATA SET permitid = :Pid WHERE rowid = CHARTOROWID(:RawRowId)", new { Pid = permitId, RawRowId = rowId }, ct); + + public Task SetPermitStatusAsync(long permitId, string status, CancellationToken ct = default) => + ExecuteAsync("UPDATE PERMITS SET shipmentstatuscode = :Status, lastupdatedate = SYSDATE WHERE id = :Id", new { Status = status, Id = permitId }, ct); +} + +/// SQL of grains.cfc getPermitInfoToPrint / getOrderInInfoToprint / getInfoToprint / getEventInfo_IN / getEventInfo_OUT / getPrintData. +internal sealed class PrintRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IPrintRepository +{ + private sealed class AcceptDb + { + public long Id { get; set; } + public string? ShipmentStatusCode { get; set; } + public string? Shift { get; set; } + public string? Tn { get; set; } + public string? Drvr { get; set; } + public string? CompName { get; set; } + public string? OperationType { get; set; } + public string? Trn { get; set; } + public string? Pn { get; set; } + public string? Destination { get; set; } + public string? CargoType { get; set; } + public string? NextPn { get; set; } + public string? Crn { get; set; } + public string? Scrn { get; set; } + } + + public async Task GetAcceptPrintAsync(long permitId, CancellationToken ct = default) + { + var r = await QueryFirstAsync(""" + SELECT p.id AS Id, p.shipmentstatuscode AS ShipmentStatusCode, + DECODE(o.mobile_shift, 1, N'صباحي', 2, N'مسائي', 3, N'ليلي') AS Shift, p.tn AS Tn, + (SELECT MAX(d.name) FROM NTP_DRIVERS d WHERE d.nnpn = p.nnpn AND d.statuscode IN ('OPEN','ACCPT') AND d.domain = 'GN') AS Drvr, + getcompanynamefromscac(p.companycode, 62) AS CompName, + DECODE(p.inbondtypecode, 'EXPT', N'فارغ', 'IMPT', N'محمل', '') AS OperationType, p.trn AS Trn, TO_CHAR(p.pn) AS Pn, + loc.name AS Destination, getcargotypename(o.cargotype, 'GN') AS CargoType, + (SELECT DISTINCT FIRST_VALUE(TO_CHAR(x.pn)) OVER (ORDER BY x.id) FROM PERMITS x + WHERE x.domain = 'GN' AND x.tn = p.tn AND x.pn > p.pn AND x.tt = p.tt AND x.shipmentstatuscode IN ('OPEN','REQST')) AS NextPn, + p.crn AS Crn, p.scrn AS Scrn + FROM PERMITS p, GRAINSTENDERORDER o, (SELECT * FROM LOCATIONS WHERE domain = 'GN') loc + WHERE p.scrn = TO_CHAR(o.id(+)) AND p.domain = 'GN' AND TO_CHAR(loc.id(+)) = o.destenation AND p.id = :Id + """, new { Id = permitId }, ct); + if (r is null) return null; + return new AcceptPrintDto + { + Id = r.Id, Pn = r.Pn, ShipmentStatusCode = r.ShipmentStatusCode, Shift = r.Shift, Tn = r.Tn, Trn = r.Trn, Drvr = r.Drvr, + CompName = r.CompName, OperationType = r.OperationType, Destination = r.Destination, CargoType = r.CargoType, NextPn = r.NextPn, + Crn = long.TryParse(r.Crn, out var c) ? c : null, Scrn = long.TryParse(r.Scrn, out var s) ? s : null + }; + } + + public Task GetPrintHeaderAsync(long permitId, bool withLocations, CancellationToken ct = default) => + withLocations + ? QueryFirstAsync(""" + SELECT TO_CHAR(t.trackingno) AS TrackingNo, getcompanynamefromscac(t.companycode, 62) AS CompName, t.drvr AS Drvr, t.nnpn AS Nnpn, + t.tn AS Tn, c.name AS ShipmentMode, l1.name AS Destination, l2.name AS Origin + FROM PERMITS t, CARGOTYPE c, LOCATIONS l1, LOCATIONS l2 + WHERE t.id = :Id AND t.shipmentmode = TO_CHAR(c.id) AND t.destinationaddressid = l1.id AND l1.domain = 'GN' + AND t.originaddressid = l2.id AND l2.domain = 'GN' AND t.domain = 'GN' + """, new { Id = permitId }, ct) + : QueryFirstAsync(""" + SELECT TO_CHAR(t.trackingno) AS TrackingNo, getcompanynamefromscac(t.companycode, 62) AS CompName, t.drvr AS Drvr, t.nnpn AS Nnpn, + t.tn AS Tn, c.name AS ShipmentMode + FROM PERMITS t, CARGOTYPE c WHERE t.id = :Id AND t.shipmentmode = TO_CHAR(c.id) + """, new { Id = permitId }, ct); + + public Task> GetLatestWeightEventsAsync(long permitId, CancellationToken ct = default) => + QueryAsync(""" + SELECT t.id AS Id, t.locationid AS LocationId, l.name AS LocationName, t.doneby AS DoneBy, t.weight AS Weight, t.eventtype AS EventType + FROM EVENTS t, LOCATIONS l + WHERE t.permitid = :Pid AND t.eventtype IN ('LTW','DTW','LGW','DGW') AND t.domain = 'GN' AND l.id(+) = t.locationid AND l.domain(+) = 'GN' + AND t.id IN ((SELECT MAX(x.id) FROM EVENTS x WHERE x.permitid = :Pid AND x.eventtype = 'LTW' AND x.domain = 'GN'), + (SELECT MAX(x.id) FROM EVENTS x WHERE x.permitid = :Pid AND x.eventtype = 'DTW' AND x.domain = 'GN'), + (SELECT MAX(x.id) FROM EVENTS x WHERE x.permitid = :Pid AND x.eventtype = 'LGW' AND x.domain = 'GN'), + (SELECT MAX(x.id) FROM EVENTS x WHERE x.permitid = :Pid AND x.eventtype = 'DGW' AND x.domain = 'GN')) + """, new { Pid = permitId }, ct); + + public Task GetLatestEventWithLocationAsync(long permitId, string eventType, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT t.id AS Id, t.locationid AS LocationId, l.name AS LocationName, t.doneby AS DoneBy, t.weight AS Weight, t.eventtype AS EventType + FROM EVENTS t, LOCATIONS l + WHERE t.permitid = :Pid AND t.eventtype = :Type AND t.locationid = l.id AND l.domain = 'GN' AND t.domain = 'GN' + AND t.eventdate = (SELECT MAX(e.eventdate) FROM EVENTS e WHERE e.permitid = :Pid AND e.domain = 'GN' AND e.eventtype = :Type) + ORDER BY t.id DESC + """, new { Pid = permitId, Type = eventType }, ct); + + public Task GetDetailsAsync(long permitId, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT p.id AS Id, TO_CHAR(p.pn) AS Pn, p.shipmentstatuscode AS StatusCode, p.tn AS Tn, p.trn AS Trn, p.trnat AS TruckNationality, + p.tt AS TrailerType, p.drvr AS DriverName, p.nnpn AS Nnpn, p.dln AS Dln, p.cat AS Cat, TO_DATE(NULL) AS Dled, + p.nat AS DriverNationality, p.shipmentmode AS ShipmentMode, p.inbondtypecode AS Operation, p.firms AS Lane, + (SELECT MIN(l.name) FROM LOCATIONS l WHERE l.id = p.originaddressid AND l.domain = 'GN') AS Origin, + (SELECT MIN(l.name) FROM LOCATIONS l WHERE l.id = p.destinationaddressid AND l.domain = 'GN') AS Destination, + routdetails(p.routingtemplateid, p.domain) AS RouteName + FROM PERMITS p WHERE p.id = :Id + """, new { Id = permitId }, ct); + + public Task GetCompanyCodeAsync(long permitId, CancellationToken ct = default) => + QueryFirstAsync("SELECT companycode FROM PERMITS WHERE id = :Id", new { Id = permitId }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/BlacklistRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/BlacklistRepository.cs new file mode 100644 index 0000000..7923f9f --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/BlacklistRepository.cs @@ -0,0 +1,102 @@ +using System.Data; +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Registry; +using NTP.Domain.Grains.Registry; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Registry; + +/// Dapper port of the GRAINSBLACKLIST SQL of grains.cfc (getBlackListGrid, BL_addToBlacklist, deleteFromBlackList) and jobs\changeBlacklistStatus.cfm. +internal sealed class BlacklistRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IBlacklistRepository +{ + public async Task> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct = default) + { + var where = new StringBuilder(" WHERE 1 = 1"); + var p = new DynamicParameters(); + if (!string.IsNullOrWhiteSpace(query.EntityId)) + { + // the screen filters by permit number: ENTITYID = (select id from permits where pn = ...) + where.Append(" AND b.ENTITYID IN (SELECT pp.ID FROM PERMITS pp WHERE TO_CHAR(pp.PN) = :Pn)"); + p.Add("Pn", query.EntityId.Trim()); + } + if (!string.IsNullOrWhiteSpace(query.Category)) { where.Append(" AND b.CATEGORY = :Category"); p.Add("Category", query.Category.Trim()); } + if (!string.IsNullOrWhiteSpace(query.StatusCode)) { where.Append(" AND b.STATUSCODE = :Status"); p.Add("Status", query.StatusCode.Trim()); } + + var baseSql = $""" + SELECT b.ID AS Id, b.CATEGORY AS Category, b.ENTITYTYPE AS EntityType, + CASE WHEN b.ENTITYTYPE = 'PERMIT' + THEN (SELECT MIN(TO_CHAR(p.PN)) FROM PERMITS p WHERE p.ID = b.ENTITYID) + ELSE TO_CHAR(b.ENTITYID) END AS EntityNumber, + b.CREATIONDATE AS CreationDate, b.CREATEDBY AS CreatedBy, b.LASTUPDATEDATE AS LastUpdateDate, + b.LASTUPDATEUSER AS LastUpdateUser, b.EXPIRYDATE AS ExpiryDate, b.STATUSCODE AS StatusCode, b.REMARKS AS Remarks + FROM GRAINSBLACKLIST b{where} + """; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY b.ID"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task GetPermitShiftAsync(long permitId, CancellationToken ct = default) + { + var shift = await QueryFirstAsync(""" + SELECT g.SHIFT FROM PERMITS p, GRAINSTENDERORDER g + WHERE p.ID = :Id AND p.DOMAIN = 'GN' AND p.SCRN = g.ID + ORDER BY g.ID + """, new { Id = permitId }, ct); + return shift is null ? null : (int)shift.Value; + } + + public Task FindPermitIdByNumberAsync(string pn, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT * FROM (SELECT ID FROM PERMITS WHERE TO_CHAR(PN) = :Pn AND DOMAIN = 'GN' ORDER BY ID DESC) WHERE ROWNUM = 1 + """, new { Pn = pn }, ct); + + public async Task InsertAsync(string category, string entityType, string entityId, string createdBy, DateTime expiry, string remarks, CancellationToken ct = default) + { + var p = new DynamicParameters(new { Category = category, EntityType = entityType, EntityId = entityId, CreatedBy = createdBy, Expiry = expiry, Remarks = remarks }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + await ExecuteAsync(""" + INSERT INTO GRAINSBLACKLIST + (ID, CATEGORY, ENTITYTYPE, ENTITYID, CREATEDBY, EXPIRYDATE, STATUSCODE, REMARKS, LASTUPDATEUSER, LASTUPDATEDATE) + VALUES + (SEQ_GRAINSBLACKLIST.NEXTVAL, :Category, :EntityType, :EntityId, :CreatedBy, :Expiry, 'OPEN', :Remarks, :CreatedBy, SYSDATE) + RETURNING ID INTO :NewId + """, p, ct); + return OracleSql.ToInt64(p.Get("NewId")); + } + + public Task GetAsync(long id, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT ID AS Id, CATEGORY AS Category, ENTITYTYPE AS EntityType, TO_CHAR(ENTITYID) AS EntityId, CREATEDBY AS CreatedBy, + EXPIRYDATE AS ExpiryDate, STATUSCODE AS StatusCode, REMARKS AS Remarks, + LASTUPDATEUSER AS LastUpdateUser, LASTUPDATEDATE AS LastUpdateDate + FROM GRAINSBLACKLIST WHERE ID = :Id + """, new { Id = id }, ct); + + public Task CancelAsync(long id, string user, string remarks, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE GRAINSBLACKLIST + SET STATUSCODE = 'DELETED', LASTUPDATEUSER = :UserId, LASTUPDATEDATE = SYSDATE, REMARKS = :Remarks + WHERE ID = :Id + """, new { UserId = user, Remarks = remarks, Id = id }, ct); + + public Task DeleteDistributionLogAsync(long blacklistId, string remarks, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE TRUCK_DISTRIBUTION_LOG + SET STATUSCODE = 'DELETED', UPDATEDATE = SYSDATE, NOTES = :Notes + WHERE TO_CHAR(BLACKLISTID) = :BlacklistId AND STATUSCODE IN ('PENDING', 'RVKD') + """, new { Notes = remarks, BlacklistId = blacklistId.ToString(System.Globalization.CultureInfo.InvariantCulture) }, ct); + + public Task ExpireDueAsync(CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE GRAINSBLACKLIST + SET STATUSCODE = 'EXPIRED', LASTUPDATEUSER = 'SYSTEM', LASTUPDATEDATE = SYSDATE + WHERE EXPIRYDATE < SYSDATE AND STATUSCODE = 'OPEN' + """, null, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryFileStoreService.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryFileStoreService.cs new file mode 100644 index 0000000..ed90bf5 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryFileStoreService.cs @@ -0,0 +1,64 @@ +using System.Text; +using System.Text.RegularExpressions; +using NTP.Application.Grains.Registry; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Registry; + +/// +/// File system side of the registry attachments. Temp uploads are stored as {guid}.tmp with a {guid}.name sidecar +/// holding the original file name (legacy kept the original name as the temp file name); promotion moves the file into +/// {UploadedFilesPath}/{folder}/{storedName} (legacy cffile rename into uploadedfiles/ntp_*_files). +/// +internal sealed partial class RegistryFileStoreService(IRegistrySettingsService settings) : IRegistryFileStoreService +{ + [GeneratedRegex("^[0-9a-f]{32}$")] + private static partial Regex TempIdRegex(); + + [GeneratedRegex(@"^[A-Za-z0-9_\-]+(\.[A-Za-z0-9]{1,8})?$")] + private static partial Regex StoredNameRegex(); + + private string TempFile(string id) => Path.Combine(settings.TempUploadPath, id + ".tmp"); + private string TempNameFile(string id) => Path.Combine(settings.TempUploadPath, id + ".name"); + + public async Task SaveTempAsync(Stream content, string originalName, CancellationToken ct = default) + { + Directory.CreateDirectory(settings.TempUploadPath); + var id = Guid.NewGuid().ToString("N"); + long size; + await using (var fs = new FileStream(TempFile(id), FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true)) + { + await content.CopyToAsync(fs, ct); + size = fs.Length; + } + await File.WriteAllTextAsync(TempNameFile(id), originalName, Encoding.UTF8, ct); + return new RegistryTempFileDto(id, originalName, size); + } + + public async Task GetTempNameAsync(string tempId, CancellationToken ct = default) + { + if (!TempIdRegex().IsMatch(tempId) || !File.Exists(TempFile(tempId))) return null; + return File.Exists(TempNameFile(tempId)) + ? (await File.ReadAllTextAsync(TempNameFile(tempId), Encoding.UTF8, ct)).Trim() + : tempId; + } + + public Task PromoteAsync(string tempId, string folder, string storedName, CancellationToken ct = default) + { + if (!TempIdRegex().IsMatch(tempId) || !StoredNameRegex().IsMatch(storedName)) + throw new ArgumentException("Invalid attachment name."); + var targetDir = Path.Combine(settings.UploadedFilesPath, folder); + Directory.CreateDirectory(targetDir); + File.Move(TempFile(tempId), Path.Combine(targetDir, storedName), overwrite: false); + File.Delete(TempNameFile(tempId)); + return Task.CompletedTask; + } + + public Task OpenAsync(string folder, string storedName, CancellationToken ct = default) + { + if (!StoredNameRegex().IsMatch(storedName)) return Task.FromResult(null); + var path = Path.Combine(settings.UploadedFilesPath, folder, storedName); + return Task.FromResult(File.Exists(path) + ? new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true) + : null); + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryOpsRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryOpsRepository.cs new file mode 100644 index 0000000..758eb02 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryOpsRepository.cs @@ -0,0 +1,268 @@ +using System.Globalization; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Registry; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Registry; + +/// +/// Dapper port of: register.cfc saveWeighbridgesControlInfo / validateTNMOT / validateTRNMOT / validateOwnerTN (MOT tables) and +/// grains.cfc saveGrainsWeights / checkTrucks / validateNtpTrucks / getlocTruckNum / getDriverInfo / getTruckInfo / isTrailerInUse / +/// getTruckInfoFromTN / getTrailerNumber / getTNinfo / getTRNinfo / getDRVRinfo. +/// +internal sealed class RegistryOpsRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IRegistryOpsRepository +{ + // -------------------------------------------------------------------------------------------- weighbridge control + + public Task FindOpenOrAcceptedTruckIdAsync(string tn, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT * FROM ( + SELECT ID FROM NTP_TRUCKS + WHERE TO_CHAR(TN) = :Tn AND STATUSCODE IN ('OPEN','ACCPT') AND DOMAIN = 'GN' + ORDER BY ID DESC + ) WHERE ROWNUM = 1 + """, new { Tn = tn }, ct); + + public Task InsertWeighbridgeControlAsync(long truckId, long locationId, string? notes, string createdBy, DateTime expiryDate, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO GRAINS_WEIGHBRIDG_CONTROL (ID, NTP_TRUCKID, LOCATIONID, DOMAIN, NOTES, CREATEDBY, EXPIEYDATE) + VALUES (SEQ_GRAINS_WEIGHBRIDG_CONTROL.NEXTVAL, :TruckId, :LocationId, 'GN', :Notes, :CreatedBy, :ExpiryDate) + """, new { TruckId = truckId, LocationId = locationId, Notes = notes, CreatedBy = createdBy, ExpiryDate = expiryDate }, ct); + + // -------------------------------------------------------------------------------------------- grains weights + + private sealed class PermitRow + { + public long Id { get; set; } + public string? Status { get; set; } + } + + public async Task<(long Id, string? Status)?> FindPermitByNumberAsync(string pn, CancellationToken ct = default) + { + var row = await QueryFirstAsync(""" + SELECT * FROM ( + SELECT ID AS Id, SHIPMENTSTATUSCODE AS Status FROM PERMITS WHERE TO_CHAR(PN) = :Pn AND DOMAIN = 'GN' ORDER BY ID DESC + ) WHERE ROWNUM = 1 + """, new { Pn = pn }, ct); + return row is null ? null : (row.Id, row.Status); + } + + public Task FindWeightRowAsync(long permitId, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT * FROM (SELECT ID FROM GRAINS_PERMITS_WEIGHTS WHERE PERMIT_ID = :PermitId ORDER BY ID) WHERE ROWNUM = 1 + """, new { PermitId = permitId }, ct); + + public Task UpdateWeightsAsync(long weightRowId, string empty, string gross, string document, string user, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE GRAINS_PERMITS_WEIGHTS + SET EMPTY_WEIGHT = :Empty, GROSS_WEIGHT = :Gross, DOCUMENT_NUMBER = :Document, UPDATE_DATE = SYSDATE, UPDATE_BY = :UserId + WHERE ID = :Id + """, new { Empty = empty, Gross = gross, Document = document, UserId = user, Id = weightRowId }, ct); + + public Task InsertWeightsAsync(string empty, string gross, string document, long permitId, string user, CancellationToken ct = default) => + // Legacy uses a positional INSERT (no column list): id, empty, gross, document no, permit id, create date, create user, update date, update user. + ExecuteAsync(""" + INSERT INTO GRAINS_PERMITS_WEIGHTS + VALUES (SEQ_GRAINS_PERMITS_WEIGHTS.NEXTVAL, :Empty, :Gross, :Document, :PermitId, SYSDATE, :UserId, NULL, NULL) + """, new { Empty = empty, Gross = gross, Document = document, PermitId = permitId, UserId = user }, ct); + + // -------------------------------------------------------------------------------------------- fleet turns (checkTrucks) + + public async Task CountActiveFleetAsync(long scac, CancellationToken ct = default) => + (int)await ExecuteScalarAsync(""" + SELECT COUNT(P.ID) FROM NTP_TRUCKS P + WHERE P.DOMAIN = 'GN' AND P.STATUSCODE IN ('OPEN','ACCPT') AND P.TCSCAC = :Scac + """, new { Scac = scac }, ct); + + public async Task CountActiveTurnRowsAsync(long scac, CancellationToken ct = default) => + (int)await ExecuteScalarAsync("SELECT COUNT(ID) FROM GRAINS_TRUCKS_VALIDATION WHERE SCAC = :Scac AND STATUS = 1", + new { Scac = scac }, ct); + + public async Task TruckInTurnAsync(long scac, long tn, CancellationToken ct = default) => + await ExecuteScalarAsync("SELECT COUNT(ID) FROM GRAINS_TRUCKS_VALIDATION WHERE TN = :Tn AND STATUS = 1 AND SCAC = :Scac", + new { Tn = tn, Scac = scac }, ct) > 0; + + public Task InsertTurnRowAsync(long scac, long tn, string user, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO GRAINS_TRUCKS_VALIDATION (ID, SCAC, TN, STATUS, CREATEDBY) + VALUES (SEQ_GRAINS_TRUCKS_VALIDATION.NEXTVAL, :Scac, :Tn, 1, :UserId) + """, new { Scac = scac, Tn = tn, UserId = user }, ct); + + public Task ResetTurnRowsAsync(long scac, CancellationToken ct = default) => + ExecuteAsync("UPDATE GRAINS_TRUCKS_VALIDATION SET STATUS = 0 WHERE STATUS = 1 AND SCAC = :Scac", new { Scac = scac }, ct); + + // -------------------------------------------------------------------------------------------- misc grains.cfc + + public async Task IsValidBadiyaTruckAsync(string tn, long badiyaScac, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM NTP_TRUCKS + WHERE TO_CHAR(TN) = :Tn AND STATUSCODE IN ('ACCPT','OPEN','REGREQST') AND DOMAIN = 'GN' AND TCSCAC = :Scac + """, new { Tn = tn, Scac = badiyaScac }, ct) > 0; + + public Task> GetLocationTruckCountsAsync(CancellationToken ct = default) => + QueryAsync(""" + SELECT NVL((SELECT MIN(l.NAME) FROM LOCATIONS l WHERE l.ID = t.DESTINATIONADDRESSID AND l.DOMAIN = 'GN'), N'مواقع التحميل') AS Loc, + COUNT(*) AS Cnt + FROM PERMITS t + WHERE t.DOMAIN = 'GN' AND t.SHIPMENTSTATUSCODE IN ('ACTRL','ACCPT','RESD') + GROUP BY t.SHIPMENTSTATUSCODE, t.DESTINATIONADDRESSID + ORDER BY 2 DESC, 1 + """, null, ct); + + // -------------------------------------------------------------------------------------------- permit-screen lookups + + public Task GetDriverFromPermitsAsync(string nnpn, string domain, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT * FROM ( + SELECT p.DRVR AS Drvr, TO_CHAR(p.CAT) AS Cat, p.DLED AS Dled, TO_CHAR(p.DLN) AS Dln, TO_CHAR(p.NAT) AS Nat + FROM PERMITS p + WHERE TO_CHAR(p.NNPN) = :Nnpn + AND p.SHIPMENTSTATUSCODE IN (SELECT CODE FROM STATUS WHERE ISACTIVE = 1 AND DOMAIN = :Domain) + AND UPPER(p.DOMAIN) = :Domain + ORDER BY p.ID DESC + ) WHERE ROWNUM = 1 + """, new { Nnpn = nnpn, Domain = domain.ToUpperInvariant() }, ct); + + public Task GetTruckFromPermitsAsync(string tn, string domain, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT * FROM ( + SELECT TO_CHAR(p.TN) AS Tn, TO_CHAR(p.TRN) AS Trn, TO_CHAR(p.TRNAT) AS Trnat, p.TT AS Tt, p.DRVR AS Drvr, + TO_CHAR(p.CAT) AS Cat, TO_CHAR(p.DLN) AS Dln, p.DLED AS Dled, TO_CHAR(p.NAT) AS Nat, TO_CHAR(p.NNPN) AS Nnpn, + p.ROUTINGTEMPLATEID AS RoutingTemplateId, p.ORIGINADDRESSID AS OriginAddressId, + p.DESTINATIONADDRESSID AS DestinationAddressId, TO_CHAR(p.FIRMS) AS Firms, TO_CHAR(p.ASRN) AS Asrn, + TO_CHAR(p.CAN) AS Can, getClearingAgen(p.CAN) AS CanName + FROM PERMITS p + WHERE TO_CHAR(p.TN) = :Tn + AND p.SHIPMENTSTATUSCODE IN (SELECT CODE FROM STATUS WHERE ISACTIVE = 0 AND DOMAIN = :Domain) + ORDER BY p.ID DESC + ) WHERE ROWNUM = 1 + """, new { Tn = tn, Domain = domain.ToUpperInvariant() }, ct); + + public Task> GetTrailerInUseAsync(string trn, long? exceptPermitId, string domain, CancellationToken ct = default) => + QueryAsync(""" + SELECT TO_CHAR(po.PN) AS Pn, TO_CHAR(po.CREATIONDATE, 'yyyy/mm/dd') AS CreationDate + FROM PERMITS po + WHERE po.SHIPMENTSTATUSCODE IN (SELECT CODE FROM STATUS WHERE ISACTIVE = 1 AND DOMAIN = :Domain) + AND po.PN IS NOT NULL + AND TO_CHAR(po.TRN) = :Trn + AND (:ExceptId IS NULL OR po.ID <> :ExceptId) + ORDER BY po.ID + """, new { Domain = domain.ToUpperInvariant(), Trn = trn, ExceptId = exceptPermitId }, ct); + + public Task GetPermitByTruckAsync(string tn, string status, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT * FROM ( + SELECT ID AS Id, DRVR AS Drvr, TO_CHAR(TN) AS Tn, TO_CHAR(PN) AS Pn, SHIPMENTSTATUSCODE AS ShipmentStatusCode + FROM PERMITS + WHERE TO_CHAR(TN) = :Tn AND SHIPMENTSTATUSCODE = :Status AND DOMAIN = 'GN' + ORDER BY ID DESC + ) WHERE ROWNUM = 1 + """, new { Tn = tn, Status = status }, ct); + + public Task GetTrailerNumberOfTruckAsync(string tn, IReadOnlyList allowedStatuses, CancellationToken ct = default) + { + if (allowedStatuses.Count == 0) return Task.FromResult(null); + var p = new DynamicParameters(); + p.Add("Tn", tn); + var names = new List(); + for (var i = 0; i < allowedStatuses.Count; i++) + { + names.Add($":S{i}"); + p.Add($"S{i}", allowedStatuses[i]); + } + return QueryFirstAsync($""" + SELECT * FROM ( + SELECT TO_CHAR(trn.TN) + FROM NTP_TRAILERS trn + WHERE trn.TN_ID IN (SELECT t.ID FROM NTP_TRUCKS t + WHERE TO_CHAR(t.TN) = :Tn AND t.DOMAIN = 'GN' AND t.STATUSCODE IN ({string.Join(", ", names)})) + ORDER BY CASE WHEN trn.STATUSCODE = 'RVKD' THEN 1 ELSE 0 END, trn.ID DESC + ) WHERE ROWNUM = 1 + """, p, ct); + } + + private sealed class InfoRow + { + public string? ChasesNumber { get; set; } + public string? Axials { get; set; } + public DateTime? RegDate { get; set; } + } + + public async Task<(string? ChasesNumber, string? Axials, DateTime? RegDate)?> GetTruckInfoAsync(string tn, RegistryScope scope, CancellationToken ct = default) + { + var scopeSql = scope.CompanyOnly ? (scope.CompanyCodeNo is null ? " AND 1 = 0" : " AND t.TCSCAC = :Scac") : ""; + var row = await QueryFirstAsync($""" + SELECT t.CHASESNUMBER AS ChasesNumber, k.DESCREPTION AS Axials, t.REG_DATE AS RegDate + FROM NTP_TRUCKS t, TRUCKKINDS k + WHERE TO_CHAR(t.TN) = :Tn AND t.DOMAIN = 'GN' AND t.AXIALS = k.ID{scopeSql} + AND t.STATUSCODE NOT IN ('RVKD') + ORDER BY t.ID DESC + """, new { Tn = tn, Scac = scope.CompanyCodeNo }, ct); + return row is null ? null : (row.ChasesNumber, row.Axials, row.RegDate); + } + + public Task GetActiveTrailerScacAsync(string trn, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT * FROM ( + SELECT TCSCAC FROM NTP_TRAILERS + WHERE TO_CHAR(TN) = TRIM(:Trn) AND DOMAIN = 'GN' AND STATUSCODE IN ('OPEN','ACCPT') + ORDER BY TCSCAC DESC + ) WHERE ROWNUM = 1 + """, new { Trn = trn }, ct); + + public async Task<(string? ChasesNumber, string? Axials, DateTime? RegDate)?> GetTrailerInfoAsync(string trn, RegistryScope scope, CancellationToken ct = default) + { + var scopeSql = scope.CompanyOnly ? (scope.CompanyCodeNo is null ? " AND 1 = 0" : " AND t.TCSCAC = :Scac") : ""; + var row = await QueryFirstAsync($""" + SELECT t.CHASESNUMBER AS ChasesNumber, k.DESCREPTION AS Axials, t.REG_DATE AS RegDate + FROM NTP_TRAILERS t, TRUCKKINDS k + WHERE TO_CHAR(t.TN) = TRIM(:Trn) AND t.AXIALS = k.ID{scopeSql} + AND t.STATUSCODE NOT IN ('RVKD') AND t.DOMAIN = 'GN' + ORDER BY t.ID DESC + """, new { Trn = trn, Scac = scope.CompanyCodeNo }, ct); + return row is null ? null : (row.ChasesNumber, row.Axials, row.RegDate); + } + + private sealed class DriverInfoRow + { + public string? Name { get; set; } + public string? Dln { get; set; } + public DateTime? Dled { get; set; } + } + + public async Task<(string? Name, string? Dln, DateTime? Dled)?> GetDriverInfoAsync(string nnpn, CancellationToken ct = default) + { + var row = await QueryFirstAsync(""" + SELECT NAME AS Name, TO_CHAR(DLN) AS Dln, DLED AS Dled + FROM NTP_DRIVERS + WHERE TO_CHAR(NNPN) = :Nnpn AND DOMAIN = 'GN' AND STATUSCODE NOT IN ('RVKD') + ORDER BY ID DESC + """, new { Nnpn = nnpn }, ct); + return row is null ? null : (row.Name, row.Dln, row.Dled); + } + + // -------------------------------------------------------------------------------------------- MOT + + public Task GetMotOwnershipCodeAsync(string tn, long scac, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT TO_CHAR(t.OWNERSHIPCODE) FROM MOT_TRUCKS t + WHERE t.STATUS = 1 AND TO_CHAR(t.TCSCAC) = :Scac AND TO_CHAR(t.TN) = :Tn + ORDER BY t.ID + """, new { Scac = scac.ToString(CultureInfo.InvariantCulture), Tn = tn }, ct); + + public Task> GetMotTruckTypesAsync(string tn, long scac, CancellationToken ct = default) => + QueryAsync(""" + SELECT tt.CODE + FROM MOT_TRUCKS t, MOT_ENTITYSPECS s, MOTTRUCKTYPE tt + WHERE t.ID = s.TNID AND s.SPECID = tt.ID AND t.STATUS = 1 AND s.STATUS = 1 + AND TO_CHAR(t.TCSCAC) = :Scac AND TO_CHAR(t.TN) = :Tn + """, new { Scac = scac.ToString(CultureInfo.InvariantCulture), Tn = tn }, ct); + + public async Task CountMotTrailerRowsAsync(string trn, long scac, CancellationToken ct = default) => + (int)await ExecuteScalarAsync(""" + SELECT COUNT(*) + FROM MOT_ENTITYSPECS s, MOT_TRAILERS t, MOTTRUCKTYPE tt + WHERE t.STATUS = 1 AND s.STATUS = 1 AND TO_CHAR(t.TRN) = :Trn AND t.ID = s.TRNID AND s.SPECID = tt.ID AND t.TCSCAC = :Scac + """, new { Trn = trn, Scac = scac }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryQueuePermitRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryQueuePermitRepository.cs new file mode 100644 index 0000000..af6e857 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryQueuePermitRepository.cs @@ -0,0 +1,64 @@ +using System.Data; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Registry; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Registry; + +/// SQL of ws.cfc createPermitRecord and jobs\RegisterGrainsQueueForNewTrucks.cfm. +internal sealed class RegistryQueuePermitRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IRegistryQueuePermitRepository +{ + public async Task IsOpenOrAcceptedGnTruckAsync(string tn, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM NTP_TRUCKS t + WHERE TO_CHAR(t.TN) = :Tn AND t.DOMAIN = 'GN' AND t.STATUSCODE IN ('OPEN','ACCPT') + """, new { Tn = tn }, ct) > 0; + + public async Task HasActivePermitAsync(string tn, string tt, bool checkAllStatuses, CancellationToken ct = default) + { + var statuses = checkAllStatuses ? "('REQST','PLND','OPEN')" : "('OPEN')"; + return await ExecuteScalarAsync($""" + SELECT COUNT(*) FROM PERMITS t + WHERE TO_CHAR(t.TN) = :Tn AND t.SHIPMENTSTATUSCODE IN {statuses} AND t.DOMAIN = 'GN' AND t.TT = :Tt + """, new { Tn = tn, Tt = tt }, ct) > 0; + } + + public Task NextTrackingNumberAsync(bool badiya, CancellationToken ct = default) => + ExecuteScalarAsync(badiya + ? "SELECT SEQ_GRAINS_TRACKINGNO_OWN.NEXTVAL FROM DUAL" + : "SELECT SEQ_GRAINS_TRACKINGNO_CO.NEXTVAL FROM DUAL", null, ct); + + public Task NextTripCounterAsync(string tt, long badiyaScac, CancellationToken ct = default) => + ExecuteScalarAsync(""" + SELECT NVL(MAX(p.TRIPCOUNTER), 0) + 1 FROM PERMITS p + WHERE p.DOMAIN = 'GN' AND p.TT = :Tt AND p.CREATIONDATE > TRUNC(SYSDATE) AND p.COMPANYCODE = :Scac + """, new { Tt = tt, Scac = badiyaScac }, ct); + + public Task GetMaxTenderIdAsync(CancellationToken ct = default) => + ExecuteScalarAsync("SELECT NVL(MAX(ID), 0) FROM NTP_TENDER t WHERE t.DOMAIN = 'GN'", null, ct); + + public async Task InsertPermitAsync(string pn, string tn, long scac, string status, string tt, long? tripCounter, CancellationToken ct = default) + { + var p = new DynamicParameters(new + { + Pn = pn, Tn = string.IsNullOrWhiteSpace(tn) ? null : tn, Scac = scac, Status = status, Tt = tt, TripCounter = tripCounter + }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + // addDBRecordNOORM('PERMITS', ...) -> seq_PERMITS.nextval; TRIPCOUNTER is only set for company 327 + await ExecuteAsync(""" + INSERT INTO PERMITS (ID, PN, TN, COMPANYCODE, SHIPMENTSTATUSCODE, DOMAIN, TT, TRIPCOUNTER) + VALUES (SEQ_PERMITS.NEXTVAL, :Pn, :Tn, :Scac, :Status, 'GN', :Tt, :TripCounter) + RETURNING ID INTO :NewId + """, p, ct); + return NTP.Infrastructure.Persistence.OracleSql.ToInt64(p.Get("NewId")); + } + + public async Task> GetBadiyaTrucksWithoutPermitsAsync(long badiyaScac, CancellationToken ct = default) => + await QueryAsync(""" + SELECT TO_CHAR(t.TN) + FROM NTP_TRUCKS t, + (SELECT p.TN FROM PERMITS p WHERE p.DOMAIN = 'GN' AND p.COMPANYCODE = :Scac) p + WHERE p.TN IS NULL AND p.TN(+) = t.TN AND t.TCSCAC = :Scac AND t.STATUSCODE IN ('OPEN','ACCPT') + """, new { Scac = badiyaScac }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryRepository.cs new file mode 100644 index 0000000..46063de --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistryRepository.cs @@ -0,0 +1,524 @@ +using System.Data; +using System.Globalization; +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Registry; +using NTP.Domain.Grains.Registry; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Registry; + +/// +/// Dapper port of the SQL of register.cfc (trucks, trailers, drivers, attachments, destinations) and the lookups it feeds. +/// Legacy tables: NTP_TRUCKS, NTP_TRAILERS, NTP_DRIVERS, GRAINS_FILES, NTP_COMPANY_DISTINATION, STATUS, LOCATIONS, TRUCKKINDS, +/// NTP_TENDERS_COMPANIES, GROUP_ACTIONS, PERMITS. Every statement uses bind variables. +/// +internal sealed class RegistryRepository(IDbSession session, INtpDbSession ntpSession, ILogger logger) + : OracleRepositoryBase(session, logger), IRegistryRepository +{ + private NtpAccess Ntp { get; } = new(ntpSession, logger); + + /// NTP-schema connection: GROUPS / GROUP_ACTIONS (isActAuthorized) and NATIONALITY are not reachable from NAFITHTCS. + private sealed class NtpAccess(INtpDbSession s, ILogger l) : NtpRepositoryBase(s, l) + { + public Task> ListAsync(string sql, object? p, CancellationToken ct) => QueryAsync(sql, p, ct); + public Task ScalarAsync(string sql, object? p, CancellationToken ct) => ExecuteScalarAsync(sql, p, ct); + } + + private const string Gn = "GN"; + + // columns shared by the entity reads (aliases match the Domain property names; TO_CHAR keeps string properties safe + // whichever of NUMBER / VARCHAR2 the legacy column is) + private const string TruckColumns = """ + t.ID AS Id, TO_CHAR(t.TN) AS Tn, t.CHASESNUMBER AS ChasesNumber, t.REG_DATE AS RegDate, t.AXIALS AS Axials, + t.STATUSCODE AS StatusCode, t.OWNERNAME AS OwnerName, TO_CHAR(t.OWNERNNPN) AS OwnerNnpn, t.COLOR AS Color, t.MODEL AS Model, + TO_CHAR(t.MANIFACTUREYEAR) AS ManifactureYear, TO_CHAR(t.PHONENUMBER) AS PhoneNumber, t.HEADTYPE AS HeadType, t.TCSCAC AS Tcscac, + t.CREATEUSERID AS CreateUserId, t.CREATETIMESTAMP AS CreateTimestamp, + t.LASTUPDATEUSERID AS LastUpdateUserId, t.LASTUPDATETIMESTAMP AS LastUpdateTimestamp + """; + + private const string TrailerColumns = """ + t.ID AS Id, TO_CHAR(t.TN) AS Tn, t.CHASESNUMBER AS ChasesNumber, t.REG_DATE AS RegDate, t.AXIALS AS Axials, + t.STATUSCODE AS StatusCode, t.OWNERNAME AS OwnerName, TO_CHAR(t.OWNERNNPN) AS OwnerNnpn, TO_CHAR(t.PHONENUMBER) AS PhoneNumber, + t.TN_ID AS TnId, t.TCSCAC AS Tcscac, t.CREATEUSERID AS CreateUserId, t.CREATETIMESTAMP AS CreateTimestamp, + t.LASTUPDATEUSERID AS LastUpdateUserId, t.LASTUPDATETIMESTAMP AS LastUpdateTimestamp + """; + + private const string DriverColumns = """ + t.ID AS Id, TO_CHAR(t.NNPN) AS Nnpn, t.NAME AS Name, TO_CHAR(t.DLN) AS Dln, t.DLED AS Dled, TO_CHAR(t.NAT) AS Nat, + TO_CHAR(t.CAT) AS Cat, TO_CHAR(t.MOBILE1) AS Mobile1, TO_CHAR(t.MOBILE2) AS Mobile2, t.STATUSCODE AS StatusCode, + t.TCSCAC AS Tcscac, t.CREATEUSERID AS CreateUserId, t.CREATETIMESTAMP AS CreateTimestamp + """; + + // ===================================================================================================== authorization + + public async Task HasActionAsync(string roleCode, int actionId, CancellationToken ct = default) => + await Ntp.ScalarAsync(""" + SELECT COUNT(*) FROM GROUP_ACTIONS ga, GROUPS g + WHERE ga.GROUPID = g.ID AND g.NAME = :Role AND g.STATUS = 1 AND ga.ACTIONID = :ActionId + """, new { Role = roleCode, ActionId = actionId }, ct) > 0; + + // ===================================================================================================== lookups + + public Task> GetTenderCompaniesAsync(CancellationToken ct = default) => + QueryAsync(""" + SELECT t.SCAC AS Scac, t.NAME AS Name + FROM NTP_TENDERS_COMPANIES t + WHERE t.STATUSCODE = 'ACTIVE' + ORDER BY DECODE(t.SCAC, 327, 1, t.SCAC) + """, null, ct); + + public Task> GetTruckKindsAsync(IReadOnlyList kinds, CancellationToken ct = default) + { + if (kinds.Count == 0) return Task.FromResult>([]); + var p = new DynamicParameters(); + var names = new List(); + for (var i = 0; i < kinds.Count; i++) + { + names.Add($":K{i}"); + p.Add($"K{i}", kinds[i].ToUpperInvariant()); + } + return QueryAsync($""" + SELECT UPPER(t.TRUCKKINDCODE) AS Kind, t.ID AS Id, t.DESCREPTION AS Name + FROM TRUCKKINDS t + WHERE UPPER(t.TRUCKKINDCODE) IN ({string.Join(", ", names)}) + ORDER BY UPPER(t.TRUCKKINDCODE), t.ID + """, p, ct); + } + + public Task> GetDestinationLocationsAsync(string gnType, CancellationToken ct = default) => + QueryAsync(""" + SELECT t.ID AS Id, t.NAME AS Name + FROM LOCATIONS t + WHERE t.DOMAIN = 'GN' AND t.STATUS = 1 AND t.GN_TYPE = :GnType AND t.TYPE = 'EX' + ORDER BY t.SORTORDER, t.ID + """, new { GnType = gnType }, ct); + + public Task> GetDriverNationalitiesAsync(CancellationToken ct = default) => + Ntp.ListAsync(""" + SELECT TO_CHAR(CODE) AS Code, NAME AS Name + FROM NATIONALITY + WHERE LANGID = 0 AND ID NOT IN (11, 12) + ORDER BY ID + """, null, ct); + + public Task> GetLocationsByIdsAsync(IReadOnlyList ids, CancellationToken ct = default) + { + if (ids.Count == 0) return Task.FromResult>([]); + var p = new DynamicParameters(); + var names = new List(); + for (var i = 0; i < ids.Count; i++) + { + names.Add($":I{i}"); + p.Add($"I{i}", ids[i]); + } + return QueryAsync( + $"SELECT ID AS Id, NAME AS Name FROM LOCATIONS WHERE ID IN ({string.Join(", ", names)}) ORDER BY NAME, ID", p, ct); + } + + // ===================================================================================================== grids + + /// Appends the company-user restriction (legacy: session.stkid eq 62 -> and tcscac = session.companycodeno). + private static void AddScope(StringBuilder where, DynamicParameters p, RegistryScope scope, string alias) + { + if (!scope.CompanyOnly) return; + if (scope.CompanyCodeNo is null) { where.Append(" AND 1 = 0"); return; } + where.Append($" AND {alias}.TCSCAC = :ScopeScac"); + p.Add("ScopeScac", scope.CompanyCodeNo.Value); + } + + public async Task> SearchTrucksAsync(RegistryScope scope, TruckListQuery query, PageRequest page, CancellationToken ct = default) + { + // searchType TN (default) reads NTP_TRUCKS, TRN reads NTP_TRAILERS (getTruckGrid) + var trailers = string.Equals(query.SearchType, "TRN", StringComparison.OrdinalIgnoreCase); + var table = trailers ? "NTP_TRAILERS" : "NTP_TRUCKS"; + + var where = new StringBuilder(" WHERE s.CODE = t.STATUSCODE AND s.DOMAIN = 'GN' AND t.DOMAIN = 'GN'"); + var p = new DynamicParameters(); + if (scope.IsGoo) where.Append(" AND t.STATUSCODE IN ('OPEN','RVKD','ACCPT','INCOMP','REGREQST')"); + AddScope(where, p, scope, "t"); + if (!string.IsNullOrWhiteSpace(query.Tn)) { where.Append(" AND TO_CHAR(t.TN) = :Tn"); p.Add("Tn", query.Tn.Trim()); } + if (!string.IsNullOrWhiteSpace(query.ChasesNumber)) { where.Append(" AND UPPER(t.CHASESNUMBER) = UPPER(:Chases)"); p.Add("Chases", query.ChasesNumber.Trim()); } + if (!string.IsNullOrWhiteSpace(query.StatusCode)) { where.Append(" AND t.STATUSCODE = :Status"); p.Add("Status", query.StatusCode.Trim()); } + if (!trailers && !string.IsNullOrWhiteSpace(query.HeadType)) { where.Append(" AND t.HEADTYPE = :HeadType"); p.Add("HeadType", query.HeadType.Trim()); } + if (query.Tcscac is not null) { where.Append(" AND t.TCSCAC = :Tcscac"); p.Add("Tcscac", query.Tcscac.Value); } + + var tnId = trailers ? "t.TN_ID" : "NULL"; + var baseSql = $""" + SELECT t.ID AS Id, TO_CHAR(t.TN) AS Tn, t.CHASESNUMBER AS ChasesNumber, t.CREATETIMESTAMP AS CreateTimestamp, + t.REG_DATE AS RegDate, t.CREATEUSERID AS CreateUserId, t.STATUSCODE AS StatusCode, s.DESCRIPTION AS StatusCaption, + getcompanynamefromscac(t.TCSCAC, 62) AS CompName, {tnId} AS TnId + FROM {table} t, STATUS s{where} + """; + + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY t.ID DESC"), p, ct); + foreach (var i in items) i.EntityType = trailers ? "TRN" : "TN"; + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task> SearchTrailersAsync(RegistryScope scope, TrailerListQuery query, PageRequest page, CancellationToken ct = default) + { + var where = new StringBuilder(" WHERE s.CODE = t.STATUSCODE AND s.DOMAIN = 'GN' AND t.DOMAIN = 'GN'"); + var p = new DynamicParameters(); + if (scope.IsGoo) where.Append(" AND t.STATUSCODE IN ('OPEN','RVKD','ACCPT')"); + AddScope(where, p, scope, "t"); + if (!string.IsNullOrWhiteSpace(query.Tn)) { where.Append(" AND TO_CHAR(t.TN) = :Tn"); p.Add("Tn", query.Tn.Trim()); } + if (!string.IsNullOrWhiteSpace(query.ChasesNumber)) { where.Append(" AND UPPER(t.CHASESNUMBER) = UPPER(:Chases)"); p.Add("Chases", query.ChasesNumber.Trim()); } + if (!string.IsNullOrWhiteSpace(query.StatusCode)) { where.Append(" AND t.STATUSCODE = :Status"); p.Add("Status", query.StatusCode.Trim()); } + if (query.Tcscac is not null) { where.Append(" AND t.TCSCAC = :Tcscac"); p.Add("Tcscac", query.Tcscac.Value); } + + var baseSql = $""" + SELECT t.ID AS Id, TO_CHAR(t.TN) AS Tn, t.CHASESNUMBER AS ChasesNumber, t.CREATETIMESTAMP AS CreateTimestamp, + t.REG_DATE AS RegDate, t.CREATEUSERID AS CreateUserId, t.STATUSCODE AS StatusCode, s.DESCRIPTION AS StatusCaption, + getcompanynamefromscac(t.TCSCAC, 62) AS CompName, t.OWNERNAME AS OwnerName, TO_CHAR(t.OWNERNNPN) AS OwnerNnpn + FROM NTP_TRAILERS t, STATUS s{where} + """; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY t.ID DESC"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task> SearchDriversAsync(RegistryScope scope, DriverListQuery query, PageRequest page, CancellationToken ct = default) + { + var where = new StringBuilder(" WHERE s.CODE = t.STATUSCODE AND s.DOMAIN = 'GN' AND t.DOMAIN = 'GN'"); + var p = new DynamicParameters(); + if (scope.IsGoo) where.Append(" AND t.STATUSCODE IN ('OPEN','RVKD')"); + AddScope(where, p, scope, "t"); + if (!string.IsNullOrWhiteSpace(query.Nnpn)) { where.Append(" AND TO_CHAR(t.NNPN) = :Nnpn"); p.Add("Nnpn", query.Nnpn.Trim()); } + if (!string.IsNullOrWhiteSpace(query.Name)) + { + // legacy compared the name for equality; a "contains" match is a superset that is usable for searching + where.Append(@" AND UPPER(t.NAME) LIKE UPPER(:Name) ESCAPE '\'"); + p.Add("Name", "%" + OracleSql.EscapeLike(query.Name.Trim()) + "%"); + } + if (!string.IsNullOrWhiteSpace(query.StatusCode)) { where.Append(" AND t.STATUSCODE = :Status"); p.Add("Status", query.StatusCode.Trim()); } + + var baseSql = $""" + SELECT t.ID AS Id, TO_CHAR(t.NNPN) AS Nnpn, t.NAME AS Name, TO_CHAR(t.DLN) AS Dln, t.DLED AS Dled, + t.CREATETIMESTAMP AS CreateTimestamp, t.CREATEUSERID AS CreateUserId, + getcompanynamefromscac(t.TCSCAC, 62) AS CompName, t.STATUSCODE AS StatusCode, s.DESCRIPTION AS StatusCaption + FROM NTP_DRIVERS t, STATUS s{where} + """; + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) return new PagedResult([], page.SafePage, page.SafePageSize, 0); + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync(OracleSql.Paginate(baseSql + " ORDER BY t.ID DESC"), p, ct); + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task> ListTrailersOfTruckAsync(RegistryScope scope, long? truckId, long? trailerId, CancellationToken ct = default) + { + // getAllTrnOnthisTn: filter by the truck (ID) or, when none, by the trailer (TRNID). The legacy function returned every + // trailer when neither was given; nothing is returned here. + if (truckId is null && trailerId is null) return []; + + var where = new StringBuilder(" WHERE tn.ID(+) = trn.TN_ID AND s.CODE = trn.STATUSCODE AND s.DOMAIN = 'GN'"); + var p = new DynamicParameters(); + if (truckId is not null) { where.Append(" AND tn.ID = :TruckId"); p.Add("TruckId", truckId.Value); } + else { where.Append(" AND trn.ID = :TrailerId"); p.Add("TrailerId", trailerId!.Value); } + if (scope.CompanyOnly) + { + if (scope.CompanyCodeNo is null) where.Append(" AND 1 = 0"); + else { where.Append(" AND trn.TCSCAC = :ScopeScac"); p.Add("ScopeScac", scope.CompanyCodeNo.Value); } + } + if (scope.IsGoo) where.Append(" AND trn.STATUSCODE IN ('OPEN','RVKD','ACCPT')"); + + return await QueryAsync($""" + SELECT trn.ID AS Id, TO_CHAR(trn.TN) AS Tn, trn.CHASESNUMBER AS ChasesNumber, trn.CREATETIMESTAMP AS CreateTimestamp, + trn.REG_DATE AS RegDate, trn.CREATEUSERID AS CreateUserId, trn.STATUSCODE AS StatusCode, + s.DESCRIPTION AS StatusCaption, getcompanynamefromscac(trn.TCSCAC, 62) AS CompName, + trn.OWNERNAME AS OwnerName, TO_CHAR(trn.OWNERNNPN) AS OwnerNnpn + FROM NTP_TRAILERS trn, NTP_TRUCKS tn, STATUS s{where} + ORDER BY trn.ID DESC + """, p, ct); + } + + // ===================================================================================================== trucks + + public Task GetTruckDetailAsync(long id, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT t.ID AS Id, TO_CHAR(t.TN) AS Tn, t.CHASESNUMBER AS ChasesNumber, t.REG_DATE AS RegDate, t.AXIALS AS Axials, + t.STATUSCODE AS StatusCode, s.DESCRIPTION AS StatusCaption, t.OWNERNAME AS OwnerName, + TO_CHAR(t.OWNERNNPN) AS OwnerNnpn, t.COLOR AS Color, t.MODEL AS Model, + TO_CHAR(t.MANIFACTUREYEAR) AS ManifactureYear, TO_CHAR(t.PHONENUMBER) AS PhoneNumber, t.HEADTYPE AS HeadType, + t.TCSCAC AS Tcscac, getcompanynamefromscac(t.TCSCAC, 62) AS CompName, + t.LASTUPDATEUSERID AS LastUpdateUserId, t.LASTUPDATETIMESTAMP AS LastUpdateTimestamp + FROM NTP_TRUCKS t, STATUS s + WHERE s.CODE = t.STATUSCODE AND s.DOMAIN = 'GN' AND t.ID = :Id AND t.DOMAIN = 'GN' + ORDER BY t.ID + """, new { Id = id }, ct); + + public Task GetTruckAsync(long id, CancellationToken ct = default) => + QueryFirstAsync($"SELECT {TruckColumns} FROM NTP_TRUCKS t WHERE t.ID = :Id AND t.DOMAIN = 'GN'", new { Id = id }, ct); + + public Task GetLatestTrailerOfTruckAsync(long truckId, CancellationToken ct = default) => + QueryFirstAsync($""" + SELECT * FROM ( + SELECT {TrailerColumns} + FROM NTP_TRAILERS t + WHERE t.TN_ID = :TruckId AND t.DOMAIN = 'GN' + ORDER BY CASE WHEN t.STATUSCODE = 'RVKD' THEN 1 ELSE 0 END, t.ID DESC + ) WHERE ROWNUM = 1 + """, new { TruckId = truckId }, ct); + + public async Task ActiveTruckExistsAsync(string tn, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM NTP_TRUCKS + WHERE TO_CHAR(TN) = :Tn AND DOMAIN = 'GN' AND STATUSCODE IN ('REGREQST','OPEN','ACCPT') AND ROWNUM = 1 + """, new { Tn = tn }, ct) > 0; + + public async Task InsertTruckAsync(NtpTruck t, CancellationToken ct = default) + { + var p = new DynamicParameters(new + { + t.CreateUserId, t.Tcscac, t.RegDate, t.ChasesNumber, t.Tn, t.StatusCode, t.Axials, t.OwnerName, t.OwnerNnpn, + t.Color, t.Model, t.ManifactureYear, t.PhoneNumber, t.HeadType + }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + await ExecuteAsync(""" + INSERT INTO NTP_TRUCKS + (ID, CREATEUSERID, TCSCAC, REG_DATE, CREATETIMESTAMP, CHASESNUMBER, TN, STATUSCODE, DOMAIN, AXIALS, + OWNERNAME, OWNERNNPN, COLOR, MODEL, MANIFACTUREYEAR, PHONENUMBER, HEADTYPE) + VALUES + (SEQ_NTP_TRUCKS.NEXTVAL, :CreateUserId, :Tcscac, :RegDate, SYSDATE, :ChasesNumber, :Tn, :StatusCode, 'GN', :Axials, + :OwnerName, :OwnerNnpn, :Color, :Model, :ManifactureYear, :PhoneNumber, :HeadType) + RETURNING ID INTO :NewId + """, p, ct); + return OracleSql.ToInt64(p.Get("NewId")); + } + + public async Task UpdateTruckAsync(long id, NtpTruck v, bool updatePhone, string? newStatus, string userId, CancellationToken ct = default) + { + var set = new StringBuilder(""" + COLOR = :Color, REG_DATE = NVL(:RegDate, REG_DATE), OWNERNNPN = :OwnerNnpn, + LASTUPDATETIMESTAMP = SYSDATE, LASTUPDATEUSERID = :UserId, HEADTYPE = :HeadType, + CHASESNUMBER = :ChasesNumber, MANIFACTUREYEAR = :ManifactureYear, MODEL = :Model, AXIALS = :Axials, OWNERNAME = :OwnerName + """); + var p = new DynamicParameters(new + { + v.Color, v.RegDate, v.OwnerNnpn, UserId = userId, v.HeadType, v.ChasesNumber, v.ManifactureYear, v.Model, v.Axials, v.OwnerName, Id = id + }); + if (updatePhone) { set.Append(", PHONENUMBER = :PhoneNumber"); p.Add("PhoneNumber", v.PhoneNumber); } + if (newStatus is not null) { set.Append(", STATUSCODE = :Status"); p.Add("Status", newStatus); } + await ExecuteAsync($"UPDATE NTP_TRUCKS SET {set} WHERE ID = :Id", p, ct); + } + + public Task SetTruckStatusAsync(long id, string status, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE NTP_TRUCKS SET STATUSCODE = :Status, LASTUPDATETIMESTAMP = SYSDATE, LASTUPDATEUSERID = :UserId WHERE ID = :Id + """, new { Status = status, UserId = userId, Id = id }, ct); + + public Task AcceptTruckAsync(long id, string userId, CancellationToken ct = default) => + ExecuteAsync("UPDATE NTP_TRUCKS SET STATUSCODE = 'ACCPT', ACCEPTEDDATE = SYSDATE, ACCEPTEDBY = :UserId WHERE ID = :Id", + new { UserId = userId, Id = id }, ct); + + public Task RevokeTruckAsync(long id, string userId, CancellationToken ct = default) => + ExecuteAsync("UPDATE NTP_TRUCKS SET STATUSCODE = 'RVKD', REVOKEDDATE = SYSDATE, REVOKEDBY = :UserId WHERE ID = :Id", + new { UserId = userId, Id = id }, ct); + + public Task RevokeTrailersOfTruckAsync(long truckId, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE NTP_TRAILERS SET STATUSCODE = 'RVKD', REVOKEDDATE = SYSDATE, REVOKEDBY = :UserId + WHERE TN_ID = :TruckId AND STATUSCODE <> 'RVKD' + """, new { UserId = userId, TruckId = truckId }, ct); + + public Task DeactivateDestinationsAsync(string tn, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE NTP_COMPANY_DISTINATION + SET STATUSCODE = 'INACTIVE', LASTUPDATEUSERID = :UserId, LASTUPDATETIMESTAMP = SYSDATE + WHERE TO_CHAR(TN) = :Tn AND STATUSCODE = 'ACTIVE' AND DOMAIN = 'GN' + """, new { UserId = userId, Tn = tn }, ct); + + public Task RevokeOpenPermitsOfTruckAsync(string tn, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE PERMITS SET SHIPMENTSTATUSCODE = 'RVKD', UPDATEDBY = :UserId, LASTUPDATEDATE = SYSDATE + WHERE TO_CHAR(TN) = :Tn AND SHIPMENTSTATUSCODE = 'OPEN' AND DOMAIN = 'GN' + """, new { UserId = userId, Tn = tn }, ct); + + public async Task TruckHasGnPermitAsync(string tn, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM PERMITS + WHERE DOMAIN = 'GN' AND TO_CHAR(TN) = :Tn AND SHIPMENTSTATUSCODE IN ('PLND','OPEN','RESD','REQST') AND ROWNUM = 1 + """, new { Tn = tn }, ct) > 0; + + // ===================================================================================================== destinations + + public async Task> GetActiveDestinationIdsAsync(string tn, CancellationToken ct = default) + { + var rows = await QueryAsync(""" + SELECT TO_CHAR(t.DESTINATION) FROM NTP_COMPANY_DISTINATION t + WHERE TO_CHAR(t.TN) = :Tn AND t.STATUSCODE = 'ACTIVE' AND t.DOMAIN = 'GN' + """, new { Tn = tn }, ct); + return rows.Select(r => long.TryParse(r, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : (long?)null) + .Where(n => n is not null).Select(n => n!.Value).Distinct().ToList(); + } + + private sealed class PendingRow + { + public string? Login { get; set; } + public string? Created { get; set; } + } + + public async Task GetPendingDestinationAsync(string tn, CancellationToken ct = default) + { + // destinations changed from the mobile app that are not yet INACTIVE (legacy: "will appear after 72 hours") + var row = await QueryFirstAsync(""" + SELECT t.CREATEUSERID AS Login, TO_CHAR(t.CREATETIMESTAMP, 'dd/mm/yyyy hh24:mi') AS Created + FROM NTP_COMPANY_DISTINATION t + WHERE TO_CHAR(t.TN) = :Tn AND t.STATUSCODE <> 'INACTIVE' AND t.DOMAIN = 'GN' + AND t.FROMMOBILE = 1 + ORDER BY t.CREATETIMESTAMP DESC + """, new { Tn = tn }, ct); + return row is null ? null : new PendingDestinationDto { User = row.Login, Time = row.Created }; + } + + public Task InsertDestinationAsync(string tn, long destination, string userId, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO NTP_COMPANY_DISTINATION (ID, TN, STATUSCODE, CREATEUSERID, DOMAIN, DESTINATION) + VALUES (SEQ_NTP_COMPANY_DISTINATION.NEXTVAL, :Tn, 'ACTIVE', :UserId, 'GN', :Destination) + """, new { Tn = tn, UserId = userId, Destination = destination.ToString(CultureInfo.InvariantCulture) }, ct); + + // ===================================================================================================== trailers + + public Task GetTrailerDetailAsync(long id, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT t.ID AS Id, TO_CHAR(t.TN) AS Tn, t.CHASESNUMBER AS ChasesNumber, t.REG_DATE AS RegDate, t.AXIALS AS Axials, + t.STATUSCODE AS StatusCode, s.DESCRIPTION AS StatusCaption, t.OWNERNAME AS OwnerName, + TO_CHAR(t.OWNERNNPN) AS OwnerNnpn, TO_CHAR(t.PHONENUMBER) AS PhoneNumber, t.TN_ID AS TruckId, + t.TCSCAC AS Tcscac, getcompanynamefromscac(t.TCSCAC, 62) AS CompName + FROM NTP_TRAILERS t, STATUS s + WHERE s.CODE = t.STATUSCODE AND s.DOMAIN = 'GN' AND t.ID = :Id AND t.DOMAIN = 'GN' + ORDER BY t.ID + """, new { Id = id }, ct); + + public Task GetTrailerAsync(long id, CancellationToken ct = default) => + QueryFirstAsync($"SELECT {TrailerColumns} FROM NTP_TRAILERS t WHERE t.ID = :Id AND t.DOMAIN = 'GN'", new { Id = id }, ct); + + public async Task ActiveTrailerExistsAsync(string tn, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM NTP_TRAILERS + WHERE TO_CHAR(TN) = :Tn AND DOMAIN = 'GN' + AND STATUSCODE IN ('OPEN','REQST','PLND','ACCPT','RESD','ACTRL','CLOSE') AND ROWNUM = 1 + """, new { Tn = tn }, ct) > 0; + + public async Task TruckHasNonRevokedTrailerAsync(long truckId, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM NTP_TRAILERS WHERE TN_ID = :TruckId AND STATUSCODE <> 'RVKD' AND ROWNUM = 1 + """, new { TruckId = truckId }, ct) > 0; + + public async Task InsertTrailerAsync(NtpTrailer t, CancellationToken ct = default) + { + var p = new DynamicParameters(new + { + t.CreateUserId, t.Tcscac, t.RegDate, t.ChasesNumber, t.Tn, t.StatusCode, t.Axials, t.OwnerName, t.OwnerNnpn, t.PhoneNumber, t.TnId + }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + await ExecuteAsync(""" + INSERT INTO NTP_TRAILERS + (ID, CREATEUSERID, TCSCAC, REG_DATE, CREATETIMESTAMP, CHASESNUMBER, TN, STATUSCODE, DOMAIN, AXIALS, + OWNERNAME, OWNERNNPN, PHONENUMBER, TN_ID) + VALUES + (SEQ_NTP_TRAILERS.NEXTVAL, :CreateUserId, :Tcscac, :RegDate, SYSDATE, :ChasesNumber, :Tn, :StatusCode, 'GN', :Axials, + :OwnerName, :OwnerNnpn, :PhoneNumber, :TnId) + RETURNING ID INTO :NewId + """, p, ct); + return OracleSql.ToInt64(p.Get("NewId")); + } + + public async Task UpdateTrailerAsync(long id, NtpTrailer v, bool updatePhone, string userId, CancellationToken ct = default) + { + var set = new StringBuilder(""" + REG_DATE = :RegDate, OWNERNAME = :OwnerName, OWNERNNPN = :OwnerNnpn, + LASTUPDATETIMESTAMP = SYSDATE, LASTUPDATEUSERID = :UserId, CHASESNUMBER = :ChasesNumber, AXIALS = :Axials, STATUSCODE = 'OPEN' + """); + var p = new DynamicParameters(new { v.RegDate, v.OwnerName, v.OwnerNnpn, UserId = userId, v.ChasesNumber, v.Axials, Id = id }); + if (updatePhone) { set.Append(", PHONENUMBER = :PhoneNumber"); p.Add("PhoneNumber", v.PhoneNumber); } + await ExecuteAsync($"UPDATE NTP_TRAILERS SET {set} WHERE ID = :Id", p, ct); + } + + public Task AcceptTrailerAsync(long id, string userId, CancellationToken ct = default) => + ExecuteAsync("UPDATE NTP_TRAILERS SET STATUSCODE = 'ACCPT', ACCEPTEDDATE = SYSDATE, ACCEPTEDBY = :UserId WHERE ID = :Id", + new { UserId = userId, Id = id }, ct); + + public Task RevokeTrailerAsync(long id, string userId, CancellationToken ct = default) => + ExecuteAsync("UPDATE NTP_TRAILERS SET STATUSCODE = 'RVKD', REVOKEDDATE = SYSDATE, REVOKEDBY = :UserId WHERE ID = :Id", + new { UserId = userId, Id = id }, ct); + + // ===================================================================================================== drivers + + public Task GetDriverDetailAsync(long id, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT t.ID AS Id, TO_CHAR(t.NNPN) AS Nnpn, t.NAME AS Name, TO_CHAR(t.DLN) AS Dln, t.DLED AS Dled, + t.STATUSCODE AS StatusCode, s.DESCRIPTION AS StatusCaption, TO_CHAR(t.NAT) AS Nat, TO_CHAR(t.CAT) AS Cat, + TO_CHAR(t.MOBILE1) AS Mobile1, TO_CHAR(t.MOBILE2) AS Mobile2, t.TCSCAC AS Tcscac + FROM NTP_DRIVERS t, STATUS s + WHERE s.CODE = t.STATUSCODE AND s.DOMAIN = 'GN' AND t.ID = :Id AND t.DOMAIN = 'GN' + ORDER BY t.ID + """, new { Id = id }, ct); + + public Task GetDriverAsync(long id, CancellationToken ct = default) => + QueryFirstAsync($"SELECT {DriverColumns} FROM NTP_DRIVERS t WHERE t.ID = :Id AND t.DOMAIN = 'GN'", new { Id = id }, ct); + + public async Task ActiveDriverExistsAsync(string nnpn, long? excludeId, CancellationToken ct = default) => + await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM NTP_DRIVERS + WHERE TO_CHAR(NNPN) = :Nnpn AND DOMAIN = 'GN' + AND STATUSCODE IN ('OPEN','REQST','PLND','ACCPT','RESD','ACTRL','CLOSE') + AND (:ExcludeId IS NULL OR ID <> :ExcludeId) AND ROWNUM = 1 + """, new { Nnpn = nnpn, ExcludeId = excludeId }, ct) > 0; + + public async Task InsertDriverAsync(NtpDriver d, CancellationToken ct = default) + { + var p = new DynamicParameters(new { d.Nnpn, d.Name, d.Dln, d.Dled, d.Tcscac, d.StatusCode, d.CreateUserId, d.Nat, d.Cat, d.Mobile1, d.Mobile2 }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + await ExecuteAsync(""" + INSERT INTO NTP_DRIVERS + (ID, NNPN, NAME, DLN, DLED, TCSCAC, STATUSCODE, CREATETIMESTAMP, DOMAIN, CREATEUSERID, NAT, CAT, MOBILE1, MOBILE2) + VALUES + (SEQ_NTP_DRIVERS.NEXTVAL, :Nnpn, :Name, :Dln, :Dled, :Tcscac, :StatusCode, SYSDATE, 'GN', :CreateUserId, :Nat, :Cat, :Mobile1, :Mobile2) + RETURNING ID INTO :NewId + """, p, ct); + return OracleSql.ToInt64(p.Get("NewId")); + } + + public Task AcceptDriverAsync(long id, string userId, CancellationToken ct = default) => + ExecuteAsync("UPDATE NTP_DRIVERS SET STATUSCODE = 'ACCPT', ACCEPTEDDATE = SYSDATE, ACCEPTEDBY = :UserId WHERE ID = :Id AND DOMAIN = 'GN'", + new { UserId = userId, Id = id }, ct); + + public Task RevokeDriverAsync(long id, string userId, CancellationToken ct = default) => + ExecuteAsync("UPDATE NTP_DRIVERS SET STATUSCODE = 'RVKD', REVOKEDDATE = SYSDATE, REVOKEDBY = :UserId WHERE ID = :Id AND DOMAIN = 'GN'", + new { UserId = userId, Id = id }, ct); + + // ===================================================================================================== attachments + + public Task InsertFileAsync(string attachmentType, long entityId, string originalName, string fileName, CancellationToken ct = default) => + ExecuteAsync(""" + INSERT INTO GRAINS_FILES (ID, ATTACHMENTTYPE, ENTITYID, ORIGINALNAME, FILENAME) + VALUES (SEQ_GRAINS_FILES.NEXTVAL, :Type, :EntityId, :OriginalName, :FileName) + """, new { Type = attachmentType, EntityId = entityId, OriginalName = originalName, FileName = fileName }, ct); + + public Task> GetFilesAsync(long entityId, string attachmentType, CancellationToken ct = default) => + QueryAsync(""" + SELECT ENTITYID AS EntityId, ATTACHMENTTYPE AS AttachmentType, ORIGINALNAME AS OriginalName, FILENAME AS FileName + FROM GRAINS_FILES + WHERE ENTITYID = :EntityId AND ATTACHMENTTYPE = :Type + ORDER BY ID + """, new { EntityId = entityId, Type = attachmentType }, ct); + + public Task FindFileAsync(string attachmentType, string fileName, CancellationToken ct = default) => + QueryFirstAsync(""" + SELECT ENTITYID AS EntityId, ATTACHMENTTYPE AS AttachmentType, ORIGINALNAME AS OriginalName, FILENAME AS FileName + FROM GRAINS_FILES + WHERE FILENAME = :FileName AND ATTACHMENTTYPE = :Type + ORDER BY ID + """, new { FileName = fileName, Type = attachmentType }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistrySettingsService.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistrySettingsService.cs new file mode 100644 index 0000000..02151ff --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Registry/RegistrySettingsService.cs @@ -0,0 +1,67 @@ +using Microsoft.Extensions.Configuration; +using NTP.Application.Grains.Registry; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Registry; + +/// +/// Settings of the registry slice (configuration section Grains:Registry; falls back to Grains:Permits for the values both +/// slices share, then to defaults). Replaces legacy ColdFusion application-scope variables that are NOT in the repository, so every +/// default below is UNVERIFIED and must be confirmed against the live server: +/// +/// BadiyaScac (application.GN_BadiyaSCAC) = 327 +/// AllowedTruckStatuses (application.GN_ALLOWEDSTATUSES) = OPEN, ACCPT +/// BadiyaOwnershipCodes / OthersOwnershipCodes (application.GN_BadyahOwnership / GN_OthersOwnership): empty = ownership check skipped +/// DistributionShift1..3 (application.grnsdtrbutnshft_N "start,end") = 6,18 / 18,30 / 30,42 +/// TempUploadPath / UploadedFilesPath (application.tempuploadedfiles / uploadedfiles, legacy /var/www/NTP/...) +/// +/// +internal sealed class RegistrySettingsService(IConfiguration config) : IRegistrySettingsService +{ + private const string Section = "Grains:Registry"; + private const string PermitsSection = "Grains:Permits"; + + private static readonly int[][] DefaultShifts = [[6, 18], [18, 30], [30, 42]]; + private static readonly string[] DefaultExtensions = ["pdf", "png", "jpg", "jpeg", "gif", "tif", "tiff", "bmp", "doc", "docx"]; + + public long BadiyaScac => + long.TryParse(config[$"{Section}:BadiyaScac"] ?? config[$"{PermitsSection}:BadiyaScac"], out var v) ? v : 327; + + public IReadOnlyList AllowedTruckStatuses => + Array($"{Section}:AllowedTruckStatuses") ?? Array($"{PermitsSection}:AllowedStatuses") ?? ["OPEN", "ACCPT"]; + + public IReadOnlyList BadiyaOwnershipCodes => + Array($"{Section}:BadiyaOwnershipCodes") ?? Array($"{PermitsSection}:BadiyaOwnershipCodes") ?? []; + + public IReadOnlyList OthersOwnershipCodes => + Array($"{Section}:OthersOwnershipCodes") ?? Array($"{PermitsSection}:OtherOwnershipCodes") ?? []; + + public (int Start, int End) ShiftHours(int shift) + { + var n = shift is >= 1 and <= 3 ? shift : 1; + var arr = Ints($"{Section}:DistributionShift{n}") ?? Ints($"{PermitsSection}:DistributionShift{n}") ?? DefaultShifts[n - 1]; + return arr.Length >= 2 ? (arr[0], arr[1]) : (DefaultShifts[n - 1][0], DefaultShifts[n - 1][1]); + } + + public string TempUploadPath => + config[$"{Section}:TempUploadPath"] is { Length: > 0 } p ? p : Path.Combine(AppContext.BaseDirectory, "App_Data", "tempuploadedfiles"); + + public string UploadedFilesPath => + config[$"{Section}:UploadedFilesPath"] is { Length: > 0 } p ? p : Path.Combine(AppContext.BaseDirectory, "App_Data", "uploadedfiles"); + + public long MaxUploadBytes => + long.TryParse(config[$"{Section}:MaxUploadBytes"], out var v) && v > 0 ? v : 10L * 1024 * 1024; + + public IReadOnlyList AllowedUploadExtensions => Array($"{Section}:AllowedUploadExtensions") ?? DefaultExtensions; + + private string[]? Array(string key) + { + var values = config.GetSection(key).Get(); + return values is { Length: > 0 } ? values : null; + } + + private int[]? Ints(string key) + { + var values = config.GetSection(key).Get(); + return values is { Length: > 0 } ? values : null; + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/GrainsReportsConfig.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/GrainsReportsConfig.cs new file mode 100644 index 0000000..3c928ea --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/GrainsReportsConfig.cs @@ -0,0 +1,34 @@ +using Microsoft.Extensions.Configuration; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Reports; + +/// +/// Configuration of the reports slice (read from the "GrainsReports" section; no shared file is edited): +/// +/// "GrainsReports": { +/// "DistributionShifts": { "1": { "Start": 0, "End": 8 }, "2": { "Start": 8, "End": 16 } }, // legacy application.grnsdtrbutnshft_N (hours) +/// "Ws": { "ApiKeys": [ "..." ], "EnableSaveShipmentInfo": false }, +/// "Watcher": { "Enabled": false, "Directory": "D:\silos\ir", "ArchiveDirectory": "D:\ArchiveFiles\ir", "IntervalSeconds": 60 } +/// } +/// +/// +public sealed class GrainsReportsConfig(IConfiguration configuration) +{ + private IConfigurationSection Root => configuration.GetSection("GrainsReports"); + + /// legacy application['grnsdtrbutnshft_N'] = "start,end" (hours); null when not configured. + public (int Start, int End)? Shift(int shift) + { + var s = Root.GetSection($"DistributionShifts:{shift}"); + if (!int.TryParse(s["Start"], out var a) || !int.TryParse(s["End"], out var b)) return null; + return (a, b); + } + + public IReadOnlyList ApiKeys => Root.GetSection("Ws:ApiKeys").Get() ?? []; + public bool SaveShipmentInfoEnabled => Root.GetValue("Ws:EnableSaveShipmentInfo", false); + + public bool WatcherEnabled => Root.GetValue("Watcher:Enabled", false); + public string? WatcherDirectory => Root["Watcher:Directory"]; + public string? WatcherArchive => Root["Watcher:ArchiveDirectory"]; + public int WatcherIntervalSeconds => Math.Max(5, Root.GetValue("Watcher:IntervalSeconds", 60)); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/PhoneApprovalRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/PhoneApprovalRepository.cs new file mode 100644 index 0000000..583a6d7 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/PhoneApprovalRepository.cs @@ -0,0 +1,131 @@ +using System.Data; +using Dapper; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using NTP.Application.Abstractions; +using NTP.Application.Grains.Reports; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Reports; + +/// +/// DB part of grains.cfc addPhoneAcceptEvent / addPhoneRejectEvent / BL_addToBlacklist as used by the IVR approvals file import. +/// Not ported: the mobile push notification (MobileNotifications.PrepareNotificationMessage). +/// +internal sealed class PhoneApprovalRepository(IDbSession session, IEventLogger events, IConfiguration configuration, + ILogger logger) : OracleRepositoryBase(session, logger), IPhoneApprovalRepository +{ + private readonly GrainsReportsConfig _config = new(configuration); + + private sealed class PermitRow + { + public long Id { get; set; } + public long? Scrn { get; set; } + public string? Tn { get; set; } + public string? Pn { get; set; } + public string? CompanyCode { get; set; } + public long? TrackingNo { get; set; } + } + + private sealed class OrderRow + { + public long? CargoType { get; set; } + public long? Location { get; set; } + public int? Shift { get; set; } + public decimal? DateDiff { get; set; } + } + + private Task GetPermit(long id, CancellationToken ct) => QueryFirstAsync(""" + select id as Id, scrn as Scrn, tn as Tn, to_char(pn) as Pn, to_char(companycode) as CompanyCode, trackingno as TrackingNo + from permits where id = :Id + """, new { Id = id }, ct); + + private Task GetOrder(long id, CancellationToken ct) => QueryFirstAsync(""" + select cargotype as CargoType, location as Location, shift as Shift, sysdate - orderdate as DateDiff + from grainstenderorder where id = :Id + """, new { Id = id }, ct); + + public async Task AcceptAsync(long permitId, string? remarks, string userId, CancellationToken ct) + { + var permit = await GetPermit(permitId, ct); + if (permit is null) return new(false, "PERMIT_NOT_FOUND", "الإرسالية غير موجودة"); + if (permit.Scrn is null) return new(false, "PERMIT_NOT_DISTRIBUTED", "الإرسالية غير موزعة على طلبية"); + var order = await GetOrder(permit.Scrn.Value, ct); + if (order is null) return new(false, "ORDER_NOT_FOUND", "الطلبية غير موجودة"); + + var already = await ExecuteScalarAsync(""" + select count(*) from TRUCK_DISTRIBUTION_LOG where STATUSCODE = 'CLOSE' and PERMITID = :Pid and ORDERID = :Oid + """, new { Pid = permitId.ToString(), Oid = permit.Scrn.Value.ToString() }, ct); + if (already > 0) return new(false, "ALREADY_ACCEPTED", "تمت الموافقة مسبقا من مستخدم تطبيق نافذ"); + + var text = remarks ?? " تمت الموافقة هاتفيا ، تم تحديد الوجهة " + + $"{GrainsOrderLabels.CargoTypeLabel(order.CargoType)} - {GrainsOrderLabels.LocationLabel(order.Location)}"; + + await events.AddAsync(new EventEntry("PERMITID", permitId, "REQST", "REQST", userId, "PHACCPT", "GN", "", "NTP", null, + new Dictionary { ["REMARKS"] = text }), ct); + + await ExecuteAsync(""" + update TRUCK_DISTRIBUTION_LOG set STATUSCODE = 'CLOSE', UPDATEDATE = sysdate, NOTES = :Notes, ISBLOCKED = 0 + where PERMITID = :Pid and ORDERID = :Oid and statuscode = 'PENDING' + """, new { Notes = text, Pid = permitId.ToString(), Oid = permit.Scrn.Value.ToString() }, ct); + + return new(true, "OK", "تمت العملية بنجاح"); + } + + public async Task RejectAsync(long permitId, int delayDays, string remarks, string userId, CancellationToken ct) + { + var permit = await GetPermit(permitId, ct); + if (permit is null) return new(false, "PERMIT_NOT_FOUND", "الإرسالية غير موجودة"); + + // ---- BL_addToBlacklist (CATEGORY PHONEDECLINE, ENTITYTYPE PERMIT, ENTITYNUM = permit id) + var order = permit.Scrn is { } scrn ? await GetOrder(scrn, ct) : null; + var shift = order?.Shift ?? 1; + var window = _config.Shift(shift); + if (window is null) + return new(false, "SHIFT_CONFIG_MISSING", $"لم يتم إعداد أوقات التوزيع للشفت {shift} (GrainsReports:DistributionShifts)"); + + var expiry = await ExecuteScalarAsync( + "select trunc(sysdate - (24 + :S) / 24) + :Days + :E / 24 from dual", new { S = window.Value.Start, Days = delayDays, E = window.Value.End }, ct); + var blRemarks = remarks + "، سيتم فك الانتظار بشكل تلقائي بتاريخ " + expiry.ToString("MM/dd/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture); + await ExecuteAsync(""" + insert into GRAINSBLACKLIST (ID, CATEGORY, ENTITYTYPE, ENTITYID, CREATEDBY, EXPIRYDATE, STATUSCODE, REMARKS, LASTUPDATEUSER, LASTUPDATEDATE) + values (SEQ_GRAINSBLACKLIST.nextval, 'PHONEDECLINE', 'PERMIT', :EntityId, :UserId, :Expiry, 'OPEN', :Remarks, :UserId, sysdate) + """, new { EntityId = permitId.ToString(), UserId = userId, Expiry = expiry, Remarks = blRemarks }, ct); + + // ---- queue counters: before midnight of the order date the company's queue position is given back + if (order is not null && permit.TrackingNo is { } queueId && order.DateDiff is < 0) + { + await ExecuteAsync("update GRAINS_COMPANIES_QUEUE set counter = counter - 1 where id = :Id", new { Id = queueId }, ct); + if (permit.CompanyCode != GrainsReportConstants.BadiyaScac) + { + var queueCode = await QueryFirstAsync("select code from GRAINS_COMPANIES_QUEUE where id = :Id", new { Id = queueId }, ct); + if (queueCode == "GALLAB") + await ExecuteAsync(""" + update GRAINS_COMPANIES_QUEUE set counter = counter - 1 where id in ( + select id from ( + select t.*, rank() over (order by t.counter desc, t.id desc) r + from GRAINS_COMPANIES_QUEUE t + where scac = :Scac and code = 'BULK' and type = 'COMP' and counter < 1000) + where r = 1) + """, new { Scac = permit.CompanyCode }, ct); + } + } + + // ---- permit goes back to OPEN + await ExecuteAsync(""" + update PERMITS set SHIPMENTSTATUSCODE = 'OPEN', SCRN = null, UPDATEDBY = :UserId, LASTUPDATEDATE = sysdate, trackingno = null + where id = :Id + """, new { UserId = userId, Id = permitId }, ct); + + // newer OPEN permits of the same truck/type are revoked so the truck never has two open permits + await ExecuteAsync(""" + update permits set isActive = 'N', SHIPMENTSTATUSCODE = 'RVKD', UPDATEDBY = :UserId, LASTUPDATEDATE = sysdate, trackingno = null + where id > :Id and domain = 'GN' and SHIPMENTSTATUSCODE = 'OPEN' + and tn = (select tn from permits where id = :Id) and tt = (select tt from permits where id = :Id) + """, new { UserId = userId, Id = permitId }, ct); + + await events.AddAsync(new EventEntry("PERMITID", permitId, "REQST", "OPEN", userId, "PHRJCT", "GN", "", "NTP", null, + new Dictionary { ["REMARKS"] = remarks }), ct); + + return new(true, "OK", "تمت العملية بنجاح.اضيفت الارسالية الى قائمة المنع"); + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/ReportsRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/ReportsRepository.cs new file mode 100644 index 0000000..f3f1027 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/ReportsRepository.cs @@ -0,0 +1,563 @@ +using System.Globalization; +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Common; +using NTP.Application.Grains.Reports; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Reports; + +/// +/// SQL of reports.cfc and the Reports\*.cfm pages (bind variables everywhere). The .cfr templates are encrypted, so their +/// queries are re-derived from what the calling page passes (marked "INFERRED"). +/// +internal sealed class ReportsRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IReportsRepository +{ + private const string CargoDecode = """ + decode(ct.code, 'BULK.BARLY', 'شعير سائب', 'PCKD.BARLY', 'شعير مشول', 'BULK.WHEAT', 'قمح سائب', 'PCKD.WHEAT', 'قمح مشول', ct.code) + """; + + private const string TripStatuses = "('CLOSE', 'RESD', 'ACCPT', 'ACTRL')"; + + private static DateTime Day(DateOnly d) => d.ToDateTime(TimeOnly.MinValue); + + private async Task>> RowsAsync(string sql, object? p, CancellationToken ct) + { + var rows = await QueryAsync(sql, p, ct); + return rows.Select(r => (IDictionary)(IDictionary)r).ToList(); + } + + // ------------------------------------------------------------------ lookups + + public Task> CompaniesAsync(CancellationToken ct) => QueryAsync(""" + select to_char(t.scac) as Value, t.scac || '-' || getcompanynamefromscac(t.scac, 62) as Label + from NTP_TENDERS_COMPANIES t + where t.statuscode = 'ACTIVE' + order by decode(t.scac, 327, 1, t.scac) + """, null, ct); + + public Task> CargoTypesAsync(CancellationToken ct) => QueryAsync( + "select to_char(id) as Value, name as Label from cargotype where domain = 'GN' order by id", null, ct); + + public Task> DestinationsAsync(IReadOnlyList gnTypes, CancellationToken ct) + { + var p = new DynamicParameters(); + var names = new List(); + for (var i = 0; i < gnTypes.Count; i++) { names.Add(":G" + i); p.Add("G" + i, gnTypes[i]); } + return QueryAsync($""" + select to_char(id) as Value, name as Label from LOCATIONS + where domain = 'GN' and type = 'EX' and status = 1 and gn_type in ({string.Join(",", names)}) + order by name + """, p, ct); + } + + // ------------------------------------------------------------------ reports.cfc + + public Task> TripsPerCompanyAsync(DateOnly from, DateOnly to, CancellationToken ct) => + QueryAsync($""" + with q1 as + (select count(*) ctrips, t.tn, getcompanynamefromscac(t.companycode, 62) scac, t.companycode + from permits t + where t.domain = 'GN' + and t.shipmentstatuscode in {TripStatuses} + and t.lastupdatedate >= :FromDate + and t.lastupdatedate <= :ToDate + 1 + group by t.tn, t.companycode), + q2 as + (select nc.companyshare, nc.scac from NTP_TENDERS_COMPANIES nc where nc.statuscode = 'ACTIVE') + select q1.scac as Scac, + to_char(q1.companycode) as CompanyCode, + sum(q1.ctrips) as AllTripNum, + count(q1.tn) as NumOfTruk, + q2.companyshare as CompanyShare, + decode(q1.companycode, '327', 0, round(avg(q2.companyshare / 583 * 100), 3)) as AvgShare, + decode(q1.companycode, '327', 70, round(avg(q2.companyshare / 583 * 100) / 3.3333, 3)) as TotalShare, + round(count(q1.tn) / nullif(q2.companyshare, 0) * 100, 2) as AvgTotalTrucks, + round(sum(q1.ctrips) / + nullif((select count(*) from permits g + where g.domain = 'GN' + and g.shipmentstatuscode in {TripStatuses} + and g.lastupdatedate >= :FromDate + and g.lastupdatedate <= :ToDate + 1), 0) * 100, 3) as AvrgTrips + from q1, q2 + where q2.scac = q1.companycode + group by q1.scac, q2.companyshare, q1.companycode + """, new { FromDate = Day(from), ToDate = Day(to) }, ct); + + public async Task> FrequencyAsync(DateOnly from, DateOnly to, string? scac, string? cargoType, CancellationToken ct) + { + var cols = string.Join(",\n", Enumerable.Range(1, GrainsReportConstants.MaxTripsBucket).Select(i => $"nvl(sum(decode(c, {i}, 1, 0)), 0) as T{i}")); + var sql = new StringBuilder($""" + select {cols} + from (select count(distinct t.id) c, t.tn + from permits t, events e + where t.domain = 'GN' + and t.id = e.permitid + and e.eventtype = 'ASSIGNDEST' + and e.eventdate >= :FromDate + and e.eventdate <= :ToDate + 1 + """); + var p = new DynamicParameters(new { FromDate = Day(from), ToDate = Day(to) }); + if (!string.IsNullOrEmpty(cargoType)) { sql.Append(" and t.shipmentmode = :CargoType"); p.Add("CargoType", cargoType); } + if (!string.IsNullOrEmpty(scac)) { sql.Append(" and t.companycode = :Scac"); p.Add("Scac", scac); } + sql.Append(" group by t.tn)"); + var row = (await RowsAsync(sql.ToString(), p, ct)).FirstOrDefault(); + var result = new long[GrainsReportConstants.MaxTripsBucket]; + if (row is not null) + for (var i = 0; i < result.Length; i++) + result[i] = row.TryGetValue("T" + (i + 1), out var v) && v is not null and not DBNull ? Convert.ToInt64(v, CultureInfo.InvariantCulture) : 0; + return result; + } + + public Task> DetailsAsync(DateOnly from, DateOnly to, CancellationToken ct) => + QueryAsync($""" + select getcompanynamefromscac(t.companycode, 62) as Scac, t.tn as Tn, count(*) as Tt + from permits t + where t.domain = 'GN' + and t.shipmentstatuscode in {TripStatuses} + and t.lastupdatedate >= :FromDate + and t.lastupdatedate <= :ToDate + 1 + group by t.tn, t.companycode + order by t.companycode, t.tn + """, new { FromDate = Day(from), ToDate = Day(to) }, ct); + + public Task> WeighbridgeEventsAsync(DateOnly from, DateOnly to, long? locationId, CancellationToken ct) + { + var p = new DynamicParameters(new { FromDate = Day(from), ToDate = Day(to) }); + var loc = ""; + if (locationId is not null) { loc = " and loc.id = :LocId"; p.Add("LocId", locationId); } + return QueryAsync($""" + select p.id as Pid, p.pn as Pn, p.tn as Tn, loc.name as Loc, loc.id as LocationId, + e.eventtype as EventType, to_char(e.weight) as Weight, + getcompanynamefromscac(p.companycode, 62) as Scac, + {CargoDecode} as CargoType, + p.drvr as Drvr, p.nnpn as Nnpn, + to_char(e.eventdate, 'dd/mm/yyyy') as EventDate, + loc2.name as OriginAddressId + from permits p, events e, cargotype ct, locations loc, locations loc2, events le + where p.domain = 'GN' + and le.eventdate >= :FromDate and le.eventdate < :ToDate + 1 + and e.permitid(+) = p.id + and e.eventtype(+) in ('DTW', 'DGW', 'LTW', 'LGW', 'DNW', 'LNW') + and ct.domain = 'GN' + and p.shipmentmode = ct.id + and loc.id = p.destinationaddressid + and loc2.id = p.originaddressid + and le.permitid = p.id + and le.eventtype = 'ASSIGNDEST'{loc} + order by p.id, e.id + """, p, ct); + } + + // ------------------------------------------------------------------ table reports + + public Task>> TableAsync(string key, ReportFilter f, ReportScope s, CancellationToken ct) => key switch + { + ReportKeys.ClosedPermits => ClosedPermits(f, s, ct), + ReportKeys.LoadingWeights => LoadingWeights(f, s, ct), + ReportKeys.Incapability => Incapability(f, s, ct), + ReportKeys.WaybridgeSummary => Waybridge(f, s, summary: true, ct), + ReportKeys.WaybridgeDetails => Waybridge(f, s, summary: false, ct), + ReportKeys.TenderOrder => TenderOrder(f, s, ct), + ReportKeys.DistributionSummary => DistributionSummary(f, ct), + ReportKeys.CallList => CallList(f, ct), + ReportKeys.CompaniesTurn => CompaniesTurn(f, ct), + ReportKeys.OwnersTurn => OwnersTurn(f, ct), + ReportKeys.Drivers => Drivers(f, s, ct), + ReportKeys.Trucks => Trucks(f, s, ct), + ReportKeys.OrderDistribution => OrderDistribution(f, ct), + ReportKeys.MotGrainCube => TcsOnly(MotCube(f, ct)), + ReportKeys.MotGrainFrequency => TcsOnly(MotFrequency(f, ct)), + _ => throw new NotFoundException("Report", key) + }; + + /// + /// motrpts.cfc reads the legacy TCS datasource "NTPTCS" (SHIPMENT* tables, getloc/getcomp/gettn), which is a third database + /// that this API has no connection to (and the QA database does not contain). Surface that as a clear business error. + /// + private static async Task>> TcsOnly(Task>> query) + { + try { return await query; } + catch (Exception e) when (e.Message.Contains("ORA-00942") || e.Message.Contains("ORA-00904") || e.Message.Contains("ORA-06575")) + { + throw new BusinessException("MOT_TCS_UNAVAILABLE", "مصدر بيانات النظام القديم (NTPTCS) غير متاح لهذا التقرير"); + } + } + + private static DynamicParameters Range(ReportFilter f) => + new(new { FromDate = Day(f.From!.Value), ToDate = Day(f.To!.Value) }); + + private static bool IsDestVisitor(ReportScope s) => string.Equals(s.RoleCode, "GNDSTV", StringComparison.OrdinalIgnoreCase); + + /// INFERRED from closedPermits.cfr usage (page grainsReports i=8: date range only). + private Task>> ClosedPermits(ReportFilter f, ReportScope s, CancellationToken ct) + { + var p = Range(f); + var visitor = ""; + if (IsDestVisitor(s)) { visitor = " and loc.id = :LocId"; p.Add("LocId", s.LocationId ?? -1); } + return RowsAsync($""" + select p.pn as pn, p.tn as tn, getcompanynamefromscac(p.companycode, 62) as company, + {CargoDecode} as cargoType, loc2.name as origin, loc.name as destination, + p.drvr as drvr, p.nnpn as nnpn, p.lastupdatedate as closeDate + from permits p, cargotype ct, locations loc, locations loc2 + where p.domain = 'GN' and p.shipmentstatuscode = 'CLOSE' + and ct.domain = 'GN' and p.shipmentmode = ct.id + and loc.id = p.destinationaddressid and loc2.id = p.originaddressid + and p.lastupdatedate >= :FromDate and p.lastupdatedate < :ToDate + 1{visitor} + order by p.lastupdatedate, p.id + """, p, ct); + } + + /// INFERRED from weightsReport.cfr (page grainsReports i=7: date range only): loading weights per permit. + private Task>> LoadingWeights(ReportFilter f, ReportScope s, CancellationToken ct) + { + var p = Range(f); + var visitor = ""; + if (IsDestVisitor(s)) { visitor = " and loc.id = :LocId"; p.Add("LocId", s.LocationId ?? -1); } + return RowsAsync($""" + select p.pn as pn, p.tn as tn, getcompanynamefromscac(p.companycode, 62) as company, + {CargoDecode} as cargoType, loc2.name as origin, loc.name as destination, + max(decode(e.eventtype, 'LTW', to_number(e.weight))) as tare, + max(decode(e.eventtype, 'LGW', to_number(e.weight))) as gross, + max(decode(e.eventtype, 'LNW', to_number(e.weight))) as net, + min(e.eventdate) as eventDate + from permits p, events e, cargotype ct, locations loc, locations loc2 + where p.domain = 'GN' and e.permitid = p.id and e.eventtype in ('LTW', 'LGW', 'LNW') + and ct.domain = 'GN' and p.shipmentmode = ct.id + and loc.id = p.destinationaddressid and loc2.id = p.originaddressid + and e.eventdate >= :FromDate and e.eventdate < :ToDate + 1{visitor} + group by p.id, p.pn, p.tn, p.companycode, ct.code, loc2.name, loc.name + order by min(e.eventdate), p.id + """, p, ct); + } + + /// INFERRED from GRINS_INCAPABILITY.cfr (page grainsReports i=6: order-date range): permits with their load/discharge weights. + private Task>> Incapability(ReportFilter f, ReportScope s, CancellationToken ct) + { + var p = Range(f); + var visitor = ""; + if (IsDestVisitor(s)) { visitor = " and loc.id = :LocId"; p.Add("LocId", s.LocationId ?? -1); } + return RowsAsync($""" + select p.pn as pn, p.tn as tn, getcompanynamefromscac(p.companycode, 62) as company, + {CargoDecode} as cargoType, loc.name as destination, o.orderdate as orderDate, + max(decode(e.eventtype, 'LTW', to_number(e.weight))) as ltw, + max(decode(e.eventtype, 'LGW', to_number(e.weight))) as lgw, + max(decode(e.eventtype, 'LNW', to_number(e.weight))) as lnw, + max(decode(e.eventtype, 'DTW', to_number(e.weight))) as dtw, + max(decode(e.eventtype, 'DGW', to_number(e.weight))) as dgw, + max(decode(e.eventtype, 'DNW', to_number(e.weight))) as dnw + from permits p, events e, cargotype ct, locations loc, grainstenderorder o + where p.domain = 'GN' and p.shipmentstatuscode = 'CLOSE' + and e.permitid = p.id and e.eventtype in ('LTW', 'LGW', 'LNW', 'DTW', 'DGW', 'DNW') + and ct.domain = 'GN' and p.shipmentmode = ct.id + and loc.id = p.destinationaddressid and o.id = p.scrn + and o.orderdate >= :FromDate and o.orderdate < :ToDate + 1{visitor} + group by p.id, p.pn, p.tn, p.companycode, ct.code, loc.name, o.orderdate + order by p.id + """, p, ct); + } + + /// INFERRED from Grains_WayBridge.cfr / Grains_DetailsWayBridge.cfr (page wayBridgeReport: event type + date range). + private Task>> Waybridge(ReportFilter f, ReportScope s, bool summary, CancellationToken ct) + { + var p = Range(f); + var types = "e.eventtype in ('LTW', 'LGW', 'DTW', 'DGW')"; + if (f.EventType is "LTW" or "LGW" or "DTW" or "DGW") { types = "e.eventtype = :EventType"; p.Add("EventType", f.EventType); } + var visitor = ""; + if (IsDestVisitor(s)) { visitor = " and e.locationid = :LocId"; p.Add("LocId", s.LocationId ?? -1); } + var where = $""" + from events e, permits p, cargotype ct, locations loc + where e.permitid = p.id and p.domain = 'GN' and {types} + and ct.domain = 'GN' and p.shipmentmode = ct.id and loc.id(+) = e.locationid + and e.eventdate >= :FromDate and e.eventdate < :ToDate + 1{visitor} + """; + return summary + ? RowsAsync($""" + select getcompanynamefromscac(p.companycode, 62) as company, {CargoDecode} as cargoType, + count(*) as trips, sum(to_number(e.weight)) as totalWeight + {where} + group by p.companycode, ct.code + order by p.companycode, ct.code + """, p, ct) + : RowsAsync($""" + select p.pn as pn, p.tn as tn, getcompanynamefromscac(p.companycode, 62) as company, {CargoDecode} as cargoType, + e.eventtype as eventType, loc.name as location, to_number(e.weight) as weight, + e.eventdate as eventDate, e.doneby as doneBy + {where} + order by e.eventdate, e.id + """, p, ct); + } + + /// tenderOrderReport_xls.cfm (same data as the tender order grid). + private Task>> TenderOrder(ReportFilter f, ReportScope s, CancellationToken ct) + { + var p = new DynamicParameters(); + var joinOrders = f.ShipmentStatusCode != "OPEN"; + var sql = new StringBuilder(""" + select distinct t.id as id, t.pn as pn, t.tn as tn, t.trackingno as trackingNo, t.creationdate as creationDate, + (select min(ll.name) from locations ll where ll.id = t.destinationaddressid and ll.domain = 'GN') as destinationAddressId, + t.drvr as drvr, + getcompanynamefromscac(t.companycode, 62) as compName, + getstatuscaption(t.shipmentstatuscode, 'GN', null) as statusCaption, + t.shipmentstatuscode as shipmentStatusCode, + (select distinct first_value(e.remarks) over(order by id desc) from events e + where e.permitid = t.id and e.eventtype in ('PHACCPT', 'PHRJCT')) as phoneAccpt, + (select distinct first_value(e.remarks) over(order by id desc) from events e + where e.permitid = t.id and e.eventtype = 'OVRD' and e.prevstatus = 'OPEN' and e.currentstatus = 'REQST') as remarks, + (select distinct first_value(tn.phonenumber) over(order by id desc) from ntp_trucks tn + where t.tn = tn.tn and tn.domain = 'GN' and tn.statuscode in ('OPEN', 'ACCPT')) as phoneNumber, + case when mod(TDEST.cnt, 100) = 0 then 'سائب' + when TDEST.cnt < 100 then 'مشول' + when TDEST.cnt is null then ' ' + else 'سائب+مشول' end as type, + (select getlocationname(destenation, 'GN') from GRAINSTENDERORDER where id = t.scrn) as destName, + decode(t.companycode, 327, to_char(t.creationdate, 'dd/mm/yyyy') || '-' || t.tripcounter, null) as queueNo + from PERMITS t, + (select * from status where domain = 'GN') status, + (select sum(decode(ntp_company_distination.destination, 215, 100, 220, 100, 225, 100, 1)) cnt, tn + from ntp_company_distination where ntp_company_distination.statuscode = 'ACTIVE' + group by ntp_company_distination.tn) TDEST, + """); + if (joinOrders) sql.Append(" (select id, o.cargotype from grainstenderorder o) o,"); + sql.Append(""" + cargoType ct + where t.domain = 'GN' and t.isactive = 'Y' + """); + if (joinOrders) sql.Append(" and o.id = t.scrn and o.cargotype = ct.id"); + sql.Append(""" + + and t.shipmentstatuscode in ('REQST','PLND','OPEN','ACCPT','RESD','ACTRL','CLOSE','RVKD','CLRPR') + and t.shipmentstatuscode = status.code(+) + and TDEST.tn(+) = t.tn + """); + if (s.StkId == 62) { sql.Append(" and t.companycode = :OwnCompany"); p.Add("OwnCompany", s.CompanyCodeNo ?? -1); } + if (!string.IsNullOrWhiteSpace(f.Scac)) { sql.Append(" and t.companycode = :Scac"); p.Add("Scac", f.Scac.Trim()); } + if (f.OrderDate is not null) + { + sql.Append(" and t.scrn in (select id from GRAINSTENDERORDER x where x.orderdate = :OrderDate)"); + p.Add("OrderDate", Day(f.OrderDate.Value)); + } + if (!string.IsNullOrWhiteSpace(f.Tn)) { sql.Append(" and t.tn = :Tn"); p.Add("Tn", f.Tn.Trim()); } + if (!string.IsNullOrEmpty(f.ShipmentStatusCode)) { sql.Append(" and t.shipmentstatuscode = :Status"); p.Add("Status", f.ShipmentStatusCode); } + if (f.DestAddressId is not null) { sql.Append(" and t.destinationaddressid = :Dest"); p.Add("Dest", f.DestAddressId); } + if (DateOnly.TryParse(f.CreationDate, out var cd)) { sql.Append(" and t.creationdate = :CreationDate"); p.Add("CreationDate", Day(cd)); } + if (!string.IsNullOrEmpty(f.Tt)) { sql.Append(" and listgetat(t.tt, 1, '.') = :Tt"); p.Add("Tt", f.Tt); } + sql.Append(" and t.creationdate > to_date('1/1/2020', 'dd/mm/yyyy') order by t.pn"); + return RowsAsync(sql.ToString(), p, ct); + } + + /// distributionSummary.cfm. + private Task>> DistributionSummary(ReportFilter f, CancellationToken ct) + { + var p = new DynamicParameters(new { OrderDate = Day(f.OrderDate!.Value) }); + string ct1; + if (string.Equals(f.ShipmentMode, "BULK", StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(f.ShipmentMode)) + ct1 = "o.ct in ('BULK', 'BULK_GALLAB')"; + else { ct1 = "o.ct = :Ct"; p.Add("Ct", f.ShipmentMode); } + return RowsAsync($""" + select c.name as name, + decode(o.MOBILE_SHIFT, 1, 'الشفت الصباحي', 2, 'الشفت المسائي', 3, 'الشفت الليلي') as shift, + to_char(o.orderdate, 'dd/mm/yyyy') as orderDate, count(*) as cnt + from PERMITS t, GRAINSTENDERORDER o, NTP_TENDERS_COMPANIES c + where t.shipmentstatuscode in ('REQST', 'RESD', 'PLND', 'ACCPT') and t.domain = 'GN' + and o.id = t.scrn and o.orderdate = :OrderDate + and c.scac = t.companycode and c.statuscode = 'ACTIVE' + and t.creationdate > to_date('1/1/2020', 'dd/mm/yyyy') + and {ct1} + group by c.name, o.Mobile_shift, to_char(o.orderdate, 'dd/mm/yyyy') + order by c.name + """, p, ct); + } + + /// callRpt.cfm (IVR call list for REQST permits that were not phone-accepted yet). + private Task>> CallList(ReportFilter f, CancellationToken ct) + { + var p = new DynamicParameters(); + var sql = new StringBuilder(""" + select distinct t.tn as name, + '0' || (select distinct first_value(tn.phonenumber) over(order by id desc) from ntp_trucks tn + where t.tn = tn.tn and tn.domain = 'GN' and tn.statuscode in ('OPEN', 'ACCPT')) as phone, + 'C:\\' || substr(trim(t.tn), 1, 1) || '.wav' as code1, + 'C:\\' || substr(trim(t.tn), 2, 1) || '.wav' as code2, + 'C:\\' || substr(trim(t.tn), 3, 1) || '.wav' as number1, + 'C:\\' || nvl(substr(trim(t.tn), 4, 1), 'E') || '.wav' as number2, + 'C:\\' || nvl(substr(trim(t.tn), 5, 1), 'E') || '.wav' as number3, + 'C:\\' || nvl(substr(trim(t.tn), 6, 1), 'E') || '.wav' as number4, + 'C:\\' || nvl(substr(trim(t.tn), 7, 1), 'E') || '.wav' as number5, + 'C:\\GN' || o.cargotype || '.wav' as item, + 'C:\\GN' || '.wav' as fromDist, + 'C:\\' || nvl(to_char(o.location), 'E') || '.wav' as origin, + 'C:\\d' || trim(to_char((o.orderdate + 1), 'D')) || '.wav' as week, + 'C:\\' || decode(substr(trim(to_char((o.orderdate), 'dd')), 0, 1), '0', + substr(trim(to_char((o.orderdate), 'dd')), 2, 1), trim(to_char((o.orderdate), 'dd'))) || '.wav' as day, + 'C:\\m' || decode(substr(trim(to_char((o.orderdate), 'mm')), 0, 1), '0', + substr(trim(to_char((o.orderdate), 'mm')), 2, 1), trim(to_char((o.orderdate), 'mm'))) || '.wav' as month, + t.shipmentstatuscode as shipmentStatusCode, t.id as id, o.mobile_shift as mobileShift + from PERMITS t, GRAINSTENDERORDER o, (select * from status where domain = 'GN') status, cargoType ct + where o.id = t.scrn and t.domain = 'GN' and t.isactive = 'Y' + and o.cargotype = ct.id + and t.shipmentstatuscode = status.code(+) + and t.shipmentstatuscode in ('REQST') + """); + if (f.OrderDate is not null) { sql.Append(" and o.orderdate = :OrderDate"); p.Add("OrderDate", Day(f.OrderDate.Value)); } + if (!string.IsNullOrWhiteSpace(f.Tn)) { sql.Append(" and t.tn = :Tn"); p.Add("Tn", f.Tn.Trim()); } else sql.Append(" and t.tn is not null"); + if (!string.IsNullOrEmpty(f.ShipmentStatusCode)) { sql.Append(" and t.shipmentstatuscode = :Status"); p.Add("Status", f.ShipmentStatusCode); } + if (f.DestAddressId is not null) { sql.Append(" and o.destenation = :Dest"); p.Add("Dest", f.DestAddressId); } + if (!string.IsNullOrWhiteSpace(f.Scac)) { sql.Append(" and t.companycode = :Scac"); p.Add("Scac", f.Scac.Trim()); } + if (!string.IsNullOrEmpty(f.Tt)) { sql.Append(" and t.tt like :Tt"); p.Add("Tt", OracleSql.EscapeLike(f.Tt) + "%"); sql.Append(@" escape '\'"); } + sql.Append(""" + + and not exists (select id from + (select RANK() OVER (PARTITION BY ee.permitid ORDER BY ee.id desc) ranking, ee.* + from events ee + where ee.permitid in (select permitid from events e where e.eventtype in ('PHACCPT')) + and ee.eventtype in ('PHRJCT', 'PHACCPT')) + where ranking = 1 and eventtype in ('PHACCPT') and permitid = t.id) + """); + return RowsAsync(sql.ToString(), p, ct); + } + + /// INFERRED from companiesTurnReport_xls.cfr (params: code = BULK|PCKD|GALLAB, distributionType = COMP|AHALI|all). + private Task>> CompaniesTurn(ReportFilter f, CancellationToken ct) + { + var code = (f.ShipmentMode ?? "BULK").ToUpperInvariant(); + var p = new DynamicParameters(new { Code = code }); + var type = ""; + if (!string.IsNullOrWhiteSpace(f.DistributionType) && !f.DistributionType.Equals("all", StringComparison.OrdinalIgnoreCase)) + { type = " and t.type = :Type"; p.Add("Type", f.DistributionType.ToUpperInvariant()); } + return RowsAsync($""" + select rank() over (order by t.counter, t.id) as turn, to_char(t.scac) as scac, + getcompanynamefromscac(t.scac, 62) as company, t.code as code, t.type as type, t.counter as counter + from GRAINS_COMPANIES_QUEUE t, NTP_TENDERS_COMPANIES c + where c.scac = t.scac and c.statuscode = 'ACTIVE' and t.code = :Code{type} + order by turn, t.id + """, p, ct); + } + + /// INFERRED from ownersTurnReport_xls.cfr (params: code = BULK|PCKD, DEST = destination location id): individual trucks assigned to the destination ordered by trips done. + private Task>> OwnersTurn(ReportFilter f, CancellationToken ct) => + RowsAsync(""" + select rank() over (order by count(p.id), cd.tn) as turn, cd.tn as tn, count(p.id) as trips, max(p.lastupdatedate) as lastTrip + from ntp_company_distination cd, ntp_trucks tr, permits p + where cd.statuscode = 'ACTIVE' and cd.destination = :Dest + and tr.tn = cd.tn and tr.domain = 'GN' and tr.statuscode in ('OPEN', 'ACCPT') and tr.tcscac = 327 + and p.tn(+) = cd.tn and p.domain(+) = 'GN' and p.destinationaddressid(+) = cd.destination + and p.shipmentstatuscode(+) in ('CLOSE', 'RESD', 'ACCPT', 'ACTRL') + group by cd.tn + order by turn, cd.tn + """, new { Dest = f.DestAddressId }, ct); + + /// DriversReport_xls.cfr: same query and filters as the registered-drivers grid (register.cfc getDriverGrid). + private Task>> Drivers(ReportFilter f, ReportScope s, CancellationToken ct) + { + var p = new DynamicParameters(); + var sql = new StringBuilder(""" + select t.nnpn as nnpn, t.name as name, t.dln as dln, to_char(t.dled, 'dd/mm/yyyy') as dled, + getcompanynamefromscac(t.tcscac, 62) as company, status.description as status, + to_char(t.createtimestamp, 'dd/mm/yyyy') as createDate, t.createuserid as createUser + from NTP_DRIVERS t, status + where status.code = t.statuscode and status.domain = 'GN' and t.domain = 'GN' + """); + if (string.Equals(s.RoleCode, "GOO", StringComparison.OrdinalIgnoreCase)) sql.Append(" and t.statuscode in ('OPEN', 'RVKD')"); + if (s.StkId == 62) { sql.Append(" and t.tcscac = :OwnCompany"); p.Add("OwnCompany", s.CompanyCodeNo ?? -1); } + if (!string.IsNullOrWhiteSpace(f.Nnpn)) { sql.Append(" and t.nnpn = :Nnpn"); p.Add("Nnpn", f.Nnpn.Trim()); } + if (!string.IsNullOrWhiteSpace(f.StatusCode)) { sql.Append(" and t.statuscode = :StatusCode"); p.Add("StatusCode", f.StatusCode.Trim()); } + if (!string.IsNullOrWhiteSpace(f.Name)) { sql.Append(" and t.name = :Name"); p.Add("Name", f.Name.Trim()); } + sql.Append(" order by t.id"); + return RowsAsync(sql.ToString(), p, ct); + } + + /// TruckReport_xls.cfr: same query and filters as the registered-trucks grid (register.cfc getTruckGrid, TN search). + private Task>> Trucks(ReportFilter f, ReportScope s, CancellationToken ct) + { + var p = new DynamicParameters(); + var sql = new StringBuilder(""" + select distinct t.tn as tn, t.id as id, t.chasesnumber as chasesNumber, + to_char(t.createtimestamp, 'dd/mm/yyyy') as createDate, to_char(t.reg_date, 'dd/mm/yyyy') as regDate, + t.createuserid as createUser, getcompanynamefromscac(t.tcscac, 62) as company, status.description as status + from NTP_TRUCKS t, status + where status.code = t.statuscode and status.domain = 'GN' and t.domain = 'GN' + """); + if (s.StkId == 62) { sql.Append(" and t.tcscac = :OwnCompany"); p.Add("OwnCompany", s.CompanyCodeNo ?? -1); } + if (!string.IsNullOrWhiteSpace(f.Tn)) { sql.Append(" and t.tn = :Tn"); p.Add("Tn", f.Tn.Trim()); } + if (!string.IsNullOrWhiteSpace(f.StatusCode)) { sql.Append(" and t.statuscode = :StatusCode"); p.Add("StatusCode", f.StatusCode.Trim()); } + if (!string.IsNullOrWhiteSpace(f.ChasesNumber)) { sql.Append(" and t.chasesnumber = :Chases"); p.Add("Chases", f.ChasesNumber.Trim()); } + if (!string.IsNullOrWhiteSpace(f.HeadType)) { sql.Append(" and t.headtype = :HeadType"); p.Add("HeadType", f.HeadType.Trim()); } + if (!string.IsNullOrWhiteSpace(f.Scac)) { sql.Append(" and t.tcscac = :Scac"); p.Add("Scac", f.Scac.Trim()); } + sql.Append(" order by t.id"); + return RowsAsync(sql.ToString(), p, ct); + } + + /// grainsOrder.cfm: bulk orders of a date pivoted by destination (COMP / AHALE). + private Task>> OrderDistribution(ReportFilter f, CancellationToken ct) => + RowsAsync(""" + select * from (select getlocationname(t.destenation, 'GN') dest, t.type, sum(t.quantity) quant + from GRAINSTENDERORDER t + where ct in ('BULK', 'BULK_GALLAB') and t.orderdate = :OrderDate and t.statuscode = 'ACTIVE' + group by type, getlocationname(t.destenation, 'GN')) + pivot (sum(quant) for type in ('COMP' as company, 'AHALE' as ahale)) + order by dest + """, new { OrderDate = Day(f.OrderDate!.Value) }, ct); + + // ------------------------------------------------------------------ MOT (motrpts.cfc / MotDAO.cfc) + + public Task> MotMultiTripsAsync(CancellationToken ct) => + QueryAsync(""" + select mm as Mm, regtype as RegType, case when cnt <= 25 then cnt else 0 end as Trips, + count(*) as TnFreq, sum(cnt) as TripFreq + from (select to_char(t.creationdate, 'yyyy-mm') mm, regType, TN, count(*) cnt + from grainsPermits t + group by to_char(t.creationdate, 'yyyy-mm'), regType, TN) + group by mm, regtype, case when cnt <= 25 then cnt else 0 end + order by 2, 1, 3 + """, null, ct); + + private Task>> MotCube(ReportFilter f, CancellationToken ct) => + RowsAsync(""" + select getloc(S.DestinationAddressId) as loc, getcomp(s.shipmentid) as company, + count(distinct TN.shipmentreferencevalue) as trucks, + count(distinct decode(a.headregtype, 3, TN.shipmentreferencevalue, 0)) as cTrucks, + count(distinct TRN.shipmentreferencevalue) as trails, + count(distinct decode(a.trailregtype, 3, TRN.shipmentreferencevalue, 0)) as cTrails, + count(distinct PN.shipmentreferencevalue) as trips, + count(distinct decode(a.trailregtype, 3, PN.shipmentreferencevalue, 0)) as cTrips + from shipment S, shipmentreference PN, shipmentreference TN, shipmentreference TRN, shipmentreference TRNAT, shipmenttruckregtype a + where S.SHIPMENTID = PN.SHIPMENTID and PN.SHIPMENTREFERENCETYPECODE = 'PN' + and S.SHIPMENTID = TN.SHIPMENTID and TN.SHIPMENTREFERENCETYPECODE = 'TN' + and S.SHIPMENTID = TRN.SHIPMENTID and TRN.SHIPMENTREFERENCETYPECODE = 'TRN' + and S.SHIPMENTID = TRNAT.SHIPMENTID and S.SHIPMENTID = A.SHIPMENTID(+) + and TRNAT.SHIPMENTREFERENCETYPECODE = 'ASRN' + and TRNAT.shipmentreferencevalue in ('201200012000', '201200052158') + and S.DestinationAddressId in (20, 30) + and PN.createtimestamp >= :FromDate and PN.createtimestamp < :ToDate + 1 + group by cube(getloc(S.DestinationAddressId), getcomp(s.shipmentid)) + """, Range(f), ct); + + private Task>> MotFrequency(ReportFilter f, CancellationToken ct) + { + string Side(int reg) => $""" + (select distinct c, count(*) over (partition by c) cnt, + round(count(*) over (partition by c) * 1000 / count(*) over (partition by 1)) / 10 perc + from (select GETTN(SR.SHIPMENTID) as tn, nvl(max(a.headregtype), 1) a, count(distinct S.SHIPMENTID) c + from SHIPMENTREFERENCE SR, INVOLVEDPARTY I, SHIPMENT S, COMMODITYCLASSTYPE c, shipmenttruckregtype a + where SR.SHIPMENTID = I.SHIPMENTID and S.SHIPMENTID = SR.SHIPMENTID + and s.shipmentmode = c.commodityclasstypecode + and SR.SHIPMENTID in (select SR.SHIPMENTID from SHIPMENTREFERENCE SR + where SR.SHIPMENTREFERENCETYPECODE = 'ASRN' + and SR.SHIPMENTREFERENCEVALUE in ('201200012000', '201200052158')) + and S.SHIPMENTID = A.SHIPMENTID(+) + and SR.SHIPMENTREFERENCETYPECODE = 'PN' and I.involvedpartytypecode = 'DRVR' + and SR.CREATETIMESTAMP >= :FromDate and SR.CREATETIMESTAMP < :ToDate + 1 + and nvl(a.headregtype, 1) = {reg} + group by GETTN(SR.SHIPMENTID))) + """; + return RowsAsync($""" + select nvl(cont.c, comp.c) as c, nvl(cont.cnt, 0) as contCnt, nvl(cont.perc, 0) as contPerc, + nvl(comp.cnt, 0) as compCnt, nvl(comp.perc, 0) as compPerc + from {Side(1)} comp + full outer join {Side(3)} cont on cont.c = comp.c + order by 1 + """, Range(f), ct); + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/WeighbridgeFileRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/WeighbridgeFileRepository.cs new file mode 100644 index 0000000..5ebce82 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/WeighbridgeFileRepository.cs @@ -0,0 +1,142 @@ +using System.Globalization; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Reports; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Reports; + +/// SQL of ReadFiles\* (TEMP_WAYBRIDGE* tables) and of jobs/getWeighbridgeEvents.cfm (WEIGHBRIDGE_RAW_DATA). +internal sealed class WeighbridgeFileRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IWeighbridgeFileRepository +{ + private static DateTime? Date(string s) + { + s = (s ?? "").Replace("00:00:00.0", "").Trim(); + return DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.None, out var d) ? d.Date : null; + } + + private static object IrbidParams(IrbidRecord r) => new + { + r.Id, r.F1, r.F2, r.F3, F4 = Date(r.F4), r.F5, r.F6, F7 = Date(r.F7), r.F8, r.F9, r.Wid, r.FileName, r.Location + }; + + public async Task IrbidExistsAsync(string location, string fileName, string id, CancellationToken ct) => + await ExecuteScalarAsync(""" + select count(*) from TEMP_WAYBRIDGE_IRBID where location = :Location and fileName = :FileName and id = :Id and rownum = 1 + """, new { Location = location, FileName = fileName, Id = id }, ct) > 0; + + public Task InsertIrbidAsync(IrbidRecord r, CancellationToken ct) => ExecuteAsync(""" + insert into TEMP_WAYBRIDGE_IRBID (ID, F1, F2, F3, F4, F5, F6, F7, F8, F9, WID, fileName, location) + values (:Id, :F1, :F2, :F3, :F4, :F5, :F6, :F7, :F8, :F9, :Wid, :FileName, :Location) + """, IrbidParams(r), ct); + + // Legacy updated WHERE WID = ... (WID restarts at 1 in every file, so it could hit other files' rows); keyed here by the same + // (location, fileName, id) that the "exists" check uses. + public Task UpdateIrbidAsync(IrbidRecord r, CancellationToken ct) => ExecuteAsync(""" + update TEMP_WAYBRIDGE_IRBID + set F1 = :F1, F2 = :F2, F3 = :F3, F4 = :F4, F5 = :F5, F6 = :F6, F7 = :F7, F8 = :F8, F9 = :F9, WID = :Wid + where location = :Location and fileName = :FileName and id = :Id + """, IrbidParams(r), ct); + + public Task DeleteAllIrbidAsync(CancellationToken ct) => ExecuteAsync("delete from TEMP_WAYBRIDGE_IRBID", null, ct); + + public async Task StageRsifehAsync(IReadOnlyList rows, CancellationToken ct) + { + if (rows.Count == 0) return 0; + await ExecuteAsync("delete from TEMP_WAYBRIDGE_TEMP where FILENAME = :F", new { F = rows[0].FileName }, ct); + var n = 0; + foreach (var r in rows) + { + var wid = await ExecuteScalarAsync("select TEMP_WAYBRIDGE_ID.nextval from dual", null, ct); + n += await ExecuteAsync(""" + insert into TEMP_WAYBRIDGE_TEMP (ID, FILENAME, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, WID) + values (:Id, :FileName, :F1, :F2, :F3, :F4, :F5, :F6, :F7, :F8, :F9, :F10, :F11, :F12, :F13, :Wid) + """, new { r.Id, r.FileName, r.F1, r.F2, r.F3, r.F4, r.F5, r.F6, r.F7, r.F8, r.F9, r.F10, r.F11, r.F12, r.F13, Wid = wid }, ct); + } + return n; + } + + public async Task PromoteNewRsifehAsync(string fileName, CancellationToken ct) + { + // "updated records on TN": same record id in the same file but another truck number + await ExecuteAsync(""" + update TEMP_WAYBRIDGE w + set w.F1 = (select max(t.F1) from TEMP_WAYBRIDGE_TEMP t where t.ID = w.ID and t.FILENAME = w.FILENAME) + where w.FILENAME = :F + and exists (select 1 from TEMP_WAYBRIDGE_TEMP t where t.ID = w.ID and t.FILENAME = w.FILENAME and t.F1 <> w.F1) + """, new { F = fileName }, ct); + + return await ExecuteAsync(""" + insert into TEMP_WAYBRIDGE (ID, FILENAME, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, WID) + select t.ID, t.FILENAME, t.F1, t.F2, t.F3, t.F4, t.F5, t.F6, t.F7, t.F8, t.F9, t.F10, t.F11, t.F12, t.F13, t.WID + from TEMP_WAYBRIDGE_TEMP t + where t.FILENAME = :F + and not exists (select 1 from TEMP_WAYBRIDGE w where w.ID = t.ID and w.FILENAME = t.FILENAME) + """, new { F = fileName }, ct); + } + + // ------------------------------------------------------------------ WEIGHBRIDGE_RAW_DATA + + public Task> UnmatchedRawAsync(CancellationToken ct) => QueryAsync(""" + select rowidtochar(rowid) as TransId, locationid as LocationId, cargo_truck_no as CargoTruckNo, + to_char(cargo_time_in, 'yyyymmddHH24miss') as GinTime, to_char(cargo_time_out, 'yyyymmddHH24miss') as GoutTime, + cargo_weight_in as CargoWeightIn, cargo_weight_out as CargoWeightOut + from WEIGHBRIDGE_RAW_DATA t + where t.permitid is null and cargo_weight_net > 0 and t.locationid <> 205 + order by cargo_time_out desc + """, null, ct); + + public async Task FindPermitForRawAsync(string truckNo, CancellationToken ct) + { + var r = await QueryFirstAsync(""" + select id as Id, shipmentstatuscode as ShipmentStatusCode from permits t + where t.tn = :Tn and domain = 'GN' and t.shipmentstatuscode in ('ACTRL', 'CLRPR', 'ACTWT') + order by id desc + """, new { Tn = truckNo }, ct); + return r is null ? null : new RawPermit(r.Id, r.ShipmentStatusCode); + } + + /// getPermitNumber(): the permit whose ASSIGNDEST period contains the entry time (+2h), not yet weighed at discharge. + public async Task FindPermitByTimeAsync(string truckNo, string ginTime, string tt, CancellationToken ct) + { + var r = await QueryFirstAsync(""" + with p1 as + (select p.id, tn, pn, DRVR, eventdate, p.shipmentstatuscode, rank() over (partition by tn order by p.id, e.id) r + from permits p, events e + where p.domain = 'GN' and p.tt = :Tt and e.permitid = P.id and p.tn = :Tn and e.domain = 'GN' + and e.eventtype = 'ASSIGNDEST' and p.shipmentstatuscode in ('RESD', 'ACTRL', 'CLRPR', 'CLOSE')), + p2 as + (select p.id, tn, eventdate, rank() over (partition by tn order by p.id, e.id) r + from permits p, events e + where p.domain = 'GN' and p.tt = :Tt and e.permitid = P.id and p.tn = :Tn and e.domain = 'GN' + and e.eventtype = 'ASSIGNDEST' and p.shipmentstatuscode in ('RESD', 'ACTRL', 'CLRPR', 'CLOSE')) + select p1.id as Id, p1.shipmentstatuscode as ShipmentStatusCode + from p1, p2 + where p2.tn(+) = p1.tn and p2.r(+) = p1.r + 1 + and to_date(:D, 'yyyymmddHH24miss') + 2 / 24 between p1.eventdate and nvl(p2.eventdate, sysdate) + and not exists (select id from events e where e.permitid = p1.id and e.eventtype in ('DGW', 'DTW')) + order by p1.id desc + """, new { Tn = truckNo, D = ginTime, Tt = tt }, ct); + return r is null ? null : new RawPermit(r.Id, r.ShipmentStatusCode); + } + + public Task SetRawPermitAsync(string rowId, long permitId, CancellationToken ct) => ExecuteAsync( + "update WEIGHBRIDGE_RAW_DATA set permitID = :P where rowid = chartorowid(:R)", new { P = permitId, R = rowId }, ct); + + public async Task InsertRawEventsAndCloseAsync(RawWeighbridgeRow raw, RawPermit permit, CancellationToken ct) + { + const string insert = """ + insert into events (id, permitid, eventdate, eventtype, prevstatus, currentstatus, doneby, locationid, domain, updatedtype, remarks, weight) + values (SEQ_events.nextval, :PermitId, to_date(:D, 'yyyymmddHH24miss'), :Type, :Prev, :Curr, :DoneBy, :Loc, 'GN', 'WINT', null, :Weight) + """; + var doneBy = "W" + raw.LocationId; + await ExecuteAsync(insert, new { PermitId = permit.Id, D = raw.GinTime, Type = "DGW", Prev = permit.ShipmentStatusCode, Curr = permit.ShipmentStatusCode, DoneBy = doneBy, Loc = raw.LocationId, Weight = raw.CargoWeightIn }, ct); + await ExecuteAsync(insert, new { PermitId = permit.Id, D = raw.GoutTime, Type = "DTW", Prev = permit.ShipmentStatusCode, Curr = "CLOSE", DoneBy = doneBy, Loc = raw.LocationId, Weight = raw.CargoWeightOut }, ct); + await ExecuteAsync("update permits p set p.shipmentStatusCode = 'CLOSE', p.lastupdatedate = sysdate where id = :Id", new { Id = permit.Id }, ct); + } + + private sealed class PermitRow + { + public long Id { get; set; } + public string ShipmentStatusCode { get; set; } = ""; + } +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/WsRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/WsRepository.cs new file mode 100644 index 0000000..aefc8eb --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/Grains/Reports/WsRepository.cs @@ -0,0 +1,147 @@ +using System.Data; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Grains.Reports; + +namespace NTP.Infrastructure.Persistence.Repositories.Grains.Reports; + +/// SQL of ws.cfc (IDs come from seq_<TABLE>.nextval, like the legacy addDBRecordNOORM helper). +internal sealed class WsRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IWsRepository +{ + private sealed class QuotaRow { public decimal? Total { get; set; } public decimal? Done { get; set; } } + private sealed class WbPermitRow + { + public long Id { get; set; } + public string ShipmentStatusCode { get; set; } = ""; + public long? OriginAddressId { get; set; } + public long? DestinationAddressId { get; set; } + } + + public Task CloseActivePermitsAsync(string tn, string user, CancellationToken ct) => ExecuteAsync(""" + update PERMITS t set t.SHIPMENTSTATUSCODE = 'CLOSE', t.UPDATEDBY = :UserId, t.LASTUPDATEDATE = sysdate + where t.domain = 'GN' and t.tn = :Tn + and t.SHIPMENTSTATUSCODE in (select code from status where isactive = 1 and domain = 'GN' and code != 'QUED') + """, new { UserId = user, Tn = tn }, ct); + + public Task FindQueuedAsync(string tn, CancellationToken ct) => QueryFirstAsync(""" + select to_char(pn) as Pn, creationdate as CreationDate from PERMITS t + where t.domain = 'GN' and t.tn = :Tn and t.SHIPMENTSTATUSCODE = 'QUED' + order by t.id + """, new { Tn = tn }, ct); + + public async Task<(long TrackNo, string QueueDate)> NextTrackingNoAsync(CancellationToken ct) + { + for (var i = 0; i <= 6; i++) + { + var day = DateTime.Today.AddDays(i); + var max = await ExecuteScalarAsync(""" + select nvl(max(PN), 0) from PERMITS t + where t.creationdate between :D and :D + 1 and domain = 'GN' and shipmentstatuscode = 'QUED' + """, new { D = day }, ct); + var q = await QueryFirstAsync(""" + select sum(t.quota) as Total, sum(t.donequota) as Done from DESTINATION_QUOTA t + where quotadate = :D and isactive = 1 + """, new { D = day }, ct); + // legacy: (done + max) < total; NULL sums make the comparison false (CF would have raised) -> try the next day + if (q?.Total is { } total && (q.Done ?? 0) + max < total) + return (max + 1, day.ToString("dd-MM-yyyy")); + } + return (0, ""); + } + + public async Task InsertQueuedPermitAsync(string tn, string trnat, long pn, string queueDate, CancellationToken ct) + { + var p = new DynamicParameters(new { Tn = tn, Trnat = trnat, Pn = pn, D = queueDate }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + await ExecuteAsync(""" + insert into PERMITS (ID, TN, DOMAIN, TRNAT, CREATEDBY, SHIPMENTSTATUSCODE, PN, CREATIONDATE) + values (SEQ_PERMITS.NEXTVAL, :Tn, 'GN', :Trnat, 'TCSWS', 'QUED', :Pn, to_date(:D, 'dd-mm-yyyy')) + returning ID into :NewId + """, p, ct); + return OracleSql.ToInt64(p.Get("NewId")); + } + + public Task> OpenPermitIdsAsync(string tn, CancellationToken ct) => QueryAsync( + "select id from PERMITS where domain = 'GN' and TN = :Tn and shipmentstatuscode = 'OPEN' order by id", new { Tn = tn }, ct); + + public Task UpdateStatusByTnAsync(string tn, string fromStatus, string toStatus, string user, CancellationToken ct) => ExecuteAsync(""" + update PERMITS set shipmentstatuscode = :ToStatus, UPDATEDBY = :UserId, LASTUPDATEDATE = sysdate + where domain = 'GN' and TN = :Tn and shipmentstatuscode = :FromStatus + """, new { ToStatus = toStatus, UserId = user, Tn = tn, FromStatus = fromStatus }, ct); + + public Task TruckCompanyIfRegisteredAsync(string tn, CancellationToken ct) => QueryFirstAsync(""" + select to_char(t.tcscac) from NTP_TRUCKS t + where TN = :Tn and t.domain = 'GN' and t.statuscode in ('OPEN', 'ACCPT') + order by t.id desc + """, new { Tn = tn }, ct); + + public async Task HasActivePermitAsync(string tn, string tt, bool checkAllStatuses, CancellationToken ct) + { + var statuses = checkAllStatuses ? "('REQST', 'PLND', 'OPEN')" : "('OPEN')"; + var n = await ExecuteScalarAsync($""" + select count(*) from PERMITS t + where t.tn = :Tn and t.shipmentstatuscode in {statuses} and t.domain = 'GN' and t.TT = :Tt and rownum = 1 + """, new { Tn = tn, Tt = tt }, ct); + return n > 0; + } + + public Task NextQueueSequenceAsync(bool badiya, CancellationToken ct) => ExecuteScalarAsync( + badiya ? "select SEQ_GRAINS_TRACKINGNO_OWN.nextval from dual" : "select SEQ_GRAINS_TRACKINGNO_CO.nextval from dual", null, ct); + + public Task TripCounterAsync(string tt, CancellationToken ct) => ExecuteScalarAsync(""" + select nvl(max(TRIPCOUNTER), 0) + 1 from permits p + where domain = 'GN' and TT = :Tt and CREATIONDATE > trunc(sysdate) and P.COMPANYCODE = 327 + """, new { Tt = tt }, ct); + + public Task TenderCountAsync(CancellationToken ct) => ExecuteScalarAsync( + "select nvl(max(id), 0) from NTP_TENDER t where domain = 'GN'", null, ct); + + public async Task InsertPermitAsync(NewPermit p, CancellationToken ct) + { + var d = new DynamicParameters(new { p.Pn, p.Tn, p.CompanyCode, p.StatusCode, p.Tt, p.TripCounter }); + d.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + await ExecuteAsync(""" + insert into PERMITS (ID, PN, TN, COMPANYCODE, SHIPMENTSTATUSCODE, DOMAIN, TT, TRIPCOUNTER) + values (SEQ_PERMITS.NEXTVAL, :Pn, :Tn, :CompanyCode, :StatusCode, 'GN', :Tt, :TripCounter) + returning ID into :NewId + """, d, ct); + return OracleSql.ToInt64(d.Get("NewId")); + } + + public async Task PermitExistsAsync(long pid, CancellationToken ct) => + await ExecuteScalarAsync("select count(*) from PERMITS where id = :Id", new { Id = pid }, ct) > 0; + + public Task UpdatePermitStatusAsync(long pid, string status, string user, CancellationToken ct) => ExecuteAsync(""" + update PERMITS set SHIPMENTSTATUSCODE = :Status, UPDATEDBY = :UserId, LASTUPDATEDATE = sysdate where id = :Id + """, new { Status = status, UserId = user, Id = pid }, ct); + + public async Task PermitIdByPnAsync(string pn, CancellationToken ct) => + await QueryFirstAsync("select id from PERMITS where PN = :Pn order by id", new { Pn = pn }, ct); + + public Task UpdateShipmentModeAsync(long pid, string cargoType, CancellationToken ct) => ExecuteAsync( + "update PERMITS set SHIPMENTMODE = :Mode where id = :Id", new { Mode = cargoType, Id = pid }, ct); + + public async Task FindWbPermitAsync(string tn, CancellationToken ct) + { + var r = await QueryFirstAsync(""" + select P.id as Id, P.SHIPMENTSTATUSCODE as ShipmentStatusCode, + nvl(P.ORIGINADDRESSID, O.LOCATION) as OriginAddressId, P.DESTINATIONADDRESSID as DestinationAddressId + from PERMITS P, Grainstenderorder O + where P.domain = 'GN' and P.Scrn = O.ID(+) and P.TN = :Tn + and P.SHIPMENTSTATUSCODE in ('ACCPT', 'RESD', 'ACTRL', 'CLRPR') + order by P.id desc + """, new { Tn = tn }, ct); + return r is null ? null : new WbPermit(r.Id, r.ShipmentStatusCode, r.OriginAddressId, r.DestinationAddressId); + } + + public Task InsertWbEventAsync(WsWbEventInsert e, CancellationToken ct) => ExecuteAsync(""" + insert into events (id, permitid, eventdate, eventtype, prevstatus, currentstatus, doneby, locationid, domain, updatedtype, remarks, weight) + values (SEQ_events.nextval, :PermitId, nvl(:EventDate, sysdate), :EventType, :Prev, :Curr, :DoneBy, :LocationId, 'GN', 'WINT', null, :Weight) + """, new { e.PermitId, e.EventDate, e.EventType, Prev = e.PrevStatus, Curr = e.CurrentStatus, e.DoneBy, e.LocationId, e.Weight }, ct); + + public Task LogIntegrationAsync(string? ip, string tn, string argsJson, CancellationToken ct) => ExecuteAsync(""" + insert into GN_TCS_INTEGRATION (ID, IPADDRESS, TN, EVENTDATE, ARGS) + values (seq_GN_TCS_INTEGRATION.nextval, :Ip, :Tn, sysdate, :Args) + """, new { Ip = ip, Tn = tn, Args = argsJson }, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/LookupRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/LookupRepository.cs new file mode 100644 index 0000000..0fc74f1 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/LookupRepository.cs @@ -0,0 +1,57 @@ +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Lookups; + +namespace NTP.Infrastructure.Persistence.Repositories; + +/// Generic lookups used by many legacy pages (info.getLookupTable calls on STATUS, LOCATIONS, CARGOTYPE, COMPANIES ...). +internal sealed class LookupRepository(IDbSession session, INtpDbSession ntpSession, ILogger logger) + : OracleRepositoryBase(session, logger), ILookupRepository +{ + private NtpAccess Ntp { get; } = new(ntpSession, logger); + + /// NTP-schema connection: COMPANIES, NATIONALITY. STATUS/LOCATIONS/CARGOTYPE/CITIES (with DOMAIN) are NAFITHTCS = primary. + private sealed class NtpAccess(INtpDbSession s, ILogger l) : NtpRepositoryBase(s, l) + { + public Task> ListAsync(string sql, object? p, CancellationToken ct) => QueryAsync(sql, p, ct); + } + + public Task> GetStatusesAsync(string domain, bool? isActive, CancellationToken ct = default) + { + var p = new DynamicParameters(); + p.Add("Domain", domain); + var filter = ""; + if (isActive.HasValue) + { + filter = " AND ISACTIVE = :IsActive"; + p.Add("IsActive", isActive.Value ? 1 : 0); + } + return QueryAsync( + $"SELECT CODE, DESCRIPTION, ISACTIVE FROM STATUS WHERE DOMAIN = :Domain{filter} ORDER BY DESCRIPTION, CODE", p, ct); + } + + public Task> GetLocationsAsync(string domain, string? type, bool includeInactive, CancellationToken ct = default) + { + var p = new DynamicParameters(); + p.Add("Domain", domain); + var filter = ""; + if (type is not null) { filter += " AND TYPE = :Type"; p.Add("Type", type); } + if (!includeInactive) filter += " AND STATUS = 1"; + return QueryAsync( + $"SELECT ID, NAME, TYPE, DOMAIN FROM LOCATIONS WHERE DOMAIN = :Domain{filter} ORDER BY NAME, ID", p, ct); + } + + public Task> GetCargoTypesAsync(string domain, CancellationToken ct = default) => + QueryAsync("SELECT ID, NAME, DOMAIN FROM CARGOTYPE WHERE DOMAIN = :Domain ORDER BY NAME, ID", + new { Domain = domain }, ct); + + public Task> GetCompaniesAsync(bool includeInactive, CancellationToken ct = default) => + Ntp.ListAsync( + $"SELECT ID, NAME, DESCRIPTION AS CODE FROM COMPANIES{(includeInactive ? "" : " WHERE STATUS = 1")} ORDER BY NAME, ID", null, ct); + + public Task> GetNationalitiesAsync(CancellationToken ct = default) => + Ntp.ListAsync("SELECT CODE, NAME FROM NATIONALITY WHERE LANGID = 0 ORDER BY ID", null, ct); + + public Task> GetCitiesAsync(CancellationToken ct = default) => + QueryAsync("SELECT ID, NAME FROM CITIES ORDER BY SORTORDER, ID", null, ct); +} diff --git a/src/NTP.Infrastructure/Persistence/Repositories/ShipmentRepository.cs b/src/NTP.Infrastructure/Persistence/Repositories/ShipmentRepository.cs new file mode 100644 index 0000000..cd07df9 --- /dev/null +++ b/src/NTP.Infrastructure/Persistence/Repositories/ShipmentRepository.cs @@ -0,0 +1,135 @@ +using System.Data; +using System.Text; +using Dapper; +using Microsoft.Extensions.Logging; +using NTP.Application.Abstractions; +using NTP.Application.Common; +using NTP.Application.Shipments; +using NTP.Domain.Entities; + +namespace NTP.Infrastructure.Persistence.Repositories; + +/// +/// SAMPLE repository for the existing table NAFITH.SHIPMENTS (see db/sample-schema.sql). +/// Copy this file per table; keep SQL explicit and 11g-compatible. +/// +internal sealed class ShipmentRepository(IDbSession session, ILogger logger) + : OracleRepositoryBase(session, logger), IShipmentRepository +{ + // Explicit column list - never SELECT * against legacy tables. + private const string Columns = """ + SHIPMENT_ID, SHIPMENT_NO, ORIGIN_CODE, DESTINATION_CODE, WEIGHT_KG, + STATUS, IS_ACTIVE, CREATED_AT, UPDATED_AT, ROW_VERSION + """; + + public Task GetByIdAsync(long id, CancellationToken ct = default) => + QuerySingleOrDefaultAsync( + $"SELECT {Columns} FROM SHIPMENTS WHERE SHIPMENT_ID = :Id", + new { Id = id }, ct); + + public async Task> SearchAsync(ShipmentQuery query, PageRequest page, CancellationToken ct = default) + { + var where = new StringBuilder(" WHERE 1 = 1"); + var p = new DynamicParameters(); + + if (!string.IsNullOrWhiteSpace(query.ShipmentNo)) + { + where.Append(@" AND SHIPMENT_NO LIKE :ShipmentNo ESCAPE '\'"); + p.Add("ShipmentNo", OracleSql.EscapeLike(query.ShipmentNo.Trim()) + "%"); + } + if (!string.IsNullOrWhiteSpace(query.Status)) + { + where.Append(" AND STATUS = :Status"); + p.Add("Status", query.Status); + } + if (query.IsActive.HasValue) + { + where.Append(" AND IS_ACTIVE = :IsActive"); + p.Add("IsActive", OracleSql.ToNumber(query.IsActive.Value)); + } + + var baseSql = $"SELECT {Columns} FROM SHIPMENTS{where}"; + + // ODP.NET does not support multiple result sets per command text, so count + page = 2 round trips. + var total = await ExecuteScalarAsync(OracleSql.Count(baseSql), p, ct); + if (total == 0) + return new PagedResult([], page.SafePage, page.SafePageSize, 0); + + p.Add("MinRow", page.MinRow); + p.Add("MaxRow", page.MaxRow); + var items = await QueryAsync( + OracleSql.Paginate(baseSql + " ORDER BY CREATED_AT DESC, SHIPMENT_ID DESC"), p, ct); + + return new PagedResult(items, page.SafePage, page.SafePageSize, total); + } + + public async Task ExistsByNumberAsync(string shipmentNo, long? excludeId = null, CancellationToken ct = default) + { + var count = await ExecuteScalarAsync(""" + SELECT COUNT(*) FROM SHIPMENTS + WHERE SHIPMENT_NO = :ShipmentNo + AND (:ExcludeId IS NULL OR SHIPMENT_ID <> :ExcludeId) + AND ROWNUM = 1 + """, new { ShipmentNo = shipmentNo.Trim(), ExcludeId = excludeId }, ct); + return count > 0; + } + + public async Task InsertAsync(Shipment s, CancellationToken ct = default) + { + // 11g has no IDENTITY columns: use the sequence. If the legacy table already has a + // BEFORE INSERT trigger that assigns the ID, RETURNING still gives the final value. + var p = new DynamicParameters(new + { + s.ShipmentNo, + s.OriginCode, + s.DestinationCode, + s.WeightKg, + s.Status, + IsActive = OracleSql.ToNumber(s.IsActive) + }); + p.Add("NewId", dbType: DbType.Int64, direction: ParameterDirection.Output); + + await ExecuteAsync(""" + INSERT INTO SHIPMENTS + (SHIPMENT_ID, SHIPMENT_NO, ORIGIN_CODE, DESTINATION_CODE, WEIGHT_KG, + STATUS, IS_ACTIVE, CREATED_AT, ROW_VERSION) + VALUES + (SHIPMENTS_SEQ.NEXTVAL, :ShipmentNo, :OriginCode, :DestinationCode, :WeightKg, + :Status, :IsActive, SYSDATE, 0) + RETURNING SHIPMENT_ID INTO :NewId + """, p, ct); + + // ODP.NET may hand back OracleDecimal for NUMBER output params - convert defensively. + return OracleSql.ToInt64(p.Get("NewId")); + } + + public Task UpdateAsync(Shipment s, CancellationToken ct = default) => + ExecuteAsync(""" + UPDATE SHIPMENTS + SET SHIPMENT_NO = :ShipmentNo, + ORIGIN_CODE = :OriginCode, + DESTINATION_CODE = :DestinationCode, + WEIGHT_KG = :WeightKg, + STATUS = :Status, + IS_ACTIVE = :IsActive, + UPDATED_AT = SYSDATE, + ROW_VERSION = ROW_VERSION + 1 + WHERE SHIPMENT_ID = :ShipmentId + AND ROW_VERSION = :RowVersion + """, new + { + s.ShipmentNo, + s.OriginCode, + s.DestinationCode, + s.WeightKg, + s.Status, + IsActive = OracleSql.ToNumber(s.IsActive), + s.ShipmentId, + s.RowVersion + }, ct); + + public Task DeleteAsync(long id, int rowVersion, CancellationToken ct = default) => + ExecuteAsync( + "DELETE FROM SHIPMENTS WHERE SHIPMENT_ID = :Id AND ROW_VERSION = :RowVersion", + new { Id = id, RowVersion = rowVersion }, ct); +} diff --git a/tests/NTP.Tests/AuthTests.cs b/tests/NTP.Tests/AuthTests.cs new file mode 100644 index 0000000..3dbc94e --- /dev/null +++ b/tests/NTP.Tests/AuthTests.cs @@ -0,0 +1,115 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Http; +using NTP.Api.Auth; +using NTP.Application.Auth; +using NTP.Application.Common; + +namespace NTP.Tests; + +public class PasswordHasherTests +{ + [Fact] + public void Sha1Hex_is_uppercase_hex_of_UPPER_login_plus_password() + { + // SHA-1("ABCpass") computed independently. + var expected = Convert.ToHexString(System.Security.Cryptography.SHA1.HashData("ABCpass"u8.ToArray())); + Assert.Equal(expected, PasswordHasher.Sha1Hex("abc", "pass")); + Assert.Equal(40, expected.Length); + Assert.Equal(expected, expected.ToUpperInvariant()); + } + + [Fact] + public void Sha1Hex_known_vector() + { + // SHA-1("abc") = A9993E364706816ABA3E25717850C26C9CD0D89D ; login "" + password "abc" + Assert.Equal("A9993E364706816ABA3E25717850C26C9CD0D89D", PasswordHasher.Sha1Hex("", "abc")); + } + + [Fact] + public void Login_case_does_not_matter() + => Assert.Equal(PasswordHasher.Sha1Hex("Abc", "p"), PasswordHasher.Sha1Hex("aBC", "p")); + + [Fact] + public void Aseza_accepts_two_variants_other_domains_one() + { + Assert.Equal(2, PasswordHasher.Candidates("aseza", "u", "p").Count); + Assert.Single(PasswordHasher.Candidates("GN", "u", "p")); + Assert.Contains(PasswordHasher.Sha1Hex("u", "p"), PasswordHasher.Candidates("ASEZA", "u", "p")); + } +} + +public class ClaimsMappingTests +{ + private static readonly AuthenticatedUser Sample = new( + Id: 42, UserId: "50034", Name: "Ahmad", RoleCode: "GOP", RoleName: "Gate operator", Domain: "ASEZA", + LocationId: 5, LocationName: "Gate 1", StkId: 3, CompId: 15, CompanyId: 15, CompanyName: "NAFITH", + CompanyCode: "NAF001", EmpNo: "1001", Lang: "EN", IsStaff: true); + + private static CurrentUser Map(AuthenticatedUser u) + { + var identity = new ClaimsIdentity(JwtTokenIssuer.CreateClaims(u), "test", AppClaimsNames.Name, AppClaimsNames.Role); + var ctx = new DefaultHttpContext { User = new ClaimsPrincipal(identity) }; + return new CurrentUser(new HttpContextAccessor { HttpContext = ctx }); + } + + [Fact] + public void Roundtrips_all_fields() + { + var c = Map(Sample); + Assert.True(c.IsAuthenticated); + Assert.Equal(42, c.Id); + Assert.Equal("50034", c.UserId); + Assert.Equal("Ahmad", c.Name); + Assert.Equal("GOP", c.RoleCode); + Assert.Equal("Gate operator", c.RoleName); + Assert.Equal("ASEZA", c.Domain); + Assert.Equal(5, c.LocationId); + Assert.Equal("Gate 1", c.LocationName); + Assert.Equal(3, c.StkId); + Assert.Equal(15, c.CompId); + Assert.Equal(15, c.CompanyId); + Assert.Equal("NAF001", c.CompanyCode); + Assert.Equal("1001", c.EmpNo); + Assert.Equal("EN", c.Lang); + Assert.True(c.IsStaff); + Assert.True(c.IsInRole("gop")); + Assert.True(c.IsInAnyRole("X", "GOP")); + } + + [Fact] + public void Missing_values_become_null_or_defaults() + { + var c = Map(Sample with { LocationId = null, StkId = null, IsStaff = false, Lang = "" }); + Assert.Null(c.LocationId); + Assert.Null(c.StkId); + Assert.False(c.IsStaff); + Assert.Equal("AR", c.Lang); + } + + [Fact] + public void Anonymous_user_is_not_authenticated() + { + var c = new CurrentUser(new HttpContextAccessor { HttpContext = new DefaultHttpContext() }); + Assert.False(c.IsAuthenticated); + Assert.Equal(string.Empty, c.UserId); + Assert.Null(c.CompanyId); + } +} + +public class ConventionRegistrationTests +{ + [Fact] + public void Application_services_are_registered_by_convention() + { + var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); + NTP.Application.DependencyInjection.AddApplication(services); + Assert.Contains(services, d => d.ServiceType == typeof(IAuthService) && d.ImplementationType == typeof(AuthService)); + Assert.Contains(services, d => d.ServiceType == typeof(NTP.Application.Lookups.ILookupService)); + } +} + +internal static class AppClaimsNames +{ + public const string Name = NTP.Application.Abstractions.AppClaims.Name; + public const string Role = NTP.Application.Abstractions.AppClaims.Role; +} diff --git a/tests/NTP.Tests/NTP.Tests.csproj b/tests/NTP.Tests/NTP.Tests.csproj new file mode 100644 index 0000000..0f4d111 --- /dev/null +++ b/tests/NTP.Tests/NTP.Tests.csproj @@ -0,0 +1,18 @@ + + + false + true + + + + + + + + + + + + + + diff --git a/tests/NTP.Tests/OracleCredentialGuardTests.cs b/tests/NTP.Tests/OracleCredentialGuardTests.cs new file mode 100644 index 0000000..05ad9c3 --- /dev/null +++ b/tests/NTP.Tests/OracleCredentialGuardTests.cs @@ -0,0 +1,71 @@ +using NTP.Infrastructure.Persistence; + +namespace NTP.Tests; + +public class OracleCredentialGuardTests +{ + // The guard keeps static state, so every test uses its own account key. + private static readonly DateTime T0 = new(2026, 11, 11, 9, 0, 0, DateTimeKind.Utc); + + [Fact] + public void Unknown_accounts_are_allowed() + => OracleCredentialGuard.EnsureAllowed("GUARD_FRESH@db"); + + [Fact] + public void Rejected_password_suspends_every_further_attempt_for_good() + { + const string key = "GUARD_BADPWD@db"; + Assert.True(OracleCredentialGuard.Record(key, 1017)); + Assert.Throws(() => OracleCredentialGuard.EnsureAllowed(key)); + // not even a day later: a corrected connection string needs a restart + Assert.Throws(() => OracleCredentialGuard.EnsureAllowed(key, T0.AddDays(1))); + } + + [Fact] + public void Message_names_the_account_but_never_a_password() + { + const string key = "GUARD_MSG@db"; + OracleCredentialGuard.Record(key, 1017); + var ex = Assert.Throws(() => OracleCredentialGuard.EnsureAllowed(key)); + Assert.Contains("GUARD_MSG@db", ex.Message); + Assert.Contains("ORA-01017", ex.Message); + } + + [Theory] + [InlineData(28000)] + [InlineData(28001)] + public void Locked_or_expired_account_is_retried_after_the_cooldown(int ora) + { + var key = $"GUARD_LOCKED_{ora}@db"; + Assert.True(OracleCredentialGuard.Record(key, ora, nowUtc: T0)); + Assert.Throws(() => OracleCredentialGuard.EnsureAllowed(key, T0.AddSeconds(10))); + OracleCredentialGuard.EnsureAllowed(key, T0.Add(OracleCredentialGuard.Cooldown).AddSeconds(1)); // allowed again + } + + [Fact] + public void A_successful_open_clears_a_temporary_lock_but_not_a_rejection() + { + OracleCredentialGuard.Record("GUARD_OK1@db", 28000, nowUtc: T0); + OracleCredentialGuard.Succeeded("GUARD_OK1@db"); + OracleCredentialGuard.EnsureAllowed("GUARD_OK1@db", T0); + + OracleCredentialGuard.Record("GUARD_OK2@db", 1017); + OracleCredentialGuard.Succeeded("GUARD_OK2@db"); + Assert.Throws(() => OracleCredentialGuard.EnsureAllowed("GUARD_OK2@db")); + } + + [Fact] + public void Other_oracle_errors_are_not_handled_by_the_guard() + { + Assert.False(OracleCredentialGuard.Record("GUARD_OTHER@db", 942)); + OracleCredentialGuard.EnsureAllowed("GUARD_OTHER@db"); + } + + [Fact] + public void Key_is_user_at_datasource_without_the_password() + { + var key = OracleCredentialGuard.KeyOf("User Id=NTP;Password=secret123;Data Source=db-host:1521/service;Min Pool Size=1"); + Assert.Equal("NTP@db-host:1521/service", key); + Assert.DoesNotContain("secret123", key); + } +} diff --git a/tests/NTP.Tests/OrdersRulesTests.cs b/tests/NTP.Tests/OrdersRulesTests.cs new file mode 100644 index 0000000..f311822 --- /dev/null +++ b/tests/NTP.Tests/OrdersRulesTests.cs @@ -0,0 +1,226 @@ +using System.IO.Compression; +using System.Text; +using NTP.Application.Grains.Orders; +using NTP.Domain.Grains.Orders; + +namespace NTP.Tests; + +public class TenderOrderRulesTests +{ + [Theory] + [InlineData(41, 100, false, "PCKD")] + [InlineData(41, 350, true, "PCKD")] // packed wins over tipper destinations + [InlineData(38, 350, false, "BULK_GALLAB")] + [InlineData(38, 440, false, "BULK_GALLAB")] + [InlineData(38, 465, false, "BULK_GALLAB")] + [InlineData(38, 100, true, "BULK_GALLAB")] // tipper tick-box + [InlineData(38, 100, false, "BULK")] + public void Cargo_class_follows_legacy_createTenderOrder(long cargo, long dest, bool tipper, string expected) + => Assert.Equal(expected, TenderOrderRules.ResolveCargoClass(cargo, dest, tipper)); + + [Theory] + [InlineData(0, false)] + [InlineData(1, true)] + [InlineData(200, true)] + [InlineData(201, false)] + public void Quantity_is_between_1_and_200(int q, bool ok) => Assert.Equal(ok, TenderOrderRules.IsQuantityValid(q)); + + [Fact] + public void Order_date_must_be_today_to_today_plus_4() + { + var today = new DateTime(2026, 11, 2, 15, 30, 0); + Assert.True(TenderOrderRules.IsAllowedOrderDate(new DateTime(2026, 11, 2), today)); + Assert.True(TenderOrderRules.IsAllowedOrderDate(new DateTime(2026, 11, 6), today)); + Assert.False(TenderOrderRules.IsAllowedOrderDate(new DateTime(2026, 11, 1), today)); + Assert.False(TenderOrderRules.IsAllowedOrderDate(new DateTime(2026, 11, 7), today)); + } + + [Fact] + public void Delete_is_offered_only_for_dates_after_today() + { + var today = new DateTime(2026, 11, 2, 15, 30, 0); + Assert.False(TenderOrderRules.CanDelete(new DateTime(2026, 11, 2), today)); + Assert.True(TenderOrderRules.CanDelete(new DateTime(2026, 11, 3), today)); + } + + [Theory] + [InlineData(41, false)] + [InlineData(38, true)] + public void Type_is_required_except_for_packed(long cargo, bool required) => Assert.Equal(required, TenderOrderRules.IsTypeRequired(cargo)); + + [Fact] + public void Create_validator_requires_type_only_for_non_packed() + { + var v = new CreateTenderOrderValidator(); + var ok = new CreateTenderOrderRequest(41, 1, 2, DateTime.Today, 1, 10, false, null); + Assert.True(v.Validate(ok).IsValid); + Assert.False(v.Validate(ok with { CargoType = 38 }).IsValid); + Assert.True(v.Validate(ok with { CargoType = 38, Type = "COMP" }).IsValid); + Assert.False(v.Validate(ok with { Quantity = 201 }).IsValid); + Assert.False(v.Validate(ok with { Shift = 0 }).IsValid); + } +} + +public class QuotaRulesTests +{ + [Theory] + [InlineData(10, 10, true)] + [InlineData(11, 10, true)] + [InlineData(9, 10, false)] + [InlineData(0, 0, true)] + public void New_quota_cannot_be_below_used_quota(int quota, int done, bool ok) => Assert.Equal(ok, QuotaRules.CanSetQuota(quota, done)); +} + +public class BillingCalculatorTests +{ + [Fact] + public void Wage_is_rounded_to_three_decimals_per_ton() + { + // wage 14.67 per ton, 32,500 kg => 476.775 + Assert.Equal(476.775m, BillingCalculator.Wage(14.67m, 32_500m)); + // 14.902 * 31,337 / 1000 = 466.973... -> 3 decimals, half away from zero + Assert.Equal(Math.Round(14.902m * 31_337m / 1000m, 3, MidpointRounding.AwayFromZero), BillingCalculator.Wage(14.902m, 31_337m)); + } + + [Fact] + public void Shortage_fine_is_zero_inside_the_allowance() + { + // allowance 0.4 % of 30,000 = 120 kg; lost 100 kg + Assert.Equal(0m, BillingCalculator.ShortageFine(30_000m, 29_900m, 0.004m, 243.076m)); + Assert.Equal(0m, BillingCalculator.ShortageFine(30_000m, 29_880m, 0.004m, 243.076m)); // exactly at the limit + } + + [Fact] + public void Shortage_fine_charges_only_the_excess_loss() + { + // lost 200 kg, allowed 120 kg => 80 kg * 243.076 / 1000 = 19.44608 -> 19.446 + Assert.Equal(19.446m, BillingCalculator.ShortageFine(30_000m, 29_800m, 0.004m, 243.076m)); + } + + [Fact] + public void Excess_received_weight_is_not_fined() + => Assert.Equal(0m, BillingCalculator.ShortageFine(30_000m, 30_100m, 0.004m, 243.076m)); + + [Fact] + public void Net_weight_is_gross_minus_tare() => Assert.Equal(12_500m, BillingCalculator.NetWeight(20_000m, 7_500m)); + + [Fact] + public void Discharge_may_not_precede_load() + { + Assert.True(BillingCalculator.IsDischargeAfterLoad(new DateTime(2026, 1, 1), new DateTime(2026, 1, 1))); + Assert.True(BillingCalculator.IsDischargeAfterLoad(new DateTime(2026, 1, 1), new DateTime(2026, 1, 2))); + Assert.False(BillingCalculator.IsDischargeAfterLoad(new DateTime(2026, 1, 2), new DateTime(2026, 1, 1))); + } + + [Theory] + [InlineData(0, true)] + [InlineData(50000, true)] + [InlineData(50001, false)] + [InlineData(-1, false)] + public void Sent_weight_range(int w, bool ok) => Assert.Equal(ok, BillingCalculator.IsSentWeightInRange(w)); + + [Theory] + [InlineData(215, 14.67)] + [InlineData(220, 14.902)] + [InlineData(225, 17.219)] + [InlineData(38, 243.076)] + [InlineData(39, 235.006)] + [InlineData(40, 243.076)] + [InlineData(41, 235.006)] + public void Price_table_matches_legacy(long id, double expected) => Assert.Equal((decimal)expected, BillingPrices.Get(id)); + + [Fact] + public void Unknown_price_is_null() + { + Assert.Null(BillingPrices.Get(1)); + Assert.Null(BillingPrices.Get(null)); + } + + [Fact] + public void Add_billing_validator_requires_the_form_fields() + { + var v = new AddBillingValidator(); + var ok = new AddBillingRequest(1, 2, 3, "S1", DateTime.Today, DateTime.Today, 215, 38, "T1"); + Assert.True(v.Validate(ok).IsValid); + Assert.False(v.Validate(ok with { SerialNo = "" }).IsValid); + Assert.False(v.Validate(ok with { Tn = "" }).IsValid); + } +} + +public class GrainsWeightRulesTests +{ + [Theory] + [InlineData("12345", true)] + [InlineData("1234", false)] + [InlineData("123456", false)] + [InlineData("12a45", false)] + [InlineData("", false)] + [InlineData(null, false)] + public void Weight_is_five_digits(string? w, bool ok) => Assert.Equal(ok, GrainsWeightRules.IsValidWeight(w)); + + [Fact] + public void Event_remarks_keep_the_legacy_wording() + => Assert.Equal("الوزن القائم: 25000 الوزن الفارغ: 12000", GrainsWeightRules.EventRemarks("25000", "12000")); +} + +public class ReportMathTests +{ + [Fact] + public void Percent_rounding() + { + Assert.Equal(33.3m, ReportMath.Percent1(1, 3)); + Assert.Equal(66.7m, ReportMath.Percent1(2, 3)); + Assert.Equal(33.33m, ReportMath.Percent2(1, 3)); + Assert.Equal(0m, ReportMath.Percent1(0, 0)); + } +} + +public class TabularExportTests +{ + private static readonly ExportTable Sample = new( + ["Title, with comma"], ["A", "B", "C"], + [new object?[] { "x\"y", 1.5m, new DateTime(2026, 11, 2) }], + ["Total", 1.5m, null]); + + [Fact] + public void Csv_has_bom_quotes_and_invariant_numbers() + { + var bytes = TabularExport.ToCsv([Sample]); + Assert.Equal(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3]); + var text = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3); + Assert.Contains("\"Title, with comma\"\r\n", text); + Assert.Contains("\"x\"\"y\",1.5,02/11/2026\r\n", text); + Assert.Contains("Total,1.5,\r\n", text); + } + + [Theory] + [InlineData("=1+1", "'=1+1")] + [InlineData("@SUM(A1)", "'@SUM(A1)")] + [InlineData("-5", "-5")] + [InlineData("-cmd", "'-cmd")] + [InlineData("plain", "plain")] + public void Csv_neutralises_formulas(string input, string expected) => Assert.Equal(expected, TabularExport.Csv(input)); + + [Theory] + [InlineData(0, "A")] + [InlineData(25, "Z")] + [InlineData(26, "AA")] + [InlineData(27, "AB")] + [InlineData(701, "ZZ")] + public void Column_names(int index, string expected) => Assert.Equal(expected, TabularExport.ColumnName(index)); + + [Fact] + public void Xlsx_is_a_zip_with_the_sheet_and_rtl_flag() + { + var bytes = TabularExport.ToXlsx([Sample], rightToLeft: true); + using var zip = new ZipArchive(new MemoryStream(bytes)); + Assert.NotNull(zip.GetEntry("xl/workbook.xml")); + var sheet = zip.GetEntry("xl/worksheets/sheet1.xml")!; + using var reader = new StreamReader(sheet.Open()); + var xml = reader.ReadToEnd(); + Assert.Contains("rightToLeft=\"1\"", xml); + Assert.Contains("1.5", xml); + Assert.Contains("x"y", xml); + System.Xml.Linq.XDocument.Parse(xml); // well-formed + } +} diff --git a/tests/NTP.Tests/PermissionTests.cs b/tests/NTP.Tests/PermissionTests.cs new file mode 100644 index 0000000..740b52f --- /dev/null +++ b/tests/NTP.Tests/PermissionTests.cs @@ -0,0 +1,147 @@ +using NTP.Application.Abstractions; +using NTP.Application.Access; + +namespace NTP.Tests; + +public class PermissionTests +{ + private sealed class FakeUser(string role, bool authenticated = true) : ICurrentUser + { + public bool IsAuthenticated => authenticated; + public long Id => 1; + public string UserId => "T"; + public string Name => "t"; + public string RoleCode => role; + public string RoleName => role; + public string Domain => "GN"; + public long? LocationId => null; + public string LocationName => ""; + public long? StkId => null; + public long? CompId => null; + public long? CompanyId => null; + public string CompanyName => ""; + public string CompanyCode => ""; + public string EmpNo => ""; + public string Lang => "AR"; + public bool IsStaff => false; + public bool IsInRole(string roleCode) => string.Equals(role, roleCode, StringComparison.OrdinalIgnoreCase); + public bool IsInAnyRole(params string[] roleCodes) => roleCodes.Any(IsInRole); + } + + private sealed class FakeRepo(Func?> answer) : IPermissionRepository + { + public int Calls; + public Task?> GetAllowedAsync(string roleCode, CancellationToken ct = default) + { + Calls++; + return Task.FromResult(answer(roleCode)); + } + } + + // The service caches per role in a static dictionary; each test uses its own role code so tests do not interfere. + private static PermissionService Svc(string role, FakeRepo repo, bool authenticated = true) => new(repo, new FakeUser(role, authenticated)); + + [Fact] + public async Task Super_user_gets_everything_without_touching_the_database() + { + var repo = new FakeRepo(_ => throw new InvalidOperationException("must not be called")); + var svc = Svc("SU", repo); + var dto = await svc.GetForCurrentUserAsync(); + Assert.True(dto.All); + Assert.Empty(dto.Allowed); + Assert.True(await svc.IsAllowedAsync("grains.anything.at.all")); + Assert.Equal(0, repo.Calls); + } + + [Fact] + public async Task Missing_table_falls_back_to_the_sheet_defaults() + { + var svc = Svc("GOO", new FakeRepo(_ => null)); + var dto = await svc.GetForCurrentUserAsync(); + Assert.False(dto.All); + Assert.Contains(PermissionKeys.OrdersList, dto.Allowed); // الطلبيات: GTO,GOO + Assert.Contains(PermissionKeys.OrdersCompanyDest, dto.Allowed); // وجهات الشركات: GOO + Assert.Contains(PermissionKeys.PermitsDestinations, dto.Allowed); // تحديد وجهة ارسالية تموين: GOO + Assert.DoesNotContain(PermissionKeys.PermitsWeighbridge, dto.Allowed);// شاشة القبان: GTO,GGO only + Assert.DoesNotContain(PermissionKeys.OrdersWeights, dto.Allowed); // تثبيت أوزان التحميل: GTO only + } + + [Fact] + public async Task New_order_action_is_allowed_for_gto_only_by_default() + { + Assert.False(await Svc("GOO", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.OrdersCreate)); + Assert.True(await Svc("GTO", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.OrdersCreate)); + Assert.False(await Svc("GGO", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.OrdersCreate)); + Assert.False(await Svc("GPO", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.OrdersCreate)); + } + + [Fact] + public async Task Registering_trucks_trailers_and_drivers_is_granted_by_database_rows_only() + { + foreach (var role in new[] { "GTO", "GOO", "GPO", "GGO" }) + { + var none = Svc(role, new FakeRepo(_ => null)); // table missing: built-in defaults grant none of the create keys + Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryTrucksCreate)); + Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryTrailersCreate)); + Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryDriversCreate)); + Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryTrucksEdit)); // edit rights too: database rows only + Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryTrailersEdit)); + } + var granted = Svc("CREATE-ROLE", new FakeRepo(_ => new[] { PermissionKeys.RegistryTrucksCreate })); + Assert.True(await granted.IsAllowedAsync(PermissionKeys.RegistryTrucksCreate)); + Assert.False(await granted.IsAllowedAsync(PermissionKeys.RegistryDriversCreate)); + Assert.True(await Svc("SU", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.RegistryDriversCreate)); + } + + [Fact] + public async Task Screens_not_in_the_sheet_are_hidden_from_non_super_roles() + { + var svc = Svc("GGO", new FakeRepo(_ => null)); + Assert.True(await svc.IsAllowedAsync(PermissionKeys.PermitsWeighbridge)); + Assert.False(await svc.IsAllowedAsync(PermissionKeys.OrdersQuotas)); // not in the sheet for anyone + Assert.False(await svc.IsAllowedAsync(PermissionKeys.OrdersBilling)); + } + + [Fact] + public async Task Database_rows_replace_the_defaults_once_the_table_exists() + { + var svc = Svc("GPO", new FakeRepo(_ => new[] { "grains.orders.quotas" })); + Assert.True(await svc.IsAllowedAsync("grains.orders.quotas")); + Assert.False(await svc.IsAllowedAsync(PermissionKeys.PermitsList)); // in the defaults for GPO, but not in the table + } + + [Fact] + public async Task Role_code_matching_ignores_case() + { + var svc = Svc("gto", new FakeRepo(_ => null)); + Assert.True(await svc.IsAllowedAsync(PermissionKeys.PermitsActivation)); // GTO only + } + + [Fact] + public async Task Anonymous_callers_are_never_allowed() + { + var svc = Svc("GTO-ANON", new FakeRepo(_ => new[] { PermissionKeys.PermitsList }), authenticated: false); + Assert.False(await svc.IsAllowedAsync(PermissionKeys.PermitsList)); + } + + [Fact] + public async Task Result_is_cached_per_role() + { + var repo = new FakeRepo(_ => new[] { "k" }); + var svc = Svc("CACHEROLE", repo); + await svc.IsAllowedAsync("k"); + await svc.IsAllowedAsync("k"); + Assert.Equal(1, repo.Calls); + } + + [Fact] + public void Every_default_resource_has_at_least_one_role_and_no_super_user_row() + { + foreach (var (key, roles) in PermissionDefaults.RolesByResource) + { + Assert.NotEmpty(roles); + Assert.DoesNotContain("SU", roles); // SU is implicit, never stored + Assert.StartsWith("grains.", key); + } + } +} diff --git a/tests/NTP.Tests/PermitsRulesTests.cs b/tests/NTP.Tests/PermitsRulesTests.cs new file mode 100644 index 0000000..c4f78fa --- /dev/null +++ b/tests/NTP.Tests/PermitsRulesTests.cs @@ -0,0 +1,181 @@ +using NTP.Application.Grains.Permits; +using NTP.Domain.Grains.Permits; + +namespace NTP.Tests; + +public class PermitNumberTests +{ + [Theory] + [InlineData("BULK", 15L, 327L, 7L, "30" + "07" + "000015")] + [InlineData("BULK", 15L, 12L, 7L, "1" + "07" + "000015")] + [InlineData("PCKD", 15L, 327L, 7L, "3" + "48" + "0000015")] + [InlineData("PCKD", 15L, 12L, 7L, "1" + "48" + "000015")] + [InlineData("OTHER", 15L, 12L, 7L, "")] + public void Permit_number_layout_follows_generatePermitNumber(string cargo, long seq, long company, long tender, string expected) => + Assert.Equal(expected, PermitNumberGenerator.Generate(cargo, seq, company, 327, tender)); +} + +public class WeighbridgeDecisionTests +{ + [Theory] + [InlineData("ACCPT", 215L, 100L, 215L, "EN", true, "LTW", "ACCPT")] + [InlineData("RESD", 215L, 100L, 215L, "EX", true, "LGW", "ACTRL")] + [InlineData("ACTRL", 215L, 100L, 100L, "EN", true, "DGW", "CLRPR")] + [InlineData("CLRPR", 215L, 100L, 100L, "EX", true, "DTW", "CLOSE")] + [InlineData("CLOSE", 215L, 100L, 100L, "EX", false, null, null)] + [InlineData("OPEN", 215L, 100L, 215L, "EN", false, null, null)] + public void Decide_maps_location_and_direction_to_an_event(string status, long origin, long dest, long loc, string trx, bool allowed, + string? eventType, string? current) + { + var d = WeighbridgeRules.Decide(status, origin, dest, loc, trx); + Assert.Equal(allowed, d.Allowed); + Assert.Equal(eventType, d.EventType); + Assert.Equal(current, d.CurrentStatus); + } + + [Fact] + public void Location_off_the_route_is_error_2() => Assert.Equal("2", WeighbridgeRules.Decide("ACCPT", 215, 100, 999, "EN").ErrorCode); + + [Theory] + [InlineData(12000L, 40000L, true)] + [InlineData(9999L, 40000L, false)] + [InlineData(12000L, 76000L, false)] + [InlineData(20000L, 36000L, true)] + public void Manual_weights_must_be_in_range(long first, long second, bool ok) => + Assert.Equal(ok, WeighbridgeRules.ValidateManualWeights(first, second) is null); + + [Fact] + public void Gross_must_exceed_tare() => Assert.NotNull(WeighbridgeRules.ValidateGrossTare(10000, 10000)); + + [Theory] + [InlineData("12345", "54321", true)] + [InlineData("1234", "54321", false)] + public void Stored_weights_need_five_digits(string empty, string gross, bool ok) => + Assert.Equal(ok, WeighbridgeRules.ValidateStoredWeights(empty, gross) is null); +} + +public class PrintWeightTests +{ + [Fact] + public void Breakdown_splits_ton_and_kilo_and_signs_the_difference() + { + var b = WeightBreakdown.Compute(loadingTare: 14000, loadingGross: 40500, dischargeTare: 14000, dischargeGross: 40200); + Assert.Equal(26500, b.LoadingNet); + Assert.Equal(26200, b.DischargeNet); + Assert.Equal((26, 500), (b.LoadingTon, b.LoadingKilo)); + Assert.Equal((26, 200), (b.DischargeTon, b.DischargeKilo)); + Assert.Equal("(-)", b.Sign); + Assert.Equal(-300, b.KiloDifference); + } +} + +public class PhoneRejectRuleTests +{ + [Fact] + public void Blacklist_expiry_is_date_part_plus_days_plus_shift_end() + { + // shift 1 = [6,18]: (now - 30h).date + 2 days + 18h + var expiry = PhoneRejectRules.BlacklistExpiry(new DateTime(2026, 5, 10, 9, 0, 0), 6, 18, 2); + Assert.Equal(new DateTime(2026, 5, 11, 18, 0, 0), expiry); + } + + [Theory] + [InlineData("عدم الحضور بعد التسريب", true)] + [InlineData("لايرد", false)] + public void Absence_reasons_are_recognised(string reason, bool absence) => Assert.Equal(absence, PhoneRejectRules.IsAbsence(reason)); + + [Theory] + [InlineData("one", 1)] + [InlineData("fiv", 5)] + [InlineData("xyz", 0)] + public void Dialer_postponement_suffix(string key, int days) => Assert.Equal(days, PhoneRejectRules.PostponeDaysFromDialerKey(key)); +} + +public class DestinationRuleTests +{ + [Fact] + public void Packed_trucks_lose_the_bulk_locations_and_others_keep_only_them() + { + long[] all = [100, 215, 220, 350, 410]; + Assert.Equal(new long[] { 100, 410 }, DestinationRules.FilterCompanyLocations(all, "201401693756")); + Assert.Equal(new long[] { 215, 220, 350 }, DestinationRules.FilterCompanyLocations(all, "999")); + } + + [Theory] + [InlineData(38L, "38,39")] + [InlineData(39L, "38,39")] + [InlineData(41L, "40,41")] + public void Cargo_groups_are_interchangeable(long cargo, string expected) => + Assert.Equal(expected, string.Join(',', DestinationRules.CargoGroup(cargo)!)); + + [Fact] + public void Operation_window_is_inclusive() => + Assert.True(OperationWindow.IsWithin(new DateTime(2026, 1, 2, 6, 0, 0), new DateTime(2026, 1, 2), 6, 18)); +} + +public class DistributionCategoryTests +{ + [Theory] + [InlineData("PCKD", "PCKD", "", "PCKD")] + [InlineData("BULK_AHALE", "BULK", "AHALE", "BULK")] + [InlineData("BULK_GALLAB_COMP", "BULK_GALLAB", "COMP", "BULK")] + public void Category_maps_to_queue_code_type_and_cargo(string request, string code, string type, string cargo) + { + var c = DistributionCategory.Parse(request)!; + Assert.Equal((code, type, cargo), (c.DistributionCode, c.QueueType, c.PermitCargoType)); + } + + [Fact] + public void Unknown_category_is_rejected() => Assert.Null(DistributionCategory.Parse("NOPE")); + + [Fact] + public void Queue_filter_uses_the_AHALI_spelling() => Assert.Equal(("BULK", "AHALI"), DistributionCategory.Parse("BULK_AHALE")!.QueueFilter); +} + +public class PermitActionRuleTests +{ + [Fact] + public void Requested_permit_can_be_submitted_by_a_company_but_phone_buttons_are_staff_only() + { + var company = PermitActionRules.For(PermitStatus.Requested, 12, isCompany: true, isOperator: true, isConvertRole: false, isReactivator: false, 327); + Assert.Contains(PermitActionRules.Submit, company); + Assert.DoesNotContain(PermitActionRules.PhoneAccept, company); + var staff = PermitActionRules.For(PermitStatus.Requested, 12, isCompany: false, isOperator: true, isConvertRole: false, isReactivator: false, 327); + Assert.Contains(PermitActionRules.PhoneAccept, staff); + } + + [Fact] + public void Accepted_permit_offers_convert_to_resd_only_to_su_gpo() + { + var a = PermitActionRules.For(PermitStatus.Accepted, 327, false, true, true, false, 327); + var b = PermitActionRules.For(PermitStatus.Accepted, 327, false, true, false, false, 327); + Assert.Contains(PermitActionRules.ConvertToResd, a); + Assert.DoesNotContain(PermitActionRules.ConvertToResd, b); + } + + [Fact] + public void Revoked_owner_permit_can_be_reactivated_by_su_gto_only() + { + Assert.Contains(PermitActionRules.Reactivate, PermitActionRules.For(PermitStatus.Revoked, 327, false, true, false, true, 327)); + Assert.DoesNotContain(PermitActionRules.Reactivate, PermitActionRules.For(PermitStatus.Revoked, 12, false, true, false, true, 327)); + } +} + +public class PermitSupportTests +{ + [Theory] + [InlineData("ASE000094", 94L)] + [InlineData("ASE", null)] + [InlineData(null, null)] + public void Company_code_number_is_mid_4_6(string? code, long? expected) => Assert.Equal(expected, PermitUserContext.ParseCompanyCodeNo(code)); + + [Theory] + [InlineData("2026-03-05", 2026, 3, 5)] + [InlineData("05/03/2026", 2026, 3, 5)] + [InlineData("05\\03\\2026", 2026, 3, 5)] + public void Legacy_dates_parse(string text, int y, int m, int d) => Assert.Equal(new DateTime(y, m, d), PermitDates.ParseLegacy(text)); + + [Fact] + public void Bad_date_is_null() => Assert.Null(PermitDates.ParseLegacy("nonsense")); + +} diff --git a/tests/NTP.Tests/PermitsWiringTests.cs b/tests/NTP.Tests/PermitsWiringTests.cs new file mode 100644 index 0000000..b1b5847 --- /dev/null +++ b/tests/NTP.Tests/PermitsWiringTests.cs @@ -0,0 +1,50 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NTP.Application; +using NTP.Application.Abstractions; +using NTP.Application.Grains.Permits; +using NTP.Infrastructure; + +namespace NTP.Tests; + +/// Proves that the conventionally registered services/repositories of the permits slice resolve (no connection is opened). +public class PermitsWiringTests +{ + private static ServiceProvider Build() + { + var cfg = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["ConnectionStrings:NAFITHTCS"] = "User Id=x;Password=x;Data Source=localhost:1521/x", + ["ConnectionStrings:NtpSchema"] = "User Id=x;Password=x;Data Source=localhost:1521/x", + ["Grains:Permits:BadiyaScac"] = "327", + }).Build(); + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(cfg); + services.AddApplication(); + services.AddInfrastructure(cfg); + services.AddScoped(_ => null!); + return services.BuildServiceProvider(); + } + + [Theory] + [InlineData(typeof(IPermitService))] + [InlineData(typeof(IQueueService))] + [InlineData(typeof(IDestinationService))] + [InlineData(typeof(IDistributionService))] + [InlineData(typeof(IWeighbridgeService))] + public void Services_resolve(Type service) + { + using var sp = Build(); + using var scope = sp.CreateScope(); + Assert.NotNull(scope.ServiceProvider.GetRequiredService(service)); + } + + [Fact] + public void Settings_are_bound_from_configuration() + { + using var sp = Build(); + using var scope = sp.CreateScope(); + Assert.Equal(327, scope.ServiceProvider.GetRequiredService().Value.BadiyaScac); + } +} diff --git a/tests/NTP.Tests/RegistryRulesTests.cs b/tests/NTP.Tests/RegistryRulesTests.cs new file mode 100644 index 0000000..df80fd7 --- /dev/null +++ b/tests/NTP.Tests/RegistryRulesTests.cs @@ -0,0 +1,207 @@ +using NTP.Application.Grains.Registry; + +namespace NTP.Tests; + +public class RegistryRulesTests +{ + private const long Badiya = 327; + + [Theory] + [InlineData("OPEN", true, true)] + [InlineData("REGREQST", true, true)] + [InlineData("INCOMP", true, true)] + [InlineData("ACCPT", false, true)] + [InlineData("RVKD", false, false)] + [InlineData("accpt", false, true)] + public void Status_transitions_follow_legacy(string status, bool canAccept, bool canRevoke) + { + Assert.Equal(canAccept, RegistryRules.CanAccept(status)); + Assert.Equal(canRevoke, RegistryRules.CanRevoke(status)); + Assert.Equal(canRevoke, RegistryRules.CanEdit(status)); + } + + [Theory] + [InlineData(327, "REGREQST", "REGREQST")] // Badiya keeps the awaiting-registration state + [InlineData(327, "OPEN", null)] // ... any other state is not touched + [InlineData(327, "ACCPT", null)] + [InlineData(100, "REGREQST", "OPEN")] // other companies go back to OPEN after an edit + [InlineData(100, "ACCPT", "OPEN")] + public void Truck_edit_status(long scac, string current, string? expected) + => Assert.Equal(expected, RegistryRules.StatusAfterTruckEdit(scac, current, Badiya)); + + [Theory] + [InlineData("OPEN", "جديد")] + [InlineData("ACCPT", "مرخص")] + [InlineData("RVKD", "ملغي")] + [InlineData("REGREQST", "بانتظار التسجيل")] + [InlineData("INCOMP", "غير مكتمل")] + [InlineData("OTHER", "OTHER")] + public void Status_captions(string code, string caption) => Assert.Equal(caption, RegistryRules.StatusCaption(code)); + + [Theory] + [InlineData("abc", false)] + [InlineData("اسم المالك 12", false)] + [InlineData("a.b", true)] + [InlineData("a_b", true)] + [InlineData("a/b", true)] + [InlineData("a@b", true)] + [InlineData("a b", false)] + [InlineData(null, false)] + public void Special_characters(string? text, bool special) => Assert.Equal(special, RegistryRules.HasSpecialChars(text)); + + [Theory] + [InlineData("1960", 2026, true)] + [InlineData("2027", 2026, true)] // next year is allowed + [InlineData("2028", 2026, false)] + [InlineData("1959", 2026, false)] + [InlineData("", 2026, false)] + [InlineData("20a0", 2026, false)] + [InlineData(null, 2026, false)] + public void Manufacture_year_range(string? year, int now, bool ok) => Assert.Equal(ok, RegistryRules.IsYearWithinRange(year, now)); + + [Theory] + [InlineData("123456789012", 12, true)] + [InlineData("1234567890123", 12, false)] + [InlineData("12a4", 12, false)] + [InlineData("", 12, false)] + public void Digits(string s, int max, bool ok) => Assert.Equal(ok, RegistryRules.IsDigits(s, max)); + + [Theory] + [InlineData(2, "S")] + [InlineData(6, "S")] + [InlineData(7, "T")] + [InlineData(null, null)] + public void Truck_kind_of_axials(int? axials, string? kind) => Assert.Equal(kind, RegistryRules.TruckKindOfAxials(axials)); + + [Theory] + [InlineData(11, "TR")] + [InlineData(12, "HTR")] + [InlineData(null, null)] + public void Trailer_kind_of_axials(int? axials, string? kind) => Assert.Equal(kind, RegistryRules.TrailerKindOfAxials(axials)); + + [Theory] + [InlineData(0, 0, false)] + [InlineData(1, 0, false)] + [InlineData(2, 0, true)] + [InlineData(1, 1, true)] + public void Attachments_need_two_files(int newFiles, int stored, bool ok) => Assert.Equal(ok, RegistryRules.HasEnoughAttachments(newFiles, stored)); + + [Fact] + public void Blacklist_expiry_uses_shift_end_of_the_day_after_the_shift_start() + { + // 14:00 on 10 Jan, shift 6..14: (14:00 - 30h) = 08:00 on 9 Jan -> date 9 Jan, + 3 days = 12 Jan, + shift end hour + var expiry = RegistryRules.BlacklistExpiry(new DateTime(2025, 1, 10, 14, 0, 0), 3, 6, 14); + Assert.Equal(new DateTime(2025, 1, 12, 14, 0, 0), expiry); + } + + [Fact] + public void Blacklist_remarks_carry_the_automatic_release_date() + { + var text = RegistryRules.BlacklistRemarks("ملاحظة", new DateTime(2025, 1, 12, 14, 0, 0)); + Assert.Equal("ملاحظة، سيتم فك الانتظار بشكل تلقائي بتاريخ 01/12/2025 14:00", text); + } + + [Theory] + [InlineData("6,14", 6, 14)] + [InlineData(" 8 , 16 ", 8, 16)] + [InlineData("", 0, 24)] + [InlineData("x,y", 0, 24)] + [InlineData(null, 0, 24)] + public void Shift_hours_setting(string? setting, int start, int end) => Assert.Equal((start, end), RegistryRules.ParseShiftHours(setting)); + + [Theory] + [InlineData("PHONEDECLINE", true)] + [InlineData("WAITINGLIST", true)] + [InlineData("X", false)] + [InlineData(null, false)] + public void Blacklist_categories(string? c, bool ok) => Assert.Equal(ok, RegistryRules.IsBlacklistCategory(c)); + + [Theory] + [InlineData(1, true)] + [InlineData(14, true)] + [InlineData(30, true)] + [InlineData(6, false)] + public void Blacklist_days(int days, bool ok) => Assert.Equal(ok, RegistryRules.BlacklistDays.Contains(days)); + + [Fact] + public void Ownership_skipped_when_no_codes_configured_and_missing_truck_reported() + { + Assert.Equal(RegistryMessages.TruckNotFound, RegistryRules.ValidateOwnership(null, 100, Badiya, ["A"], ["B"])); + Assert.Equal(string.Empty, RegistryRules.ValidateOwnership("X", 100, Badiya, [], [])); + Assert.Equal(string.Empty, RegistryRules.ValidateOwnership("A", Badiya, Badiya, ["A"], ["B"])); + Assert.Equal(RegistryMessages.OwnershipNotAllowed, RegistryRules.ValidateOwnership("A", 100, Badiya, ["A"], ["B"])); + } + + [Fact] + public void Mot_truck_validation() + { + Assert.Equal(RegistryRules.MotNotRegistered, RegistryRules.MotTruckValidation([])); + Assert.Equal(string.Empty, RegistryRules.MotTruckValidation(["trucktype.general.cargo"])); + Assert.Equal(string.Empty, RegistryRules.MotTruckValidation(["trucktype.all"])); + Assert.Equal(RegistryRules.MotWrongType, RegistryRules.MotTruckValidation(["trucktype.fuel"])); + Assert.Equal(RegistryRules.MotNotRegistered, RegistryRules.MotTrailerValidation(0)); + Assert.Equal(string.Empty, RegistryRules.MotTrailerValidation(2)); + } + + [Theory] + [InlineData(5, 4, true)] + [InlineData(5, 5, true)] + [InlineData(5, 6, true)] + public void Fleet_decision_is_total(int fleet, int turns, bool _) => + Assert.True(Enum.IsDefined(RegistryRules.FleetDecision(fleet, turns, false))); + + [Fact] + public void Truck_validation_requires_full_set_for_badiya_only() + { + var empty = new SaveTruckRequest { Tn = "123456", Tcscac = 100 }; + Assert.Empty(RegistryValidation.ValidateTruck(empty, 100, false, Badiya, 2026)); + var failures = RegistryValidation.ValidateTruck(empty, Badiya, false, Badiya, 2026); + Assert.Contains(failures, f => f.PropertyName == nameof(SaveTruckRequest.ChasesNumber)); + Assert.Contains(failures, f => f.PropertyName == nameof(SaveTruckRequest.OwnerNnpn)); + Assert.Contains(failures, f => f.PropertyName == nameof(SaveTruckRequest.HeadType)); + } + + [Fact] + public void Truck_edit_for_other_companies_needs_axials_and_valid_year() + { + var failures = RegistryValidation.ValidateTruck(new SaveTruckRequest(), 100, true, Badiya, 2026); + Assert.Contains(failures, f => f.PropertyName == nameof(SaveTruckRequest.Axials)); + Assert.Contains(failures, f => f.PropertyName == nameof(SaveTruckRequest.ManifactureYear)); + Assert.Empty(RegistryValidation.ValidateTruck(new SaveTruckRequest { Axials = 3, ManifactureYear = "2020" }, 100, true, Badiya, 2026)); + } + + [Fact] + public void Driver_validation() + { + Assert.NotEmpty(RegistryValidation.ValidateDriver(new SaveDriverRequest())); + var ok = new SaveDriverRequest + { + Nnpn = "9801012345", Name = "Test Driver", Dln = "123456789", Dled = new DateTime(2030, 1, 1), Nat = "JO", Cat = "3", + Mobile1 = "0791234567" + }; + Assert.Empty(RegistryValidation.ValidateDriver(ok)); + ok.Cat = "7"; + Assert.Contains(RegistryValidation.ValidateDriver(ok), f => f.PropertyName == nameof(SaveDriverRequest.Cat)); + ok.Cat = "3"; + ok.Name = "a.b"; + Assert.Contains(RegistryValidation.ValidateDriver(ok), f => f.ErrorMessage == RegistryMessages.SpecialChars); + } + + [Fact] + public void Blacklist_validation() + { + var ok = new AddBlacklistRequest { EntityNum = "123456", Category = "WAITINGLIST", ExpiryDays = 5 }; + Assert.Empty(RegistryValidation.ValidateBlacklist(ok)); + ok.ExpiryDays = 6; + Assert.NotEmpty(RegistryValidation.ValidateBlacklist(ok)); + Assert.NotEmpty(RegistryValidation.ValidateCancelBlacklist(new CancelBlacklistRequest())); + } + + [Fact] + public void Trailer_edit_requires_full_set_for_every_company() + { + var failures = RegistryValidation.ValidateTrailer(new SaveTrailerRequest(), 100, true, Badiya); + Assert.Contains(failures, f => f.PropertyName == nameof(SaveTrailerRequest.OwnerName)); + Assert.Empty(RegistryValidation.ValidateTrailer(new SaveTrailerRequest { Tn = "1234" }, 100, false, Badiya)); + } +} diff --git a/tests/NTP.Tests/ReportsSliceTests.cs b/tests/NTP.Tests/ReportsSliceTests.cs new file mode 100644 index 0000000..c0047a4 --- /dev/null +++ b/tests/NTP.Tests/ReportsSliceTests.cs @@ -0,0 +1,390 @@ +using NTP.Application.Grains.Reports; + +namespace NTP.Tests; + +public class TripsReportMathTests +{ + private static readonly DateOnly D = new(2024, 1, 1); + + [Fact] + public void Frequency_computes_totals_and_groups() + { + // 10 trucks with 1 trip, 5 with 2, 2 with 15 + var t = new long[15]; t[0] = 10; t[1] = 5; t[14] = 2; + var r = TripsReportMath.Frequency(D, D, t); + Assert.Equal(17, r.TotalTrucks); + Assert.Equal(10 + 10 + 30, r.TotalTrips); + Assert.Equal(30, r.Trips[14]); + Assert.Equal(60m, r.TripsPct[14]); + Assert.Equal(5, r.Groups.Count); + Assert.Equal(15, r.Groups[0].Trucks); // 1-3 + Assert.Equal(20, r.Groups[0].Trips); + Assert.Equal(2, r.Groups[4].Trucks); // 13-15 + Assert.Equal(30, r.Groups[4].Trips); // legacy used multipliers 1..3 here; the real one is applied + } + + [Fact] + public void Frequency_with_no_data_does_not_divide_by_zero() + { + var r = TripsReportMath.Frequency(D, D, new long[15]); + Assert.Equal(0, r.TotalTrips); + Assert.All(r.TripsPct, p => Assert.Equal(0m, p)); + Assert.All(r.Groups, g => Assert.Equal(0m, g.TrucksPct)); + } + + [Fact] + public void Frequency_tolerates_short_input() + { + var r = TripsReportMath.Frequency(D, D, [3, 1]); + Assert.Equal(15, r.Trucks.Count); + Assert.Equal(5, r.TotalTrips); + } + + private static TripsPerCompanyRow Row(string code, decimal trucks, decimal trips, decimal tripPct, decimal share = 10) => + new() { Scac = "C" + code, CompanyCode = code, NumOfTruk = trucks, AllTripNum = trips, AvrgTrips = tripPct, CompanyShare = share, TotalShare = 1.5m }; + + [Fact] + public void Quota_splits_companies_and_badiya() + { + var q = TripsReportMath.Quota(D, D, [Row("10", 30, 100, 40), Row("11", 20, 50, 20), Row("327", 50, 150, 40)]); + Assert.Equal(50, q.Companies.Trucks); + Assert.Equal(50m, q.Companies.TruckPct); + Assert.Equal(150, q.Companies.Trips); + Assert.Equal(60m, q.Companies.TripPct); + Assert.Equal(50, q.Individuals.Trucks); + Assert.Equal(40m, q.Individuals.TripPct); + } + + [Fact] + public void Quota_without_rows_is_zero() + { + var q = TripsReportMath.Quota(D, D, []); + Assert.Equal(0m, q.Companies.TruckPct); + Assert.Equal(0m, q.Individuals.TruckPct); + } + + [Fact] + public void NumOfTrips_totals_exclude_badiya_then_add_it_to_the_grand_total() + { + var r = TripsReportMath.NumOfTrips(D, D, [Row("10", 3, 7, 70), Row("327", 1, 3, 30)]); + Assert.Single(r.Companies); + Assert.Equal(7, r.CompaniesTotal.Trips); // allTripNum summed (legacy summed numOfTruk) + Assert.Equal(10, r.GrandTrips); + Assert.Equal(4, r.GrandTrucks); + Assert.Equal(100m, r.GrandTripsPct); + Assert.NotNull(r.Individuals); + } + + [Fact] + public void Details_groups_by_company() + { + var rows = new List + { + new() { Scac = "A", Tn = "1", Tt = 2 }, new() { Scac = "A", Tn = "2", Tt = 3 }, new() { Scac = "B", Tn = "3", Tt = 1 } + }; + var r = TripsReportMath.Details(D, D, rows); + Assert.Equal(2, r.Groups.Count); + Assert.Equal(5, r.Groups[0].TotalTrips); + Assert.Equal(2, r.Groups[0].TruckCount); + } +} + +public class WeighbridgeEventMathTests +{ + private static WeighbridgeEventRaw Ev(long pid, string? type, string? w, string? date = "01/02/2024") => new() + { + Pid = pid, Pn = "P" + pid, Tn = "T", Loc = "Dest", EventType = type, Weight = w, EventDate = date, OriginAddressId = "Silo", Scac = "Co", CargoType = "قمح سائب" + }; + + [Fact] + public void Net_falls_back_to_gross_minus_tare_and_loss_is_difference() + { + var rows = WeighbridgeEventMath.Pivot([ + Ev(1, "LTW", "10000", "01/02/2024"), Ev(1, "LGW", "40000"), Ev(1, "DTW", "10000", "02/02/2024"), Ev(1, "DGW", "39500")]); + var r = Assert.Single(rows); + Assert.Equal(30000, r.Lnw); + Assert.Equal(29500, r.Dnw); + Assert.Equal(500, r.NetLoss); + Assert.Equal("01/02/2024", r.LoadDate); + Assert.Equal("02/02/2024", r.DischargeDate); + Assert.Equal(@"العقبة \ Silo", r.Origin); + } + + [Fact] + public void Explicit_net_events_win_and_are_shown_absolute() + { + var r = Assert.Single(WeighbridgeEventMath.Pivot([Ev(1, "LNW", "-30000"), Ev(1, "DNW", "29000")])); + Assert.Equal(30000, r.Lnw); + Assert.Equal(-59000, r.NetLoss); // legacy: signed LNW - DNW, shown unabsoluted + } + + [Fact] + public void Permit_without_weight_events_still_gets_a_row_with_dashes() + { + var r = Assert.Single(WeighbridgeEventMath.Pivot([Ev(1, null, null)])); + Assert.Equal("-", r.LoadDate); + Assert.Equal(0, r.Ltw); + } + + [Fact] + public void Serial_counts_permits_not_events() + { + var rows = WeighbridgeEventMath.Pivot([Ev(1, "LTW", "1"), Ev(1, "LGW", "2"), Ev(2, "LTW", "1")]); + Assert.Equal([1, 2], rows.Select(x => x.Serial)); + } +} + +public class PhoneApprovalTests +{ + private static string[] Row(string id, string conf, string callNo = "", string status = "") + { + var r = new string[20]; + Array.Fill(r, ""); + r[16] = id; r[17] = conf; r[18] = callNo; r[19] = status; + return r; + } + + [Fact] + public void Header_and_non_numeric_ids_are_skipped() => + Assert.Equal(PhoneDecisionKind.Skip, PhoneApprovalLogic.Decide(Row("ID", "Yes")).Kind); + + [Fact] + public void Yes_is_accept() + { + var d = PhoneApprovalLogic.Decide(Row("123", "Yes", "", "Call Answered.")); + Assert.Equal(PhoneDecisionKind.Accept, d.Kind); + Assert.Equal(123, d.PermitId); + } + + [Theory] + [InlineData("0123456789one", 1)] + [InlineData("0123456789two", 2)] + [InlineData("0123456789thr", 3)] + [InlineData("0123456789fou", 4)] + [InlineData("0123456789fiv", 5)] + [InlineData("0123456789xyz", 0)] + [InlineData("short", 0)] + public void No_rejects_with_delay_from_the_call_number(string callNo, int days) + { + var d = PhoneApprovalLogic.Decide(Row("5", "No", callNo)); + Assert.Equal(PhoneDecisionKind.Reject, d.Kind); + Assert.Equal(days, d.DelayDays); + Assert.Contains($"تم التأجيل {days} يوم", d.Remarks); + } + + [Fact] + public void Conf_containing_space_No_is_a_reject() => + Assert.Equal(PhoneDecisionKind.Reject, PhoneApprovalLogic.Decide(Row("5", "Press No", "0123456789one")).Kind); + + [Fact] + public void Empty_confirmation_is_no_decision_with_one_day_delay() + { + var d = PhoneApprovalLogic.Decide(Row("5", "", "", "Call Made. No Answer.")); + Assert.Equal(PhoneDecisionKind.Reject, d.Kind); + Assert.Equal(1, d.DelayDays); + Assert.StartsWith(PhoneApprovalLogic.NoAnswerRemark, d.Remarks); + Assert.EndsWith(PhoneApprovalLogic.NoDecisionRemark, d.Remarks); + } + + [Fact] + public void Status_text_selects_the_remark_case_insensitively() + { + Assert.StartsWith(PhoneApprovalLogic.AnsweredRemark, PhoneApprovalLogic.Decide(Row("5", "", "", "call answered.")).Remarks); + Assert.StartsWith(PhoneApprovalLogic.NoAnswerRemark, PhoneApprovalLogic.Decide(Row("5", "", "", "Call Made. timeout")).Remarks); + } + + [Fact] + public void Csv_reader_handles_quotes_commas_and_crlf() + { + var rows = CsvReader.Parse("a,\"b,c\",d\r\n\"x\"\"y\",,z\r\n"); + Assert.Equal(2, rows.Count); + Assert.Equal(["a", "b,c", "d"], rows[0]); + Assert.Equal(["x\"y", "", "z"], rows[1]); + } + + [Fact] + public void Csv_reader_keeps_a_last_line_without_newline() + { + var rows = CsvReader.Parse("1,2\n3,4"); + Assert.Equal(2, rows.Count); + Assert.Equal(["3", "4"], rows[1]); + } +} + +public class FileParserTests +{ + [Fact] + public void Irbid_first_record_has_9_lines_then_10() + { + var lines = new List { "2" }; + lines.AddRange(["1", "12 345", "20000", "10:30:00", "2024-01-05 00:00:00.0", "0", "x", "y", "z"]); // 9 lines + lines.AddRange(["2", "99999", "100", "11:00:00", "2024-01-06 00:00:00.0", "5", "a", "b", "c", "last"]); // 10 lines + var r = IrbidFileParser.Parse(lines, @"D:\silos\ir\IR2024.txt"); + Assert.Equal(2, r.Count); + Assert.Equal("6012345", r[0].F1); // blanks removed, "60" prefix + Assert.Null(r[0].F9); + Assert.Equal("last", r[1].F9); + Assert.Equal([1L, 2L], r.Select(x => x.Wid)); + Assert.Equal("IR", r[0].FileName); // digits stripped from the file name + } + + [Fact] + public void Irbid_event_date_combines_date_and_time() + { + var rec = new IrbidRecord { F3 = "10:30:05", F4 = "2024-01-05 00:00:00.0" }; + Assert.Equal("20240105103005", IrbidFileParser.EventDate(rec)); + Assert.Equal("", IrbidFileParser.EventDate(new IrbidRecord { F3 = "", F4 = "2024-01-05" })); + } + + [Fact] + public void Rsifeh_reads_id_and_data_line_pairs() + { + var lines = new[] + { + "1", "777", + "\"12/345*\", 5 ,\"ABC\",plate,#2024-01-05 10:00:00#,#2024-01-05 11:00:00#,#2024-01-05#,#2024-01-05#,\"n1\",\"n2\",\"n3\",\"n4\",13" + }; + var r = Assert.Single(RsifehFileParser.Parse(lines, @"C:\files\W31122013.rdg")); + Assert.Equal("777", r.Id); + Assert.Equal("6012345", r.F1); + Assert.Equal("5", r.F2); + Assert.Equal(new DateTime(2024, 1, 5, 10, 0, 0), r.F5); + Assert.Equal(new DateTime(2024, 1, 5), r.F7); + Assert.Equal("n4", r.F12); + Assert.Equal("31122013", r.FileName); + } + + [Fact] + public void Rsifeh_stops_after_the_announced_record_count() + { + var data = "\"1\",2,\"x\",d,#2024-01-05#,#2024-01-05#,#2024-01-05#,#2024-01-05#,\"a\",\"b\",\"c\",\"d\",1"; + var r = RsifehFileParser.Parse(["1", "1", data, "2", data], "f.rdg"); + Assert.Single(r); + } +} + +public class WsRulesTests +{ + [Theory] + [InlineData("EN", "ACCPT", "LTW", "ACCPT", null)] + [InlineData("EN", "RESD", "LTW", "RESD", null)] + [InlineData("EX", "ACTRL", "LGW", "ACTRL", "ACTRL")] + public void Origin_plans(string trx, string status, string evt, string current, string? next) + { + var p = WbRules.Plan(WbRules.LocationType.Origin, trx, status, out _); + Assert.NotNull(p); + Assert.Equal(evt, p!.EventType); + Assert.Equal(next, p.NewPermitStatus); + Assert.True(p.UseProvidedEventDate); + _ = current; + } + + [Fact] + public void Origin_entry_rejects_wrong_status() => + Assert.Null(WbRules.Plan(WbRules.LocationType.Origin, "EN", "ACTRL", out _)); + + [Theory] + [InlineData("ACCPT")] [InlineData("RESD")] [InlineData("ACTRL")] [InlineData("CLRPR")] + public void Destination_entry_moves_to_CLRPR(string status) + { + var p = WbRules.Plan(WbRules.LocationType.Destination, "EN", status, out _); + Assert.Equal("DGW", p!.EventType); + Assert.Equal("CLRPR", p.NewPermitStatus); + Assert.False(p.UseProvidedEventDate); + } + + [Fact] + public void Destination_exit_needs_CLRPR_and_closes() + { + Assert.Null(WbRules.Plan(WbRules.LocationType.Destination, "EX", "ACTRL", out _)); + var p = WbRules.Plan(WbRules.LocationType.Destination, "EX", "CLRPR", out _); + Assert.Equal("DTW", p!.EventType); + Assert.Equal("CLOSE", p.NewPermitStatus); + Assert.Equal("printPage2", p.Action); + } + + [Fact] + public void Unknown_trx_type_is_the_generic_error() + { + Assert.Null(WbRules.Plan(WbRules.LocationType.Origin, "ZZ", "ACCPT", out var generic)); + Assert.True(generic); + } + + [Fact] + public void Location_is_matched_against_origin_then_destination() + { + Assert.Equal(WbRules.LocationType.Origin, WbRules.Locate(10, 20, 10)); + Assert.Equal(WbRules.LocationType.Destination, WbRules.Locate(10, 20, 20)); + Assert.Equal(WbRules.LocationType.None, WbRules.Locate(10, 20, 30)); + Assert.Equal(WbRules.LocationType.None, WbRules.Locate(null, null, 30)); + } + + [Theory] + [InlineData("20240105 103005", true)] + [InlineData("20240105103005", true)] + [InlineData("2024-01-05", false)] + [InlineData("", false)] + public void Event_date_formats(string s, bool ok) + { + Assert.Equal(ok, WbRules.TryParseEventDate(s, out var d)); + if (ok) Assert.Equal(new DateTime(2024, 1, 5, 10, 30, 5), d); + } + + [Theory] + [InlineData("BULK", 5, "10", 3L, "1" + "03" + "000005")] + [InlineData("BULK", 5, "327", 3L, "30" + "03" + "000005")] + [InlineData("PCKD", 12, "10", 3L, "1" + "44" + "000012")] + [InlineData("PCKD", 12, "327", 3L, "3" + "44" + "0000012")] + [InlineData("BULK", 5, "10", 123L, "1" + "123" + "000005")] + public void Permit_number_format(string tt, long seq, string company, long tenders, string expected) => + Assert.Equal(expected, PermitNumber.Generate(tt, seq, company, tenders)); + + [Fact] + public void Permit_number_unsupported_type_is_null() => Assert.Null(PermitNumber.Generate("OTHER", 1, "10", 1)); +} + +public class OrderLabelsAndMotTests +{ + [Fact] + public void Labels_match_legacy_getOrderDetails() + { + Assert.Equal("سائب", GrainsOrderLabels.CargoTypeLabel(38)); + Assert.Equal("مشول", GrainsOrderLabels.CargoTypeLabel(41)); + Assert.Equal("صوامع", GrainsOrderLabels.LocationLabel(205)); + Assert.Equal("999", GrainsOrderLabels.LocationLabel(999)); + Assert.Equal("سائب قلاب", GrainsOrderLabels.OrderTypeLabel("BULK_GALLAB")); + } + + [Fact] + public void Mot_pivot_sums_months_and_averages_trucks() + { + var rows = new List + { + new() { Mm = "2016-01", RegType = "COMP", Trips = 1, TnFreq = 10, TripFreq = 10 }, + new() { Mm = "2016-01", RegType = "COMP", Trips = 2, TnFreq = 4, TripFreq = 8 }, + new() { Mm = "2016-02", RegType = "COMP", Trips = 1, TnFreq = 20, TripFreq = 20 }, + new() { Mm = "2016-01", RegType = "OWN", Trips = 1, TnFreq = 6, TripFreq = 6 }, + }; + var r = MotMultiTripsBuilder.Build(rows); + Assert.Equal(2, r.MonthCount); + Assert.Equal(2, r.Companies.Months.Count); + Assert.Equal(14, r.Companies.Months[0].TrucksTotal); + Assert.Equal(18, r.Companies.Months[0].TripsTotal); + Assert.Equal(15, r.Companies.AvgTrucksPerTrips[0]); // (10+20)/2 months + Assert.Equal(17, r.Companies.AvgTrucksTotal); // (14+20)/2 + Assert.Equal(38, r.Companies.TripsSum); + Assert.Equal(3, r.Individuals.AvgTrucksTotal); // 6 / 2 months + // per-bucket average over rows present: COMP trips=1 -> avg(10,20)=15, OWN -> 6 => 71%/29% + Assert.Equal(15, r.ChartCompanies[0]); + Assert.Equal(6, r.ChartIndividuals[0]); + Assert.Equal(71.43m, r.ChartCompaniesPct[0]); + } + + [Fact] + public void Mot_pivot_with_no_rows_is_empty_not_a_crash() + { + var r = MotMultiTripsBuilder.Build([]); + Assert.Empty(r.Companies.Months); + Assert.Equal(0, r.Companies.AvgTrucksTotal); + } +} diff --git a/web/.env.example b/web/.env.example new file mode 100644 index 0000000..196d5bf --- /dev/null +++ b/web/.env.example @@ -0,0 +1,5 @@ +# Set to 1 to run with the in-browser mock API and show the _example feature. +VITE_MOCK=0 +# Optional: API address. Default /api/v1 (same origin; Vite proxies /api to https://localhost:7180 in development). +# VITE_API_BASE=/api/v1 +# Build modes read .env.qa / .env.production (npm run build:qa / build:prod); .env.local files are git-ignored. diff --git a/web/.env.production b/web/.env.production new file mode 100644 index 0000000..b30aa92 --- /dev/null +++ b/web/.env.production @@ -0,0 +1,5 @@ +# Production build (npm run build:prod). Only non-secret values: everything here ends up in the public JavaScript. +# Same-origin by default: the web server proxies /api to the production API. For a separate API host use e.g. +# https:///api/v1 and add the web origin to Cors__AllowedOrigins__0 on the API. +VITE_API_BASE=/api/v1 +VITE_MOCK=0 diff --git a/web/.env.qa b/web/.env.qa new file mode 100644 index 0000000..6f56857 --- /dev/null +++ b/web/.env.qa @@ -0,0 +1,5 @@ +# QA build (npm run build:qa). Only non-secret values: everything here ends up in the public JavaScript. +# Same-origin by default: the web server proxies /api to the QA API. For a separate API host use e.g. https:///api/v1 +# and add the QA web origin to Cors__AllowedOrigins__0 on the API. +VITE_API_BASE=/api/v1 +VITE_MOCK=0 diff --git a/web/.gitignore b/web/.gitignore new file mode 100644 index 0000000..804bd4a --- /dev/null +++ b/web/.gitignore @@ -0,0 +1,3 @@ +node_modules +dist +*.local diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..82a408b --- /dev/null +++ b/web/index.html @@ -0,0 +1,17 @@ + + + + + + + Nafith + + + + + + +
+ + + diff --git a/web/package-lock.json b/web/package-lock.json new file mode 100644 index 0000000..faa1d76 --- /dev/null +++ b/web/package-lock.json @@ -0,0 +1,2468 @@ +{ + "name": "ntp-web", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ntp-web", + "version": "0.1.0", + "dependencies": { + "@emotion/cache": "^11.14.0", + "@emotion/react": "^11.14.0", + "@emotion/styled": "^11.14.1", + "@mui/icons-material": "^9.5.0", + "@mui/material": "^9.5.0", + "@tanstack/react-query": "^5.105.1", + "html2canvas": "^1.4.1", + "jsbarcode": "^3.12.3", + "jspdf": "^4.2.1", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "^7.18.5", + "stylis": "^4.4.0", + "stylis-plugin-rtl": "^2.1.1" + }, + "devDependencies": { + "@types/node": "^26.6.6", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@types/stylis": "^4.2.7", + "@vitejs/plugin-react": "^6.2.1", + "typescript": "^7.0.2", + "vite": "^8.3.5" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.13.tgz", + "integrity": "sha512-T5FRo+RzVHvGjWOuF1Ljc44b+NXAOazodHkGUHp4I3zCkQ4/sNVJm56h1S278LMR0bY5xBhztGziSbli8zObIw==", + "dependencies": { + "@babel/parser": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.13.tgz", + "integrity": "sha512-fWegr+WsEsiMVW4KUNdIIzzMTZSzNiqhy0//6+2MRi2d5NFNsL/AYwBQW8eBnRbTBVRnDVzjaJEUqKaCWjMMdQ==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.13.tgz", + "integrity": "sha512-fJM50YYjlTiBhgdkGmC1tBpv+FMAyo4annf2X6Aks+0yRlaiVkYW/3f07xAfVVkYIoZ9fFZp+mEThUFnuybhkQ==", + "dependencies": { + "@babel/types": "^7.29.11" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.13.tgz", + "integrity": "sha512-v+oN26xP4YIlQsbQ/CbTH1WG5m/l/DjKKZNy/Kp3f/AFvbgt7Em/D0FeMM3O2hX0YzeN2M16W8lOpyhIkfCBcQ==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.13.tgz", + "integrity": "sha512-0ve0xMlFA73dgY1oyJRY6RoW+/bncdcOQqg6jjYcVfXBK90OdLXjm9R6lmRetdZVrPjXkKIoMVBqYFPjcAlZ4Q==", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.11", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.11", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.11.tgz", + "integrity": "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==", + "dependencies": { + "@babel/helper-string-parser": "^7.29.11", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emotion/babel-plugin": { + "version": "11.13.5", + "resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.13.5.tgz", + "integrity": "sha512-pxHCpT2ex+0q+HH91/zsdHkw/lXd468DIN2zvfvLtPKLLMo6gQj7oLObq8PhkrxOZb/gGCq03S3Z7PDhS8pduQ==", + "dependencies": { + "@babel/helper-module-imports": "^7.16.7", + "@babel/runtime": "^7.18.3", + "@emotion/hash": "^0.9.2", + "@emotion/memoize": "^0.9.0", + "@emotion/serialize": "^1.3.3", + "babel-plugin-macros": "^3.1.0", + "convert-source-map": "^1.5.0", + "escape-string-regexp": "^4.0.0", + "find-root": "^1.1.0", + "source-map": "^0.5.7", + "stylis": "4.2.0" + } + }, + "node_modules/@emotion/babel-plugin/node_modules/stylis": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.2.0.tgz", + "integrity": "sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw==" + }, + "node_modules/@emotion/cache": { + "version": "11.14.0", + "resolved": "https://registry.npmjs.org/@emotion/cache/-/cache-11.14.0.tgz", + "integrity": "sha512-L/B1lc/TViYk4DcpGxtAVbx0ZyiKM5ktoIyafGkH6zg/tj+mA+NE//aPYKG0k8kCHSHVJrpLpcAlOBEXQ3SavA==", + "dependencies": { + "@emotion/memoize": "^0.9.0", + "@emotion/sheet": "^1.4.0", + "@emotion/utils": "^1.4.2", + "@emotion/weak-memoize": "^0.4.0", + "stylis": "4.2.0" + } + }, + "node_modules/@emotion/cache/node_modules/stylis": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.2.0.tgz", + "integrity": "sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw==" + }, + "node_modules/@emotion/hash": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.9.2.tgz", + "integrity": "sha512-MyqliTZGuOm3+5ZRSaaBGP3USLw6+EGykkwZns2EPC5g8jJ4z9OrdZY9apkl3+UP9+sdz76YYkwCKP5gh8iY3g==" + }, + "node_modules/@emotion/is-prop-valid": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-1.4.0.tgz", + "integrity": "sha512-QgD4fyscGcbbKwJmqNvUMSE02OsHUa+lAWKdEUIJKgqe5IwRSKd7+KhibEWdaKwgjLj0DRSHA9biAIqGBk05lw==", + "dependencies": { + "@emotion/memoize": "^0.9.0" + } + }, + "node_modules/@emotion/memoize": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@emotion/memoize/-/memoize-0.9.0.tgz", + "integrity": "sha512-30FAj7/EoJ5mwVPOWhAyCX+FPfMDrVecJAM+Iw9NRoSl4BBAQeqj4cApHHUXOVvIPgLVDsCFoz/hGD+5QQD1GQ==" + }, + "node_modules/@emotion/react": { + "version": "11.14.0", + "resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.14.0.tgz", + "integrity": "sha512-O000MLDBDdk/EohJPFUqvnp4qnHeYkVP5B0xEG0D/L7cOKP9kefu2DXn8dj74cQfsEzUqh+sr1RzFqiL1o+PpA==", + "dependencies": { + "@babel/runtime": "^7.18.3", + "@emotion/babel-plugin": "^11.13.5", + "@emotion/cache": "^11.14.0", + "@emotion/serialize": "^1.3.3", + "@emotion/use-insertion-effect-with-fallbacks": "^1.2.0", + "@emotion/utils": "^1.4.2", + "@emotion/weak-memoize": "^0.4.0", + "hoist-non-react-statics": "^3.3.1" + }, + "peerDependencies": { + "react": ">=16.8.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@emotion/serialize": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@emotion/serialize/-/serialize-1.3.3.tgz", + "integrity": "sha512-EISGqt7sSNWHGI76hC7x1CksiXPahbxEOrC5RjmFRJTqLyEK9/9hZvBbiYn70dw4wuwMKiEMCUlR6ZXTSWQqxA==", + "dependencies": { + "@emotion/hash": "^0.9.2", + "@emotion/memoize": "^0.9.0", + "@emotion/unitless": "^0.10.0", + "@emotion/utils": "^1.4.2", + "csstype": "^3.0.2" + } + }, + "node_modules/@emotion/sheet": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@emotion/sheet/-/sheet-1.4.0.tgz", + "integrity": "sha512-fTBW9/8r2w3dXWYM4HCB1Rdp8NLibOw2+XELH5m5+AkWiL/KqYX6dc0kKYlaYyKjrQ6ds33MCdMPEwgs2z1rqg==" + }, + "node_modules/@emotion/styled": { + "version": "11.14.1", + "resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.14.1.tgz", + "integrity": "sha512-qEEJt42DuToa3gurlH4Qqc1kVpNq8wO8cJtDzU46TjlzWjDlsVyevtYCRijVq3SrHsROS+gVQ8Fnea108GnKzw==", + "dependencies": { + "@babel/runtime": "^7.18.3", + "@emotion/babel-plugin": "^11.13.5", + "@emotion/is-prop-valid": "^1.3.0", + "@emotion/serialize": "^1.3.3", + "@emotion/use-insertion-effect-with-fallbacks": "^1.2.0", + "@emotion/utils": "^1.4.2" + }, + "peerDependencies": { + "@emotion/react": "^11.0.0-rc.0", + "react": ">=16.8.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@emotion/unitless": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.10.0.tgz", + "integrity": "sha512-dFoMUuQA20zvtVTuxZww6OHoJYgrzfKM1t52mVySDJnMSEa08ruEvdYQbhvyu6soU+NeLVd3yKfTfT0NeV6qGg==" + }, + "node_modules/@emotion/use-insertion-effect-with-fallbacks": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@emotion/use-insertion-effect-with-fallbacks/-/use-insertion-effect-with-fallbacks-1.2.0.tgz", + "integrity": "sha512-yJMtVdH59sxi/aVJBpk9FQq+OR8ll5GT8oWd57UpeaKEVGab41JWaCFA7FRLoMLloOZF/c/wsPoe+bfGmRKgDg==", + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@emotion/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@emotion/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-3vLclRofFziIa3J2wDh9jjbkUz9qk5Vi3IZ/FSTKViB0k+ef0fPV7dYrUIugbgupYDx7v9ud/SjrtEP8Y4xLoA==" + }, + "node_modules/@emotion/weak-memoize": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@emotion/weak-memoize/-/weak-memoize-0.4.0.tgz", + "integrity": "sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==" + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@mui/core-downloads-tracker": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-9.5.0.tgz", + "integrity": "sha512-PErEpl3Lp+1ZqWYKI7GQU8XSiciAFmLbUAZ7IoaUL598HLy1UAFuEUMEJu8yAS1v8vkXYzWprMVZzky4UwXoOA==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + } + }, + "node_modules/@mui/icons-material": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/icons-material/-/icons-material-9.5.0.tgz", + "integrity": "sha512-dahtVaqnRUIBgaZ4WC9EdP+LgJ5d2rslASYIX+nDFG6+ssUiM11jQ+Gd1wH8vhUGoNA9ES40MYics5BI8zJFXQ==", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@mui/material": "^9.5.0", + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@mui/material": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/material/-/material-9.5.0.tgz", + "integrity": "sha512-QgqvdVjZoKxP8E8SBxYY6LrdV+kw00moXweZQWBbMMdifPKZAGfUaaXhGKIca6fjKnCL6HJIe/AWWCpqNvyHVw==", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5", + "@mui/core-downloads-tracker": "^9.5.0", + "@mui/system": "^9.5.0", + "@mui/types": "^9.5.0", + "@mui/utils": "^9.5.0", + "@popperjs/core": "^2.11.8", + "@types/react-transition-group": "^4.4.12", + "clsx": "^2.1.1", + "csstype": "^3.2.3", + "prop-types": "^15.8.1", + "react-is": "^19.3.0", + "react-transition-group": "^4.4.5" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@emotion/react": "^11.5.0", + "@emotion/styled": "^11.3.0", + "@mui/material-pigment-css": "^9.5.0", + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/react": { + "optional": true + }, + "@emotion/styled": { + "optional": true + }, + "@mui/material-pigment-css": { + "optional": true + }, + "@types/react": { + "optional": true + } + } + }, + "node_modules/@mui/private-theming": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-9.5.0.tgz", + "integrity": "sha512-UHZKySlr4ZJeA5HEhe/Tq1fhsR5573ViKYn7JV80dCVJtgqRQIplRSer1DHPg2Yi22llX7QRhgM0Vtrx4kZHSA==", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5", + "@mui/utils": "^9.5.0", + "prop-types": "^15.8.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@mui/styled-engine": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-9.5.0.tgz", + "integrity": "sha512-IX1ceHnZ0bJgzJRWO/Ayl4ME1rNmpWVYwV28yb089UAMR17rJkV1qfr7ApsWQXXPi1oi+2JapJrWQAiAnTlJHQ==", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5", + "@emotion/cache": "^11.14.0", + "@emotion/serialize": "^1.3.3", + "@emotion/sheet": "^1.4.0", + "csstype": "^3.2.3", + "prop-types": "^15.8.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@emotion/react": "^11.4.1", + "@emotion/styled": "^11.3.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/react": { + "optional": true + }, + "@emotion/styled": { + "optional": true + } + } + }, + "node_modules/@mui/system": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/system/-/system-9.5.0.tgz", + "integrity": "sha512-OZuAwvoiaaHpvn0a540VH1DUwwmojJubGfNmO2g+nb2ybNDP4/gF7t7aA6AMduELSuJ5yxwlzyFvUO3CfLv1Yg==", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5", + "@mui/private-theming": "^9.5.0", + "@mui/styled-engine": "^9.5.0", + "@mui/types": "^9.5.0", + "@mui/utils": "^9.5.0", + "clsx": "^2.1.1", + "csstype": "^3.2.3", + "prop-types": "^15.8.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@emotion/react": "^11.5.0", + "@emotion/styled": "^11.3.0", + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/react": { + "optional": true + }, + "@emotion/styled": { + "optional": true + }, + "@types/react": { + "optional": true + } + } + }, + "node_modules/@mui/types": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/types/-/types-9.5.0.tgz", + "integrity": "sha512-O0S6xS80qEQqW2CYNrd4GlBEQ1xpMOHZ5b4zO/DaLu6NZmtthM6smEg0Gz/u9gX5vL+8NB3EiBIxmxSCcG590Q==", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5" + }, + "peerDependencies": { + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@mui/utils": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-9.5.0.tgz", + "integrity": "sha512-8m0LfSgE2pj58znY3kZ+anwRKbnBkcu/7AJPA8L/77wEjN0QnpX4/zRAccyplp1VEUnMsUBADeTRin5Mkf7epA==", + "dependencies": { + "@babel/runtime": "^7.29.7 || ^8.0.5", + "@mui/types": "^9.5.0", + "@types/prop-types": "^15.7.15", + "clsx": "^2.1.1", + "prop-types": "^15.8.1", + "react-is": "^19.3.0" + }, + "engines": { + "node": ">=14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mui-org" + }, + "peerDependencies": { + "@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@popperjs/core": { + "version": "2.11.8", + "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", + "integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.18.tgz", + "integrity": "sha512-ubTG+4KlidvioxjOFdsdEa2F6JVGZb8m2ByJUqQ7fYzUeT1cEn194POcsQ10PKH4p//q0YQn4SB3YpSuzcA1Yg==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.18.tgz", + "integrity": "sha512-2Xa1t/JeFGTZn5TbzgPppcCftF8sCVnTNvrIvoSdcZhoFzAuVy1L3xxQUQ4sfWDtwVzg1u6Yi1R3SlJugRNV2Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.18.tgz", + "integrity": "sha512-iUzw9HshVvrWci9gVXjxWS7/M/IcLvNo67vu2c/w9zKBz4hIvPRixdUpIW/iCfhldLaq9ER2hecsI9UY5z0/yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.18.tgz", + "integrity": "sha512-XuDHFzbFEtZl0QGJi92+fmG67tfnp1iZ9VOeDkwasGyTq2VG3/5PnJnvAr+MTzFh/rNScJ3VhN+XpZyyGsN7Jw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.18.tgz", + "integrity": "sha512-MM8opLfsLK15oEXDz6iBc0t3ahu+ew9jsAmha+ovZ33hSwYgqo7YmpRITqFTfW7xA71BLEQ3jJdTsaCmhB1c9w==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.18.tgz", + "integrity": "sha512-J6EoCWiy5RnFQzHrKyHXXevZ9lukQfGpnchX/zG/k/WC2nc9O9XyS1JgA8kI9VxMFggMbCPjpv7LcikriXfehw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.18.tgz", + "integrity": "sha512-HIkFuLF7CdDeki+1aCZLLbLq0hk/PHntb+z4/YCTo47JbksTD6jJEELIz92tYROmDmvMrNqUMqBi71BkJLDR+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.18.tgz", + "integrity": "sha512-4oqWItLLYt7IceOnElCct8T2ek5p7PmD7LN04TRJRXGo5f3HtKTgGH6PhYRFK4C2ICkq/LMUU0BVPvvlAKhm8g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.18.tgz", + "integrity": "sha512-+AkRly5SrCEgnPhGRfub7pucASYEC2fTsxZg7VCcnozpA2+Wn/gCYy1t7LuJS67/xyJu/7noYBJncDUkbwgw2A==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.18.tgz", + "integrity": "sha512-Ttg1r9vVykMnQrE/GwYO9icKtXiuiMfRe/w74xJkeoVuvhRG+WtT6LEMOf58Yl63yd77lhHzO8Y55R8CC3XALA==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.18.tgz", + "integrity": "sha512-xX1Tt4o5jUMma0vJsXp5eRZA9nOuyigb2dKJMMzZRmzMxLYGE9PaKKSqHPzPvSQgM8ZOEacSTQwDQcwWfh0xmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.18.tgz", + "integrity": "sha512-4VVlGI5K2kociZlW3lSN8VjG3TW5yQIlAcfCdBXMgGjJxZll15Fa4ocRHXHvIVVnwlibCw/NQajJrNDiqqpiiw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.18.tgz", + "integrity": "sha512-PApTsgH1jLYuyy3tSCz9De82Gq5qXwi7vImVZhEzTgX1C4150Cp5M2ZfL3pLvbCvbEHL0oJeC6pd6podtv8Y5w==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.18.tgz", + "integrity": "sha512-J2XjWjx/SP+4x0H4r6dz3Vzb5WVkg7re40Do9K7HJ3sK2/xcmZrWwakXlSwaMvOkvruLJCD4CL/3wqsIR/thgg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.18.tgz", + "integrity": "sha512-XwRJxRQvkuEtS0hIIt29QrqPJ+JzMJSNYHJw4ae/mc6uEarfRG1ceyg4HmmWiBdL/YCb6g7N5BLbSvmRJRYZHw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.0.tgz", + "integrity": "sha512-K+NU2HDCEem4sClgHH4ZZXwdJeNFkJo+hRk479DIwdIviAPN2hFJH1KHHwg8CxHQXvi0M5XY4deTXINfIiSG6w==", + "dev": true + }, + "node_modules/@tanstack/query-core": { + "version": "5.107.1", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.107.1.tgz", + "integrity": "sha512-PSyAik11oQBEVOiVy5hjZWHmoUqOXqK1WYy4v55mcxozEfKaQgpUMsgnXhWjuESzSht8JfzqMS1m6M/9CpNgvg==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.107.1", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.107.1.tgz", + "integrity": "sha512-udCOOLp3ZAheUrIHLCe+ZZge6nr2ZUrGMSWcCuXsjY1Bf2JeeE09oxst97PILiCY6N8xo/7bIo3Hvz13zh06FA==", + "dependencies": { + "@tanstack/query-core": "5.107.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@types/react": "^18 || ^19", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/pako": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/pako/-/pako-2.0.4.tgz", + "integrity": "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==" + }, + "node_modules/@types/parse-json": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz", + "integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==" + }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==" + }, + "node_modules/@types/raf": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@types/raf/-/raf-3.4.3.tgz", + "integrity": "sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==", + "optional": true + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@types/react-transition-group": { + "version": "4.4.12", + "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.12.tgz", + "integrity": "sha512-8TV6R3h2j7a91c+1DXdJi3Syo69zzIZbz7Lg5tORM5LEJG7X/E6a1V3drRyBRZq7/utz7A+c4OgYLiLcYGHG6w==", + "peerDependencies": { + "@types/react": "*" + } + }, + "node_modules/@types/stylis": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/@types/stylis/-/stylis-4.2.7.tgz", + "integrity": "sha512-VgDNokpBoKF+wrdvhAAfS55OMQpL6QRglwTwNC3kIgBrzZxA4WsFj+2eLfEA/uMUDzBcEhYmjSbwQakn/i3ajA==", + "dev": true + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "optional": true + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.0.tgz", + "integrity": "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw==", + "dev": true, + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": ">=0.152.0 <0.157.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/babel-plugin-macros": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz", + "integrity": "sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==", + "dependencies": { + "@babel/runtime": "^7.12.5", + "cosmiconfig": "^7.0.0", + "resolve": "^1.19.0" + }, + "engines": { + "node": ">=10", + "npm": ">=6" + } + }, + "node_modules/base64-arraybuffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz", + "integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/canvg": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/canvg/-/canvg-3.0.11.tgz", + "integrity": "sha512-5ON+q7jCTgMp9cjpu4Jo6XbvfYwSB2Ow3kzHKfIyJfaCAOHLbdKPQqGKgfED/R5B+3TFFfe8pegYA+b423SRyA==", + "optional": true, + "dependencies": { + "@babel/runtime": "^7.12.5", + "@types/raf": "^3.4.0", + "core-js": "^3.8.3", + "raf": "^3.4.1", + "regenerator-runtime": "^0.13.7", + "rgbcolor": "^1.0.1", + "stackblur-canvas": "^2.0.0", + "svg-pathdata": "^6.0.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==" + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/core-js": { + "version": "3.51.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.51.0.tgz", + "integrity": "sha512-7bDKx/5jm5MxzsXxc93g6Z2+4ZsuT/MddrfRmTDJNAkWsYWHU8EVNEsBiIEWnMAMCHMmRfUEjkuo3jeNBOIHRw==", + "hasInstallScript": true, + "optional": true, + "engines": { + "node": "*" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/cosmiconfig": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz", + "integrity": "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==", + "dependencies": { + "@types/parse-json": "^4.0.0", + "import-fresh": "^3.2.1", + "parse-json": "^5.0.0", + "path-type": "^4.0.0", + "yaml": "^1.10.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/cosmiconfig/node_modules/yaml": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", + "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", + "engines": { + "node": ">= 6" + } + }, + "node_modules/css-line-break": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/css-line-break/-/css-line-break-2.1.0.tgz", + "integrity": "sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==", + "dependencies": { + "utrie": "^1.0.2" + } + }, + "node_modules/cssjanus": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/cssjanus/-/cssjanus-2.3.1.tgz", + "integrity": "sha512-gWZQ/S0tthU2KCc55C5zbjxQN0XPK1sT0qufCqwCNUauGIsPDOfdBMBWosP+Kd4wf2A2Nxm/z6JAP6yNGnS7QQ==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/dom-helpers": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz", + "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==", + "dependencies": { + "@babel/runtime": "^7.8.7", + "csstype": "^3.0.2" + } + }, + "node_modules/dompurify": { + "version": "3.4.17", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz", + "integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==", + "optional": true, + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/error-ex": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fast-png": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/fast-png/-/fast-png-6.4.0.tgz", + "integrity": "sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==", + "dependencies": { + "@types/pako": "^2.0.3", + "iobuffer": "^5.3.2", + "pako": "^2.1.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==" + }, + "node_modules/find-root": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz", + "integrity": "sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hoist-non-react-statics": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz", + "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==", + "dependencies": { + "react-is": "^16.7.0" + } + }, + "node_modules/hoist-non-react-statics/node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + }, + "node_modules/html2canvas": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz", + "integrity": "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==", + "dependencies": { + "css-line-break": "^2.1.0", + "text-segmentation": "^1.0.3" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/iobuffer": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/iobuffer/-/iobuffer-5.4.0.tgz", + "integrity": "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==" + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==" + }, + "node_modules/is-core-module": { + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.18.0.tgz", + "integrity": "sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw==", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/jsbarcode": { + "version": "3.12.3", + "resolved": "https://registry.npmjs.org/jsbarcode/-/jsbarcode-3.12.3.tgz", + "integrity": "sha512-CuHU9hC6dPsHF5oVFMo8NW76uQVjH4L22CsP4hW+dNnGywJHC/B0ThA1CTDVLnxKLrrpYdicBLnd2xsgTfRnvg==" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" + }, + "node_modules/jspdf": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/jspdf/-/jspdf-4.2.1.tgz", + "integrity": "sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ==", + "dependencies": { + "@babel/runtime": "^7.28.6", + "fast-png": "^6.2.0", + "fflate": "^0.8.1" + }, + "optionalDependencies": { + "canvg": "^3.0.11", + "core-js": "^3.6.0", + "dompurify": "^3.3.1", + "html2canvas": "^1.0.0-rc.5" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pako": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz", + "integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ] + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "engines": { + "node": ">=8" + } + }, + "node_modules/performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==", + "optional": true + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/prop-types/node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + }, + "node_modules/raf": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz", + "integrity": "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==", + "optional": true, + "dependencies": { + "performance-now": "^2.1.0" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-is": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz", + "integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==" + }, + "node_modules/react-router": { + "version": "7.18.5", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.5.tgz", + "integrity": "sha512-dTgvcXDOrLPrlLHrcZAqWveiK1hMSqN+rGAJzegP8HtmNkfRxOoshGWBNX3ZJ0cZjOHkRdlUJtaIhZMLLyGyPw==", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.18.5", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.5.tgz", + "integrity": "sha512-9HcfDMU6JJ/fp6gJZYGwNE6RknVGS4kBjH1HkNw959mCJi70TVwdipQWv2FEol9uGpi+SZTFtVpJPtEQfayeOw==", + "dependencies": { + "react-router": "7.18.5" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/react-transition-group": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", + "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==", + "dependencies": { + "@babel/runtime": "^7.5.5", + "dom-helpers": "^5.0.1", + "loose-envify": "^1.4.0", + "prop-types": "^15.6.2" + }, + "peerDependencies": { + "react": ">=16.6.0", + "react-dom": ">=16.6.0" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", + "optional": true + }, + "node_modules/resolve": { + "version": "1.22.14", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz", + "integrity": "sha512-1ZjYvR9sbkiwC5+9QHetqW5HmA2pHRMaoupD01t2HlYnV/vydC2zPwLixhsMieSWVZt0JJRg5LVIk0Ow1D/TrA==", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.18.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "engines": { + "node": ">=4" + } + }, + "node_modules/rgbcolor": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/rgbcolor/-/rgbcolor-1.0.1.tgz", + "integrity": "sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==", + "optional": true, + "engines": { + "node": ">= 0.8.15" + } + }, + "node_modules/rolldown": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.18.tgz", + "integrity": "sha512-C1uuT3UR60SShuCaPQFAAZyefJCWZlAKB02BV3BuPE2Rs4fevRQltEKoFO2tV5W9/eJhU5RieV6vJj3euulfNQ==", + "dev": true, + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.18", + "@rolldown/binding-android-arm64": "1.2.18", + "@rolldown/binding-darwin-arm64": "1.2.18", + "@rolldown/binding-darwin-x64": "1.2.18", + "@rolldown/binding-freebsd-x64": "1.2.18", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.18", + "@rolldown/binding-linux-arm64-gnu": "1.2.18", + "@rolldown/binding-linux-arm64-musl": "1.2.18", + "@rolldown/binding-linux-ppc64-gnu": "1.2.18", + "@rolldown/binding-linux-s390x-gnu": "1.2.18", + "@rolldown/binding-linux-x64-gnu": "1.2.18", + "@rolldown/binding-linux-x64-musl": "1.2.18", + "@rolldown/binding-openharmony-arm64": "1.2.18", + "@rolldown/binding-win32-arm64-msvc": "1.2.18", + "@rolldown/binding-win32-x64-msvc": "1.2.18" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==" + }, + "node_modules/set-cookie-parser": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.3.tgz", + "integrity": "sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==" + }, + "node_modules/source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackblur-canvas": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/stackblur-canvas/-/stackblur-canvas-2.7.0.tgz", + "integrity": "sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==", + "optional": true, + "engines": { + "node": ">=0.1.14" + } + }, + "node_modules/stylis": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.4.0.tgz", + "integrity": "sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==" + }, + "node_modules/stylis-plugin-rtl": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/stylis-plugin-rtl/-/stylis-plugin-rtl-2.1.1.tgz", + "integrity": "sha512-q6xIkri6fBufIO/sV55md2CbgS5c6gg9EhSVATtHHCdOnbN/jcI0u3lYhNVeuI65c4lQPo67g8xmq5jrREvzlg==", + "dependencies": { + "cssjanus": "^2.0.1" + }, + "peerDependencies": { + "stylis": "4.x" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/svg-pathdata": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/svg-pathdata/-/svg-pathdata-6.0.3.tgz", + "integrity": "sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==", + "optional": true, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/text-segmentation": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/text-segmentation/-/text-segmentation-1.0.3.tgz", + "integrity": "sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==", + "dependencies": { + "utrie": "^1.0.2" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true + }, + "node_modules/utrie": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/utrie/-/utrie-1.0.2.tgz", + "integrity": "sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==", + "dependencies": { + "base64-arraybuffer": "^1.0.2" + } + }, + "node_modules/vite": { + "version": "8.3.7", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.7.tgz", + "integrity": "sha512-oxh0dMxrayBr33ScJvvBJ2HBQ2jc1TBrXKR2NyL/MJ9WPuX19mN2DXWUmywKdyw5RFVQBo8hmtb2FMC0LHrnng==", + "dev": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "optional": true, + "peer": true, + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..2e5cf14 --- /dev/null +++ b/web/package.json @@ -0,0 +1,39 @@ +{ + "name": "ntp-web", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "build:qa": "tsc --noEmit && vite build --mode qa", + "build:prod": "tsc --noEmit && vite build --mode production", + "typecheck": "tsc --noEmit", + "preview": "vite preview" + }, + "dependencies": { + "@emotion/cache": "^11.14.0", + "@emotion/react": "^11.14.0", + "@emotion/styled": "^11.14.1", + "@mui/icons-material": "^9.5.0", + "@mui/material": "^9.5.0", + "@tanstack/react-query": "^5.105.1", + "html2canvas": "^1.4.1", + "jsbarcode": "^3.12.3", + "jspdf": "^4.2.1", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-router-dom": "^7.18.5", + "stylis": "^4.4.0", + "stylis-plugin-rtl": "^2.1.1" + }, + "devDependencies": { + "@types/node": "^26.6.6", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@types/stylis": "^4.2.7", + "@vitejs/plugin-react": "^6.2.1", + "typescript": "^7.0.2", + "vite": "^8.3.5" + } +} diff --git a/web/public/brand/nafith-ar.gif b/web/public/brand/nafith-ar.gif new file mode 100644 index 0000000..f362a4f Binary files /dev/null and b/web/public/brand/nafith-ar.gif differ diff --git a/web/public/brand/nafith-en.jpg b/web/public/brand/nafith-en.jpg new file mode 100644 index 0000000..67480f7 Binary files /dev/null and b/web/public/brand/nafith-en.jpg differ diff --git a/web/src/App.tsx b/web/src/App.tsx new file mode 100644 index 0000000..7bc4076 --- /dev/null +++ b/web/src/App.tsx @@ -0,0 +1,40 @@ +import { useEffect, useMemo } from 'react'; +import { RouterProvider, createBrowserRouter } from 'react-router-dom'; +import { useToast } from '@/providers/ToastProvider'; +import { featureRoutes } from '@/registry'; +import { AppShell } from '@/shell/AppShell'; +import { DashboardPage } from '@/shell/DashboardPage'; +import { NotFoundPage } from '@/shell/ErrorPages'; +import { LoginPage } from '@/shell/LoginPage'; +import { ProtectedRoute } from '@/shell/ProtectedRoute'; + +export function App() { + const router = useMemo( + () => + createBrowserRouter([ + { path: '/login', element: }, + { + element: , + children: [ + { + element: , + children: [{ index: true, element: }, ...featureRoutes, { path: '*', element: }], + }, + ], + }, + ]), + [], + ); + // a response message does not follow the user to another page + const toast = useToast(); + useEffect(() => { + let path = router.state.location.pathname; + return router.subscribe((state) => { + if (state.location.pathname !== path) { + path = state.location.pathname; + toast.dismissOnNavigate(); + } + }); + }, [router, toast]); + return ; +} diff --git a/web/src/api/activity.ts b/web/src/api/activity.ts new file mode 100644 index 0000000..c81505e --- /dev/null +++ b/web/src/api/activity.ts @@ -0,0 +1,28 @@ +import { useSyncExternalStore } from 'react'; + +/** Global in-flight request counters: reads drive the slim progress bar, writes drive the blocking overlay. */ +interface Snapshot { reads: number; writes: number } +let state: Snapshot = { reads: 0, writes: 0 }; +const listeners = new Set<() => void>(); + +function emit(next: Snapshot) { + state = next; + listeners.forEach((l) => l()); +} + +export function trackStart(kind: 'read' | 'write'): () => void { + emit(kind === 'read' ? { ...state, reads: state.reads + 1 } : { ...state, writes: state.writes + 1 }); + let done = false; + return () => { + if (done) return; + done = true; + emit(kind === 'read' ? { ...state, reads: state.reads - 1 } : { ...state, writes: state.writes - 1 }); + }; +} + +export function useActivity(): Snapshot { + return useSyncExternalStore( + (cb) => { listeners.add(cb); return () => { listeners.delete(cb); }; }, + () => state, + ); +} diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts new file mode 100644 index 0000000..4d824c0 --- /dev/null +++ b/web/src/api/auth.ts @@ -0,0 +1,79 @@ +/** + * THE ONLY FILE that knows the auth endpoint shapes. If the backend contract differs, change it here. + * POST /auth/login {userName,password} -> {accessToken, user:{...}, mustChangePassword} + * GET /auth/me -> user (or {user}) + * POST /auth/language {lang} -> {accessToken,...} (new token carries the language) + * POST /auth/change-password {oldPassword,newPassword} + */ +import { api, setToken } from './client'; + +export interface AuthUser { + userId: number | string; + name: string; + roleCode: string; + roleName: string; + domain: string; + locationId: number | string | null; + locationName: string; + stkId: number | string | null; + compId: number | string | null; + companyCode: string; + lang: string; + isStaff: boolean; +} + +export interface LoginResult { + token: string; + user: AuthUser; +} + +type Raw = Record; + +function toUser(raw: Raw): AuthUser { + const s = (v: unknown) => (v === undefined || v === null ? '' : String(v)); + const idOrNull = (v: unknown) => (v === undefined || v === null || v === '' ? null : (v as number | string)); + return { + userId: (raw.userId as number | string) ?? '', + name: s(raw.name), + roleCode: s(raw.roleCode), + roleName: s(raw.roleName), + domain: s(raw.domain), + locationId: idOrNull(raw.locationId), + locationName: s(raw.locationName), + stkId: idOrNull(raw.stkId), + compId: idOrNull(raw.compId), + companyCode: s(raw.companyCode), + lang: s(raw.lang), + isStaff: Boolean(raw.isStaff), + }; +} + +/** GET /auth/permissions: what the caller's role code may see. SU gets all=true. */ +export interface Permissions { + roleCode: string; + all: boolean; + allowed: string[]; +} + +export const authApi = { + async permissions(): Promise { + const r = await api.get('/auth/permissions', undefined, { silent: true }); + return { roleCode: String(r.roleCode ?? ''), all: Boolean(r.all), allowed: Array.isArray(r.allowed) ? (r.allowed as unknown[]).map(String) : [] }; + }, + async login(username: string, password: string): Promise { + const r = await api.post('/auth/login', { userName: username, password }, { noAuthRedirect: true }); + return { token: String(r.accessToken), user: toUser((r.user as Raw) ?? {}) }; + }, + async me(): Promise { + const r = await api.get('/auth/me', undefined, { silent: true }); + return toUser(((r.user as Raw | undefined) ?? r) as Raw); + }, + async setLanguage(lang: 'ar' | 'en'): Promise { + const r = await api.post('/auth/language', { lang: lang.toUpperCase() }, { silent: true }); + if (r && typeof r.accessToken === 'string') setToken(r.accessToken); + return r; + }, + changePassword(currentPassword: string, newPassword: string): Promise<{ message?: string } | undefined> { + return api.post('/auth/change-password', { oldPassword: currentPassword, newPassword }); + }, +}; diff --git a/web/src/api/client.ts b/web/src/api/client.ts new file mode 100644 index 0000000..09beb1a --- /dev/null +++ b/web/src/api/client.ts @@ -0,0 +1,117 @@ +import { ssGet, ssSet } from '@/lib/storage'; +import { uiText, type Lang } from '@/i18n/ui'; +import { trackStart } from './activity'; +import { mockRequest } from './mock'; + +/** API address: same-origin '/api/v1' by default (Vite proxy in development, reverse proxy in QA/production); set VITE_API_BASE to point elsewhere. */ +export const API_BASE = (import.meta.env.VITE_API_BASE as string | undefined)?.replace(/\/$/, '') || '/api/v1'; +export const MOCK = import.meta.env.VITE_MOCK === '1'; + +export { ApiError, type ProblemDetails } from './errors'; +import { ApiError, type ProblemDetails } from './errors'; + +// ---- token (memory + sessionStorage fallback) ---- +const TOKEN_KEY = 'ntp.token'; +let token: string | null = ssGet(TOKEN_KEY); +export function getToken(): string | null { return token; } +export function setToken(t: string | null): void { + token = t; + ssSet(TOKEN_KEY, t); +} + +let currentLang: Lang = 'ar'; +export function setApiLang(l: Lang): void { currentLang = l; } + +let onUnauthorized: (() => void) | null = null; +export function setUnauthorizedHandler(fn: (() => void) | null): void { onUnauthorized = fn; } + +export interface RequestOptions { + params?: Record; + body?: unknown; + /** FormData bodies are sent as-is (multipart). */ + form?: FormData; + signal?: AbortSignal; + /** Do not trigger the global progress bar / saving overlay. */ + silent?: boolean; + /** Treat a 401 as a normal error (login call). */ + noAuthRedirect?: boolean; +} + +function buildUrl(path: string, params?: Record): string { + const url = path.startsWith('http') ? path : `${API_BASE}${path.startsWith('/') ? '' : '/'}${path}`; + if (!params) return url; + const qs = new URLSearchParams(); + for (const [k, v] of Object.entries(params)) { + if (v === undefined || v === null || v === '') continue; + qs.append(k, String(v)); + } + const s = qs.toString(); + return s ? `${url}${url.includes('?') ? '&' : '?'}${s}` : url; +} + +async function toError(res: Response): Promise { + let problem: ProblemDetails | undefined; + try { + problem = (await res.json()) as ProblemDetails; + } catch { /* not JSON */ } + const fallback = + res.status === 403 ? uiText('error.forbidden', currentLang) + : res.status === 404 ? uiText('error.notFound', currentLang) + : uiText('error.generic', currentLang); + // Backend message is shown verbatim: detail first, then title. + const message = problem?.detail || problem?.title || fallback; + return new ApiError(res.status, message, problem); +} + +export async function request(method: string, path: string, opts: RequestOptions = {}): Promise { + const isWrite = method !== 'GET'; + const done = opts.silent ? () => {} : trackStart(isWrite ? 'write' : 'read'); + try { + if (MOCK) { + const out = await mockRequest(method, path, opts.params, opts.body ?? opts.form); + return out as T; + } + const headers: Record = { Accept: 'application/json', 'Accept-Language': currentLang }; + if (token) headers.Authorization = `Bearer ${token}`; + let body: BodyInit | undefined; + if (opts.form) body = opts.form; + else if (opts.body !== undefined) { + headers['Content-Type'] = 'application/json'; + body = JSON.stringify(opts.body); + } + let res: Response; + try { + res = await fetch(buildUrl(path, opts.params), { method, headers, body, signal: opts.signal }); + } catch (e) { + if (e instanceof DOMException && e.name === 'AbortError') throw e; + throw new ApiError(0, uiText('error.network', currentLang), { code: 'NETWORK' }); + } + if (!res.ok) { + if (res.status === 401 && !opts.noAuthRedirect) onUnauthorized?.(); + throw await toError(res); + } + if (res.status === 204) return undefined as T; + const text = await res.text(); + return (text ? JSON.parse(text) : undefined) as T; + } finally { + done(); + } +} + +export const api = { + get: (path: string, params?: Record, o?: Omit) => + request('GET', path, { ...o, params }), + post: (path: string, body?: unknown, o?: Omit) => request('POST', path, { ...o, body }), + put: (path: string, body?: unknown, o?: Omit) => request('PUT', path, { ...o, body }), + patch: (path: string, body?: unknown, o?: Omit) => request('PATCH', path, { ...o, body }), + delete: (path: string, o?: RequestOptions) => request('DELETE', path, o), + upload: (path: string, form: FormData, o?: Omit) => request('POST', path, { ...o, form }), +}; + +/** Standard paged list envelope returned by every list endpoint. */ +export interface PagedResult { + items: T[]; + page: number; + pageSize: number; + totalCount: number; +} diff --git a/web/src/api/errors.ts b/web/src/api/errors.ts new file mode 100644 index 0000000..0496d9f --- /dev/null +++ b/web/src/api/errors.ts @@ -0,0 +1,34 @@ +/** RFC 7807 ProblemDetails as returned by the .NET GlobalExceptionHandler (+ our stable `code`). */ +export interface ProblemDetails { + type?: string; + title?: string; + status?: number; + detail?: string; + code?: string; + errors?: Record; + [k: string]: unknown; +} + +export class ApiError extends Error { + readonly status: number; + readonly code?: string; + /** Field-level errors keyed by (camel-cased) field name, first message per field. */ + readonly fieldErrors: Record; + readonly problem?: ProblemDetails; + + constructor(status: number, message: string, problem?: ProblemDetails) { + super(message); + this.name = 'ApiError'; + this.status = status; + this.code = problem?.code; + this.problem = problem; + this.fieldErrors = {}; + if (problem?.errors) { + for (const [k, v] of Object.entries(problem.errors)) { + const key = k.length ? k.charAt(0).toLowerCase() + k.slice(1) : k; + this.fieldErrors[key] = Array.isArray(v) ? String(v[0] ?? '') : String(v); + } + } + } +} + diff --git a/web/src/api/hooks.ts b/web/src/api/hooks.ts new file mode 100644 index 0000000..80156ef --- /dev/null +++ b/web/src/api/hooks.ts @@ -0,0 +1,38 @@ +import { useMutation, useQueryClient, type QueryKey } from '@tanstack/react-query'; +import { ApiError } from './client'; +import { useToast } from '@/providers/ToastProvider'; +import { useUi } from '@/i18n/useUi'; + +export interface WriteOptions { + /** Query keys to invalidate after success. */ + invalidate?: QueryKey[]; + /** Overrides the default success text. The backend `message` in the response always wins when present. */ + successMessage?: string; + /** Toast the success message (default true). */ + toastSuccess?: boolean; + onSuccess?: (res: TRes) => void; +} + +/** + * Standard write hook: runs `fn`, toasts the backend message verbatim (success) or the ApiError message (error), + * invalidates the given queries. The blocking "Saving..." overlay comes from the API client for non-GET calls. + */ +export function useWrite(fn: (vars: TVars) => Promise, opts: WriteOptions = {}) { + const qc = useQueryClient(); + const toast = useToast(); + const { t } = useUi(); + return useMutation({ + mutationFn: fn, + onSuccess: async (res) => { + if (opts.toastSuccess !== false) { + const m = (res as { message?: unknown } | undefined)?.message; + toast.success(typeof m === 'string' && m ? m : opts.successMessage ?? t('toast.saved')); + } + await Promise.all((opts.invalidate ?? []).map((k) => qc.invalidateQueries({ queryKey: k }))); + opts.onSuccess?.(res); + }, + onError: (e) => { + toast.error(e instanceof ApiError ? e.message : t('error.generic')); + }, + }); +} diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts new file mode 100644 index 0000000..3778563 --- /dev/null +++ b/web/src/api/mock.ts @@ -0,0 +1,83 @@ +import { ApiError } from './errors'; +/** + * Mock fetch layer, active only when VITE_MOCK=1. Features register handlers (see features/_example/mock.ts); + * the API client routes every request through `mockRequest` instead of fetch. + */ +export interface MockRequest { + method: string; + path: string; + params: Record; + body: unknown; + match: RegExpMatchArray; +} +type Handler = (req: MockRequest) => unknown | Promise; +interface Route { method: string; pattern: RegExp; handler: Handler } + +const routes: Route[] = []; + +/** `pattern` is matched against the path WITHOUT the /api/v1 prefix, e.g. /^\/example\/vehicles$/ */ +export function registerMock(method: string, pattern: RegExp, handler: Handler): void { + routes.push({ method: method.toUpperCase(), pattern, handler }); +} + +const delay = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +export class MockHttpError extends Error { + constructor(public status: number, message: string, public problem?: Record) { + super(message); + } +} + +export async function mockRequest( + method: string, + path: string, + params?: Record, + body?: unknown, +): Promise { + await delay(method === 'GET' ? 350 : 700); + const clean: Record = {}; + for (const [k, v] of Object.entries(params ?? {})) if (v !== undefined && v !== null && v !== '') clean[k] = String(v); + const route = routes.find((r) => r.method === method && r.pattern.test(path)); + if (!route) throw asApiError(404, `Mock: no handler for ${method} ${path}`); + try { + return await route.handler({ method, path, params: clean, body, match: path.match(route.pattern)! }); + } catch (e) { + if (e instanceof MockHttpError) throw asApiError(e.status, e.message, e.problem); + throw e; + } +} + +function asApiError(status: number, message: string, problem?: Record) { + return new ApiError(status, message, { title: message, status, ...problem }); +} + +// ---- mock auth (any password works; username "bad" fails) ---- +registerMock('POST', /^\/auth\/login$/, (req) => { + const b = req.body as { username?: string; password?: string }; + if (!b?.username || b.username === 'bad') throw new MockHttpError(401, 'اسم المستخدم أو كلمة المرور غير صحيحة'); + return { + token: 'mock-token', + user: { + userId: 1001, + name: b.username, + roleCode: 'SU', + roleName: 'Super user', + domain: 'NTP', + locationId: 5, + locationName: 'Sohar', + stkId: 77, + compId: 12, + companyCode: 'NAF', + lang: 'AR', + isStaff: true, + }, + }; +}); +registerMock('GET', /^\/auth\/me$/, () => ({ + userId: 1001, name: 'demo', roleCode: 'SU', roleName: 'Super user', domain: 'NTP', locationId: 5, + locationName: 'Sohar', stkId: 77, compId: 12, companyCode: 'NAF', lang: 'AR', isStaff: true, +})); +registerMock('GET', /^\/auth\/permissions$/, () => ({ roleCode: 'SU', all: true, allowed: [] })); +registerMock('PUT', /^\/auth\/language$/, () => ({})); +registerMock('POST', /^\/auth\/change-password$/, () => ({ message: 'تم تغيير كلمة المرور' })); +registerMock('POST', /^\/files\/temp$/, () => ({ id: `tmp-${Date.now()}` })); diff --git a/web/src/components/Barcode.tsx b/web/src/components/Barcode.tsx new file mode 100644 index 0000000..97b80a5 --- /dev/null +++ b/web/src/components/Barcode.tsx @@ -0,0 +1,22 @@ +import { useEffect, useRef } from 'react'; +import JsBarcode from 'jsbarcode'; + +/** + * Code 128 barcode of `value`, drawn on a canvas (black bars on white, no caption). Drawn synchronously in the effect so the + * PDF capture never sees an empty canvas. Legacy printed the permit number as a barcode image + * (application.objCMN.generatebarCode); this is the same idea. + */ +export function Barcode({ value, height = 64, barWidth = 2 }: { value: string; height?: number; barWidth?: number }) { + const ref = useRef(null); + + useEffect(() => { + if (!value || !ref.current) return; + try { + JsBarcode(ref.current, value, { format: 'CODE128', displayValue: false, width: barWidth, height, margin: 0, background: '#ffffff', lineColor: '#000000' }); + } catch { + /* an unprintable value simply leaves the canvas empty */ + } + }, [value, height, barWidth]); + + return ; +} diff --git a/web/src/components/BusyIndicators.tsx b/web/src/components/BusyIndicators.tsx new file mode 100644 index 0000000..418d0f9 --- /dev/null +++ b/web/src/components/BusyIndicators.tsx @@ -0,0 +1,45 @@ +import { useEffect, useState } from 'react'; +import { Backdrop, Box, CircularProgress, LinearProgress, Paper, Typography } from '@mui/material'; +import { useActivity } from '@/api/activity'; +import { useUi } from '@/i18n/useUi'; + +/** True only after `active` has been continuously true for `delay` ms (so quick calls never flash). */ +export function useDelayed(active: boolean, delay: number): boolean { + const [on, setOn] = useState(false); + useEffect(() => { + if (!active) { setOn(false); return; } + const id = window.setTimeout(() => setOn(true), delay); + return () => window.clearTimeout(id); + }, [active, delay]); + return on; +} + +/** Slim global progress bar for any fetch, shown after a 250 ms delay. */ +export function GlobalProgress() { + const { reads, writes } = useActivity(); + const show = useDelayed(reads + writes > 0, 250); + if (!show) return null; + return ( + t.zIndex.tooltip + 20 }} + /> + ); +} + +/** Blocking "Saving..." card for writes; also prevents double submits. */ +export function SavingOverlay() { + const { writes } = useActivity(); + const { t } = useUi(); + return ( + 0} sx={{ zIndex: (th) => th.zIndex.modal + 20, color: 'text.primary', backgroundColor: 'rgba(0,0,0,0.35)' }}> + + + + {t('busy.saving')} + {t('busy.savingHint')} + + + + ); +} diff --git a/web/src/components/ConfirmDialog.tsx b/web/src/components/ConfirmDialog.tsx new file mode 100644 index 0000000..665a066 --- /dev/null +++ b/web/src/components/ConfirmDialog.tsx @@ -0,0 +1,30 @@ +import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle } from '@mui/material'; + +export interface ConfirmDialogProps { + open: boolean; + title: string; + message: string; + confirmText: string; + cancelText: string; + danger?: boolean; + onConfirm: () => void; + onCancel: () => void; +} + +/** Presentational dialog. Use the `useConfirm()` hook (providers/ConfirmProvider) from pages. */ +export function ConfirmDialog(p: ConfirmDialogProps) { + return ( + + {p.title} + + {p.message} + + + + + + + ); +} diff --git a/web/src/components/DataGrid/DataGrid.tsx b/web/src/components/DataGrid/DataGrid.tsx new file mode 100644 index 0000000..57429e2 --- /dev/null +++ b/web/src/components/DataGrid/DataGrid.tsx @@ -0,0 +1,371 @@ +import { useEffect, useMemo, useState, type ReactNode } from 'react'; +import { keepPreviousData, useQuery } from '@tanstack/react-query'; +import { useLocation, useSearchParams } from 'react-router-dom'; +import { + alpha, Alert, Badge, Box, Button, Chip, IconButton, ListItemIcon, ListItemText, Menu, MenuItem, Paper, Stack, + Table, TableBody, TableCell, TableContainer, TableHead, TablePagination, TableRow, Tooltip, Typography, useTheme, +} from '@mui/material'; +import FilterListIcon from '@mui/icons-material/FilterList'; +import MoreVertIcon from '@mui/icons-material/MoreVert'; +import EditOutlined from '@mui/icons-material/EditOutlined'; +import VisibilityOutlined from '@mui/icons-material/VisibilityOutlined'; +import { api, ApiError, type PagedResult } from '@/api/client'; +import { EmptyState } from '@/components/EmptyState'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { StatusChip } from '@/components/StatusChip'; +import { formatDate, formatDateTime, formatNumber, getPath } from '@/components/meta/format'; +import type { ColumnMeta, FilterMeta, GridMeta, RowAction } from '@/components/meta/types'; +import { useOptions } from '@/components/meta/useOptions'; +import { useUi } from '@/i18n/useUi'; +import { useLanguage } from '@/providers/LanguageProvider'; +import { tokens } from '@/theme/tokens'; +import { rememberGridUrl } from './gridReturn'; +import { FilterDrawer } from './FilterDrawer'; + +/** Invalidate a grid after a write: `qc.invalidateQueries({ queryKey: gridKey('grains.permits') })`. */ +export const gridKey = (key: string) => ['grid', key] as const; + +const RESERVED = new Set(['page', 'size', 'f']); + +export interface DataGridProps { + meta: GridMeta; +} + +export function DataGrid({ meta }: DataGridProps) { + const { t, tr, lang, dir } = useUi(); + const { langReady } = useLanguage(); + const [sp, setSp] = useSearchParams(); + const location = useLocation(); + // so a record page can bring the user back to this list with the same filters + useEffect(() => { rememberGridUrl(location.pathname, location.search); }, [location.pathname, location.search]); + const [drawer, setDrawer] = useState(false); + const [menu, setMenu] = useState<{ anchor: HTMLElement; row: T } | null>(null); + + // every grid shows 10 rows by default (mams convention), whatever the feature meta asks for + const defaultSize = 10; + const filterDefs = meta.filters ?? []; + const statusParam = meta.status?.param; + const names = useMemo(() => [...filterDefs.map((f) => f.name), ...(statusParam ? [statusParam] : [])], [filterDefs, statusParam]); + const hasDefaults = !!meta.defaultFilters && Object.keys(meta.defaultFilters).length > 0; + + // Defaults are used for the FIRST request directly; the URL is then rewritten (replace) with the same values and + // the `f=1` marker. The query key depends only on the effective filters, so the rewrite never causes a 2nd request, + // and picking "All" later is not reverted to the default (marker present). + const initialized = !hasDefaults || sp.has('f'); + + const active = useMemo(() => { + const out: Record = {}; + if (!initialized) return { ...(meta.defaultFilters ?? {}) }; + for (const n of names) { + const v = sp.get(n); + if (v) out[n] = v; + } + return out; + }, [initialized, names, sp, meta.defaultFilters]); + + const page = initialized ? Math.max(1, Number(sp.get('page')) || 1) : 1; + const pageSize = initialized ? Number(sp.get('size')) || defaultSize : defaultSize; + + function write(filters: Record, nextPage: number, nextSize: number) { + const p = new URLSearchParams(); + if (hasDefaults) p.set('f', '1'); + for (const [k, v] of Object.entries(filters)) if (v && !RESERVED.has(k)) p.set(k, v); + if (nextPage > 1) p.set('page', String(nextPage)); + if (nextSize !== defaultSize) p.set('size', String(nextSize)); + setSp(p, { replace: false }); + } + + useEffect(() => { + if (!initialized) { + const p = new URLSearchParams(); + p.set('f', '1'); + for (const [k, v] of Object.entries(meta.defaultFilters ?? {})) p.set(k, v); + setSp(p, { replace: true }); + } + }, [initialized, meta.defaultFilters, setSp]); + + const activeCount = Object.keys(active).length; + const drawerCount = Object.keys(active).filter((k) => k !== statusParam).length; + const canLoad = langReady && initialized && (!meta.requireFilter || activeCount > 0); + // the list needs a filter first: keep the table visible, empty (headers only), under the info message + const blankGrid = langReady && initialized && !!meta.requireFilter && activeCount === 0; + + const q = useQuery, ApiError>({ + queryKey: [...gridKey(meta.key), lang, active, page, pageSize], + queryFn: () => + meta.fetcher + ? meta.fetcher({ page, pageSize, filters: active }) + : api.get>(meta.endpoint!, { page, pageSize, ...active }), + enabled: canLoad, + placeholderData: keepPreviousData, + }); + + const items = q.data?.items ?? []; + const total = q.data?.totalCount ?? 0; + const firstLoad = canLoad && q.isPending; + const updating = q.isFetching && !q.isPending; + + const visibleActions = (row: T) => (meta.rowActions ?? []).filter((a) => !a.hidden?.(row)); + // view / edit are shown as icons in the row; every other action stays in the "more" menu + const INLINE = new Set(['view', 'open', 'edit']); + const inlineActions = (row: T): RowAction[] => { + const own = visibleActions(row).filter((a) => INLINE.has(a.key)); + if (meta.onRowClick && !own.some((a) => a.key === 'view' || a.key === 'open')) { + return [{ key: 'view', label: { en: 'View', ar: 'عرض' }, onClick: meta.onRowClick }, ...own]; + } + return own; + }; + const menuActions = (row: T) => visibleActions(row).filter((a) => !INLINE.has(a.key)); + const actionsCell = (row: T) => ( + e.stopPropagation()} sx={{ width: ACTIONS_W, minWidth: ACTIONS_W, whiteSpace: 'nowrap', py: 0 }}> + + {inlineActions(row).map((a) => ( + + a.onClick(row)}> + {a.icon ?? (a.key === 'edit' ? : )} + + + ))} + {/* the menu slot is always reserved so the icons line up in every row */} + setMenu({ anchor: e.currentTarget, row })} + sx={{ visibility: menuActions(row).length > 0 ? 'visible' : 'hidden' }}> + + + + + ); + + const hasActions = (meta.rowActions?.length ?? 0) > 0 || !!meta.onRowClick; + // visualLtr: the table reads left-to-right as listed (actions on the left). In an RTL page that means reversed DOM order. + const rtl = useTheme().direction === 'rtl'; + const columns = meta.visualLtr && rtl ? [...meta.columns].reverse() : meta.columns; + const actionsBefore = !!meta.visualLtr && !rtl; + + return ( + + {/* filter card: status chips + filter button, then the applied filters with "clear all" (same look on every list) */} + {(meta.status || filterDefs.length > 0) && ( + + + + {meta.status ? ( + + {/* a list that needs a filter has no "All" chip: it would look selected next to the "choose a filter" message */} + {meta.status.showAll !== false && !meta.requireFilter && ( + write(omit(active, meta.status!.param), 1, pageSize)} + /> + )} + {meta.status.options.map((s) => { + const on = active[meta.status!.param] === String(s.value); + return ( + write(on ? omit(active, meta.status!.param) : { ...active, [meta.status!.param]: String(s.value) }, 1, pageSize)} + /> + ); + })} + + ) : } + {filterDefs.length > 0 && ( + ({ '& .MuiBadge-badge': { bgcolor: tokens[th.palette.mode].accent, color: '#fff' } })} + > + + + )} + + + {activeCount > 0 && ( + + + {filterDefs.filter((f) => active[f.name]).map((f) => ( + write(omit(active, f.name), 1, pageSize)} /> + ))} + + + + )} + + + )} + + {meta.requireFilter && activeCount === 0 && {t('grid.requireFilter')}} + {q.isError && ( + q.refetch()}>{t('common.retry')}}> + {t('grid.error')}{q.error.message ? `: ${q.error.message}` : ''} + + )} + {firstLoad && } + {updating && } + + {(blankGrid || (canLoad && !firstLoad && !q.isError)) && ( + + {items.length === 0 && !blankGrid && !meta.emptyAsGrid ? ( + 0 ? t('grid.emptyHint') : t('grid.emptyNoFilters')} + actionLabel={activeCount > 0 ? t('common.clearFilters') : undefined} + onAction={() => write({}, 1, pageSize)} + /> + ) : ( + <> + +
+ + + {hasActions && actionsBefore && } + {columns.map((c) => ( + {tr(c.header)} + ))} + {hasActions && !actionsBefore && } + + + + {items.length === 0 && !blankGrid && ( + + + {t('grid.empty')} + {activeCount > 0 ? t('grid.emptyHint') : t('grid.emptyNoFilters')} + + + )} + {items.map((row) => ( + meta.onRowClick!(row) : undefined} + sx={{ cursor: meta.onRowClick ? 'pointer' : 'default', '&:nth-of-type(even)': { bgcolor: (t) => alpha(t.palette.primary.main, t.palette.mode === 'dark' ? 0.09 : 0.05) } }} + > + {hasActions && actionsBefore && actionsCell(row)} + {columns.map((c) => ( + + + + ))} + {hasActions && !actionsBefore && actionsCell(row)} + + ))} + +
+ + write(active, p + 1, pageSize)} + onRowsPerPageChange={(e) => write(active, 1, Number(e.target.value))} + labelRowsPerPage={t('grid.rowsPerPage')} + labelDisplayedRows={({ from, to, count }) => t('grid.displayedRows', { from, to, count })} + // footer sits at the physical left in both directions; MUI already mirrors the arrow icons in RTL + sx={{ borderTop: 1, borderColor: 'divider', '.MuiTablePagination-spacer': { display: 'none' }, '.MuiTablePagination-toolbar': { flexWrap: 'wrap', justifyContent: dir === 'rtl' ? 'flex-end' : 'flex-start' } }} + /> + + )} + + )} + + setDrawer(false)} + filters={filterDefs} + applied={omit(active, statusParam)} + onApply={(v) => { + setDrawer(false); + write({ ...(statusParam && active[statusParam] ? { [statusParam]: active[statusParam] } : {}), ...v }, 1, pageSize); + }} + onClear={() => { + setDrawer(false); + write(statusParam && active[statusParam] ? { [statusParam]: active[statusParam] } : {}, 1, pageSize); + }} + /> + + setMenu(null)}> + {menu && menuActions(menu.row).map((a: RowAction) => ( + { const r = menu.row; setMenu(null); a.onClick(r); }} sx={a.danger ? { color: 'error.main' } : undefined}> + {a.icon && {a.icon}} + {tr(a.label)} + + ))} + + + ); +} + +function omit(o: Record, key?: string): Record { + const { ...rest } = o; + if (key) delete rest[key]; + return rest; +} + +// fixed width: up to two icon buttons (view/edit) plus the menu slot +const ACTIONS_W = 112; +const BP = { sm: 'sm', md: 'md', lg: 'lg' } as const; +function cellSx(c: ColumnMeta) { + return { + width: c.width, + whiteSpace: 'nowrap' as const, + ...(c.align ? { textAlign: c.align } : {}), + ...(c.hideBelow ? { display: { xs: 'none', [BP[c.hideBelow]]: 'table-cell' } } : {}), + }; +} +function Cell({ col, row }: { col: ColumnMeta; row: T }): ReactNode { + const { lang } = useUi(); + if (col.render) return <>{col.render(row, { lang })}; + const raw = getPath(row, col.field ?? col.key); + let content: ReactNode; + switch (col.format) { + case 'date': content = formatDate(raw, lang); break; + case 'datetime': content = formatDateTime(raw, lang); break; + case 'number': content = formatNumber(raw, lang); break; + case 'boolean': return ; + case 'status': return ; + default: content = raw === null || raw === undefined ? '' : String(raw); + } + const ltr = col.ltr || col.format === 'number' || col.format === 'date' || col.format === 'datetime'; + return ltr ? {content} : <>{content}; +} + +function YesNo({ v }: { v: unknown }) { + const { t } = useUi(); + return <>{v === true || v === 'true' || v === 1 || v === 'Y' ? t('common.yes') : t('common.no')}; +} + +function ActiveChip({ filter, value, parent, onDelete }: { filter: FilterMeta; value: string; parent?: unknown; onDelete: () => void }) { + const { tr, t, lang } = useUi(); + const { options } = useOptions(filter.options, parent, !!filter.dependsOn); + let shown = value; + if (filter.type === 'select' || filter.type === 'autocomplete') { + const o = options.find((x) => String(x.value) === value); + if (o) shown = tr(o.label); + } else if (filter.type === 'checkbox') shown = t('common.yes'); + else if (filter.type === 'date') shown = formatDate(value, lang); + const ltr = !!filter.ltr || !!filter.inputKind; + return ( + + {tr(filter.label)}: {ltr ? {shown} : shown} + + } + /> + ); +} diff --git a/web/src/components/DataGrid/FilterDrawer.tsx b/web/src/components/DataGrid/FilterDrawer.tsx new file mode 100644 index 0000000..29a44f2 --- /dev/null +++ b/web/src/components/DataGrid/FilterDrawer.tsx @@ -0,0 +1,73 @@ +import { useEffect, useState, type FormEvent } from 'react'; +import { Box, Button, Divider, Drawer, IconButton, Stack, Typography } from '@mui/material'; +import CloseIcon from '@mui/icons-material/Close'; +import type { FilterMeta } from '@/components/meta/types'; +import { FieldControl } from '@/components/MetaForm/FieldControl'; +import { useUi } from '@/i18n/useUi'; + +export interface FilterDrawerProps { + open: boolean; + onClose: () => void; + filters: FilterMeta[]; + /** Currently applied values (string map, as in the URL). */ + applied: Record; + onApply: (values: Record) => void; + onClear: () => void; +} + +/** Filter fields built from filter metadata. A real
: Enter in any field runs the search (Apply = submit). */ +export function FilterDrawer({ open, onClose, filters, applied, onApply, onClear }: FilterDrawerProps) { + const { t } = useUi(); + const [draft, setDraft] = useState>(applied); + + useEffect(() => { + if (open) setDraft(applied); + // reset the draft each time the drawer opens + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open]); + + function set(name: string, v: unknown) { + setDraft((d) => { + const next = { ...d, [name]: v === true ? 'true' : v === false || v === null || v === undefined ? '' : String(v) }; + for (const f of filters) if (f.dependsOn === name) next[f.name] = ''; + return next; + }); + } + + function submit(e: FormEvent) { + e.preventDefault(); + const out: Record = {}; + for (const [k, v] of Object.entries(draft)) if (v.trim() !== '') out[k] = v.trim(); + (document.activeElement as HTMLElement | null)?.blur(); + onApply(out); + } + + return ( + + + + {t('grid.filterTitle')} + + + + + {filters.map((f) => ( + set(f.name, v)} + /> + ))} + + + + + + + + + ); +} diff --git a/web/src/components/DataGrid/gridReturn.ts b/web/src/components/DataGrid/gridReturn.ts new file mode 100644 index 0000000..ccedab7 --- /dev/null +++ b/web/src/components/DataGrid/gridReturn.ts @@ -0,0 +1,15 @@ +/** + * A grid keeps its filters / status / page in the URL. When the user opens a record and comes back through the record's + * own back / cancel button, that button would land on the bare list. The grid therefore remembers its last URL per list path + * (sessionStorage) and the record pages go back to it. + */ +const KEY = 'ntp.grid:'; + +export function rememberGridUrl(pathname: string, search: string): void { + try { sessionStorage.setItem(KEY + pathname, pathname + search); } catch { /* storage may be blocked */ } +} + +/** The list URL with the filters it had when the user left it, or `listPath` itself. */ +export function gridReturnUrl(listPath: string): string { + try { return sessionStorage.getItem(KEY + listPath) || listPath; } catch { return listPath; } +} diff --git a/web/src/components/DataGrid/index.ts b/web/src/components/DataGrid/index.ts new file mode 100644 index 0000000..545b40c --- /dev/null +++ b/web/src/components/DataGrid/index.ts @@ -0,0 +1,3 @@ +export { DataGrid, gridKey } from './DataGrid'; +export type { DataGridProps } from './DataGrid'; +export { gridReturnUrl, rememberGridUrl } from './gridReturn'; diff --git a/web/src/components/EmptyState.tsx b/web/src/components/EmptyState.tsx new file mode 100644 index 0000000..1b10dd8 --- /dev/null +++ b/web/src/components/EmptyState.tsx @@ -0,0 +1,25 @@ +import type { ReactNode } from 'react'; +import { Box, Button, Typography } from '@mui/material'; +import InboxOutlinedIcon from '@mui/icons-material/InboxOutlined'; + +export interface EmptyStateProps { + title: string; + hint?: string; + icon?: ReactNode; + /** e.g. "Clear filters" */ + actionLabel?: string; + onAction?: () => void; +} + +export function EmptyState({ title, hint, icon, actionLabel, onAction }: EmptyStateProps) { + return ( + + {icon ?? } + {title} + {hint && {hint}} + {actionLabel && onAction && ( + + )} + + ); +} diff --git a/web/src/components/FileUpload.tsx b/web/src/components/FileUpload.tsx new file mode 100644 index 0000000..0fac1a2 --- /dev/null +++ b/web/src/components/FileUpload.tsx @@ -0,0 +1,85 @@ +import { useRef, useState } from 'react'; +import { Box, Button, FormHelperText, IconButton, Typography } from '@mui/material'; +import AttachFileIcon from '@mui/icons-material/AttachFile'; +import CloseIcon from '@mui/icons-material/Close'; +import { api, ApiError } from '@/api/client'; +import { useUi } from '@/i18n/useUi'; +import { useToast } from '@/providers/ToastProvider'; + +export const DEFAULT_UPLOAD_ENDPOINT = '/files/temp'; + +export interface FileUploadProps { + /** Temp id previously returned by the upload endpoint (the form carries only this id). */ + value?: string; + onChange: (tempId: string) => void; + /** Configurable upload endpoint (relative to /api/v1). Expected response: { id } (also accepts tempId/fileId). */ + endpoint?: string; + accept?: string; + disabled?: boolean; + error?: string; + id?: string; + label?: string; +} + +/** + * STUB: uploads immediately and reports the temp id. Real attachment semantics (types, size, preview, download) + * are added per slice when the legacy upload behaviour is known. + */ +export function FileUpload({ value, onChange, endpoint, accept, disabled, error, id, label }: FileUploadProps) { + const { t } = useUi(); + const toast = useToast(); + const input = useRef(null); + const [busy, setBusy] = useState(false); + const [name, setName] = useState(''); + + async function pick(file: File | undefined) { + if (!file) return; + setBusy(true); + try { + const form = new FormData(); + form.append('file', file); + const r = await api.upload<{ id?: string; tempId?: string; fileId?: string }>(endpoint ?? DEFAULT_UPLOAD_ENDPOINT, form, { silent: true }); + const tmp = r?.id ?? r?.tempId ?? r?.fileId; + if (!tmp) throw new ApiError(0, t('common.uploadFailed')); + setName(file.name); + onChange(String(tmp)); + } catch (e) { + toast.error(e instanceof ApiError ? e.message : t('common.uploadFailed')); + } finally { + setBusy(false); + if (input.current) input.current.value = ''; + } + } + + return ( + + + pick(e.target.files?.[0])} /> + + + {value ? name || t('common.uploaded') : ''} + + {value && !disabled && ( + { setName(''); onChange(''); }}> + + + )} + + {error && {error}} + + ); +} diff --git a/web/src/components/LoadingBanner.tsx b/web/src/components/LoadingBanner.tsx new file mode 100644 index 0000000..598d0ae --- /dev/null +++ b/web/src/components/LoadingBanner.tsx @@ -0,0 +1,40 @@ +import { useEffect, useState } from 'react'; +import { Box, CircularProgress, Typography } from '@mui/material'; +import { useUi } from '@/i18n/useUi'; + +export interface LoadingBannerProps { + /** 'first' = initial load, 'update' = filter/page change. */ + variant?: 'first' | 'update'; + /** Override the main line. */ + text?: string; + /** ms before the reassuring second line appears (default 5000). */ + slowAfter?: number; +} + +/** Words, not just a spinner. role=status + aria-live; after ~5 s a second line explains the wait. */ +export function LoadingBanner({ variant = 'first', text, slowAfter = 5000 }: LoadingBannerProps) { + const { t } = useUi(); + const [slow, setSlow] = useState(false); + useEffect(() => { + const id = window.setTimeout(() => setSlow(true), slowAfter); + return () => window.clearTimeout(id); + }, [slowAfter]); + return ( + + + + + {text ?? t(variant === 'first' ? 'grid.loadingFirst' : 'grid.loadingUpdate')} + + {slow && {t('grid.loadingSlow')}} + + + ); +} diff --git a/web/src/components/Logo.tsx b/web/src/components/Logo.tsx new file mode 100644 index 0000000..579c82d --- /dev/null +++ b/web/src/components/Logo.tsx @@ -0,0 +1,30 @@ +import { Box } from '@mui/material'; +import { useLanguage } from '@/providers/LanguageProvider'; +import { useThemeMode } from '@/providers/ThemeProvider'; + +/** + * Logo matrix: {light,dark} x {ar,en}. Assets copied from the legacy site (images/nafithlogo.gif = Arabic wordmark, + * images/nafith-logo.jpg = English wordmark). Both are opaque raster images with a WHITE background (no alpha), so on + * dark surfaces they sit on a white rounded plate instead of being recoloured. Replace with transparent SVG/PNG + * variants (white-text version for dark) when brand assets are available - only this file changes. + */ +const SRC = { ar: '/brand/nafith-ar.gif', en: '/brand/nafith-en.jpg' } as const; +const SIZE = { ar: { w: 375, h: 81 }, en: { w: 176, h: 43 } } as const; + +export function Logo({ height = 36, on }: { height?: number; on?: 'dark' | 'light' }) { + const { lang } = useLanguage(); + const { mode } = useThemeMode(); + const surface = on ?? mode; + const { w, h } = SIZE[lang]; + const width = Math.round((height * w) / h); + return ( + + Nafith + + ); +} diff --git a/web/src/components/MetaForm/FieldControl.tsx b/web/src/components/MetaForm/FieldControl.tsx new file mode 100644 index 0000000..8aca9c2 --- /dev/null +++ b/web/src/components/MetaForm/FieldControl.tsx @@ -0,0 +1,169 @@ +import { Autocomplete, Checkbox, FormControl, FormControlLabel, FormHelperText, MenuItem, TextField } from '@mui/material'; +import { FileUpload } from '@/components/FileUpload'; +import { useOptions } from '@/components/meta/useOptions'; +import type { FieldMeta, FilterMeta, FormValues, OptionItem } from '@/components/meta/types'; +import { useUi } from '@/i18n/useUi'; + +export interface FieldControlProps { + field: FieldMeta | FilterMeta; + value: unknown; + onChange: (value: unknown) => void; + /** Whole form/filter state: needed for dependsOn. */ + values?: FormValues; + error?: string; + disabled?: boolean; + required?: boolean; + /** Hide the helper text (filter drawer). */ + idPrefix?: string; +} + +const INPUT_MODE: Record = { phone: 'tel', email: 'email', plate: 'text', code: 'text' }; + +/** One control for every field type. Every control is fullWidth so widths are identical inside a grid cell. */ +export function FieldControl({ field, value, onChange, values, error, disabled, required, idPrefix = 'field' }: FieldControlProps) { + const { tr, t, dir } = useUi(); + const parentName = field.dependsOn; + const parent = parentName ? values?.[parentName] : undefined; + const { options, loading } = useOptions(field.options, parent, !!parentName); + const id = `${idPrefix}-${field.name}`; + const label = tr(field.label); + const ltr = !!field.ltr || !!field.inputKind; + const full = field as FieldMeta; + const helper = error || (full.helper ? tr(full.helper) : undefined); + const optLabel = (o: OptionItem) => tr(o.label); + const align = ltr ? { textAlign: dir === 'rtl' ? ('end' as const) : ('start' as const) } : undefined; + const htmlInput = { + ...(ltr ? { dir: 'ltr' as const } : {}), + ...(full.maxLength ? { maxLength: full.maxLength } : {}), + ...(field.inputKind ? { inputMode: INPUT_MODE[field.inputKind] } : {}), + style: align, + }; + const common = { id, label, required, disabled, error: !!error, helperText: helper, fullWidth: true, size: 'small' as const }; + + switch (field.type) { + case 'checkbox': + return ( + + onChange(e.target.checked)} + /> + } + label={required ? `${label} *` : label} + /> + {helper && {helper}} + + ); + + case 'select': + return ( + { + const o = options.find((x) => String(x.value) === e.target.value); + onChange(o ? o.value : ''); + }} + slotProps={{ select: { displayEmpty: false, MenuProps: { slotProps: { paper: { sx: { maxHeight: 320 } } } } } }} + > + + {loading ? '...' : t('common.select')} + + {options.map((o) => ( + + {optLabel(o)} + + ))} + + ); + + case 'autocomplete': { + const selected = options.find((o) => String(o.value) === String(value ?? '')) ?? null; + return ( + + fullWidth + size="small" + disabled={disabled} + loading={loading} + options={options} + value={selected} + getOptionLabel={optLabel} + isOptionEqualToValue={(a, b) => String(a.value) === String(b.value)} + getOptionKey={(o) => String(o.value)} + noOptionsText={t('common.noOptions')} + onChange={(_, o) => onChange(o ? o.value : '')} + renderInput={(params) => ( + + )} + /> + ); + } + + case 'textarea': + return ( + onChange(e.target.value)} + slotProps={{ htmlInput }} + /> + ); + + case 'date': + return ( + onChange(e.target.value)} + slotProps={{ inputLabel: { shrink: true }, htmlInput: { dir: 'ltr', lang: dir === 'rtl' ? 'ar' : 'en', style: align ?? { textAlign: dir === 'rtl' ? 'end' : 'start' } } }} + /> + ); + + case 'number': + return ( + onChange(e.target.value)} + slotProps={{ htmlInput: { ...htmlInput, dir: 'ltr', min: full.min, max: full.max, style: { textAlign: dir === 'rtl' ? 'end' : 'start' } } }} + /> + ); + + case 'attachment': + return ( + + {required ? `${label} *` : label} + + + ); + + default: + return ( + onChange(e.target.value)} + slotProps={{ htmlInput }} + /> + ); + } +} diff --git a/web/src/components/MetaForm/MetaForm.tsx b/web/src/components/MetaForm/MetaForm.tsx new file mode 100644 index 0000000..934a221 --- /dev/null +++ b/web/src/components/MetaForm/MetaForm.tsx @@ -0,0 +1,274 @@ +import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'; +import { Box, Button, Stack, Tab, Tabs, Typography } from '@mui/material'; +import { SectionPaper } from '@/components/SectionPaper'; +import { ViewItem } from '@/components/ViewItem'; +import { formatDate, formatNumber } from '@/components/meta/format'; +import { useOptions } from '@/components/meta/useOptions'; +import type { FieldMeta, FormMeta, FormMode, FormValues, SectionMeta } from '@/components/meta/types'; +import { useUi } from '@/i18n/useUi'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { FieldControl } from './FieldControl'; +import { sectionIcon } from './sectionIcons'; +import { allFields, buildPayload, initialValues, isDisabled, isEmpty, isHidden, isRequired } from './rules'; + +export interface MetaFormProps { + meta: FormMeta; + mode: FormMode; + initialValues?: FormValues; + /** Receives the payload built from VISIBLE fields only. Throw/reject to keep the form open. */ + onSubmit?: (payload: FormValues) => Promise | unknown; + onCancel?: () => void; + submitLabel?: string; + /** Confirmation question before saving; `false` skips the dialog. Default: the standard "Do you want to save?". */ + confirmMessage?: string | false; + /** Field-level errors from the backend (ApiError.fieldErrors); the first one is focused. */ + serverErrors?: Record; + /** Extra buttons next to Save/Cancel. */ + extraActions?: ReactNode; + /** Extra sections drawn after the form sections and before the buttons (e.g. a documents section). */ + children?: ReactNode; +} + +const COLS = { 1: '1fr', 2: 'repeat(2, minmax(0, 1fr))', 3: 'repeat(3, minmax(0, 1fr))' } as const; + +function cellSpan(f: FieldMeta, cols: 1 | 2 | 3) { + const span = f.span ?? 1; + if (span === 'full') return { gridColumn: { xs: 'auto', sm: '1 / -1' } }; + return { + gridColumn: { + xs: 'auto', + sm: span >= 2 && cols >= 2 ? 'span 2' : 'auto', + lg: `span ${Math.min(span, cols)}`, + }, + }; +} + +export function MetaForm(props: MetaFormProps) { + const { meta, mode, onSubmit, onCancel } = props; + const { t, tr } = useUi(); + const confirm = useConfirm(); + const toast = useToast(); + const [values, setValues] = useState(() => initialValues(meta, props.initialValues)); + const [errors, setErrors] = useState>({}); + const [submitting, setSubmitting] = useState(false); + const fields = useMemo(() => allFields(meta), [meta]); + const formRef = useRef(null); + + // load/refresh values when the caller delivers record data (edit/view) + const given = props.initialValues; + const givenKey = JSON.stringify(given ?? null); // value-compare so an inline object does not reset the form + const firstRun = useRef(true); + useEffect(() => { + if (firstRun.current) { firstRun.current = false; return; } + setValues(initialValues(meta, given)); + setErrors({}); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [meta, givenKey]); + + const focusField = useCallback((name: string) => { + window.setTimeout(() => { + const el = formRef.current?.querySelector(`#field-${CSS.escape(name)}`); + el?.scrollIntoView({ block: 'center', behavior: 'smooth' }); + el?.focus({ preventScroll: true }); + }, 30); + }, []); + + useEffect(() => { + const keys = Object.keys(props.serverErrors ?? {}); + if (!keys.length) return; + setErrors((e) => ({ ...e, ...props.serverErrors })); + const first = fields.find((f) => keys.includes(f.name)); + if (first) focusField(first.name); + }, [props.serverErrors, fields, focusField]); + + const setValue = useCallback( + (name: string, v: unknown) => { + setValues((cur) => { + const next = { ...cur, [name]: v }; + for (const f of fields) if (f.dependsOn === name) next[f.name] = ''; + return next; + }); + setErrors((e) => (e[name] ? { ...e, [name]: '' } : e)); + }, + [fields], + ); + + function validate(): Record { + const out: Record = {}; + for (const f of fields) { + // hidden, read-only and locked fields never block a save + if (isHidden(f, values, mode) || isDisabled(f, values, mode)) continue; + const v = values[f.name]; + if (isRequired(f, values) && (isEmpty(v) || (f.type === 'checkbox' && v !== true))) { + out[f.name] = t('common.required'); + continue; + } + if (isEmpty(v)) continue; + const s = String(v); + if (f.maxLength && s.length > f.maxLength) out[f.name] = t('common.maxLength', { n: f.maxLength }); + else if (f.pattern && !f.pattern.regex.test(s)) out[f.name] = tr(f.pattern.message); + else if (f.type === 'number') { + const n = Number(s); + if (Number.isNaN(n)) out[f.name] = t('common.invalid'); + else if (f.min !== undefined && n < f.min) out[f.name] = t('common.min', { n: f.min }); + else if (f.max !== undefined && n > f.max) out[f.name] = t('common.max', { n: f.max }); + } + } + return out; + } + + async function submit(e: FormEvent) { + e.preventDefault(); + if (submitting || mode === 'view') return; + const errs = validate(); + setErrors(errs); + const bad = fields.find((f) => errs[f.name]); + if (bad) { + toast.warning(t('common.fixErrors')); + focusField(bad.name); + return; + } + if (props.confirmMessage !== false) { + const ok = await confirm({ message: props.confirmMessage ?? t('confirm.save') }); + if (!ok) return; + } + setSubmitting(true); + try { + await onSubmit?.(buildPayload(meta, values, mode)); + } finally { + setSubmitting(false); + } + } + + const [tab, setTab] = useState(0); + const allSections = meta.sections + .map((s) => ({ s, fields: s.fields.filter((f) => !isHidden(f, values, mode)) })) + .filter((x) => x.fields.length > 0); + // view pages: attachments live in their own tab, the other fields in "Details" + const attachSections = mode === 'view' + ? allSections.map((x) => ({ s: x.s, fields: x.fields.filter((f) => f.type === 'attachment') })).filter((x) => x.fields.length > 0) + : []; + const hasTabs = attachSections.length > 0; + const visibleSections = mode !== 'view' ? allSections + : (hasTabs && tab === 1 ? attachSections + : allSections.map((x) => ({ s: x.s, fields: x.fields.filter((f) => f.type !== 'attachment') })).filter((x) => x.fields.length > 0)); + const showTitles = visibleSections.length > 1 || !!visibleSections[0]?.s.title; + + return ( + + {hasTabs && ( + setTab(v)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}> + + n + x.fields.length, 0)})`} /> + + )} + + {visibleSections.map(({ s, fields: vf }) => ( +
+ {vf.map((f) => ( + + {mode === 'view' && f.type !== 'attachment' ? ( + + ) : ( + setValue(f.name, v)} + /> + )} + + ))} +
+ ))} + {props.children} + {mode !== 'view' && ( + + + {onCancel && ( + + )} + {props.extraActions} + + )} +
+
+ ); +} + +/** Look of the mams record pages: blue-tinted frame, title bar on forms, icon-less title with a thin line on view pages. */ +function Section({ section, showTitle, view, children }: { section: SectionMeta; showTitle: boolean; view: boolean; children: ReactNode }) { + const { tr } = useUi(); + const cols = section.columns ?? 3; + const Icon = sectionIcon(`${section.key} ${section.title?.en ?? ''}`); + return ( + + {showTitle && section.title && ( + + + {tr(section.title)} + + )} + + {children} + + + ); +} + +/** Read-only caption + value (view mode), same typography as the mams record page. */ +function ViewField({ field, value, values }: { field: FieldMeta; value: unknown; values: FormValues }) { + const { tr, t, lang } = useUi(); + const parent = field.dependsOn ? values[field.dependsOn] : undefined; + const { options } = useOptions(field.options, parent, !!field.dependsOn); + const empty = value === undefined || value === null || value === ''; + let shown: ReactNode = '—'; + if (field.type === 'checkbox') shown = value === true || value === 'true' ? t('common.yes') : t('common.no'); + else if (!empty) { + let text: string; + if (field.type === 'select' || field.type === 'autocomplete') { + const o = options.find((x) => String(x.value) === String(value)); + text = o ? tr(o.label) : String(value); + } else if (field.type === 'date') text = formatDate(value, lang); + else if (field.type === 'number') text = formatNumber(value, lang); + else text = String(value); + const ltr = !!field.ltr || !!field.inputKind || field.type === 'date' || field.type === 'number'; + shown = ltr ? {text} : text; + } + return ( + + {shown} + + ); +} diff --git a/web/src/components/MetaForm/index.ts b/web/src/components/MetaForm/index.ts new file mode 100644 index 0000000..8a1388f --- /dev/null +++ b/web/src/components/MetaForm/index.ts @@ -0,0 +1,4 @@ +export { MetaForm } from './MetaForm'; +export type { MetaFormProps } from './MetaForm'; +export { FieldControl } from './FieldControl'; +export { isHidden, isDisabled, isRequired, evalRule, buildPayload, initialValues } from './rules'; diff --git a/web/src/components/MetaForm/rules.ts b/web/src/components/MetaForm/rules.ts new file mode 100644 index 0000000..73d90f5 --- /dev/null +++ b/web/src/components/MetaForm/rules.ts @@ -0,0 +1,66 @@ +import type { FieldMeta, FormMeta, FormMode, FormValues, Rule } from '@/components/meta/types'; + +export function isEmpty(v: unknown): boolean { + return v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0); +} + +/** Evaluate a declarative rule against the form values. */ +export function evalRule(rule: Rule | undefined, values: FormValues): boolean { + if (!rule) return false; + if ('all' in rule) return rule.all.every((r) => evalRule(r, values)); + if ('any' in rule) return rule.any.some((r) => evalRule(r, values)); + if ('not' in rule) return !evalRule(rule.not, values); + const v = values[rule.field]; + switch (rule.op ?? 'truthy') { + case 'eq': return String(v ?? '') === String(rule.value ?? ''); + case 'ne': return String(v ?? '') !== String(rule.value ?? ''); + case 'in': return Array.isArray(rule.value) && rule.value.map(String).includes(String(v ?? '')); + case 'nin': return !(Array.isArray(rule.value) && rule.value.map(String).includes(String(v ?? ''))); + case 'empty': return isEmpty(v); + case 'notEmpty': return !isEmpty(v); + case 'falsy': return !v || v === 'false' || v === 'NO'; + default: return !!v && v !== 'false' && v !== 'NO'; + } +} + +/** + * THE single visibility decision. Used by render, validate, payload building and "form blocked" checks. + * Never re-implement this inline. + */ +export function isHidden(field: FieldMeta, values: FormValues, mode: FormMode): boolean { + if (field.hiddenOnCreate && mode === 'create') return true; + return evalRule(field.hiddenWhen, values); +} + +export function isDisabled(field: FieldMeta, values: FormValues, mode: FormMode): boolean { + return mode === 'view' || !!field.readOnly || evalRule(field.disabledWhen, values); +} + +export function isRequired(field: FieldMeta, values: FormValues): boolean { + return !!field.required || evalRule(field.requiredWhen, values); +} + +export function allFields(meta: FormMeta): FieldMeta[] { + return meta.sections.flatMap((s) => s.fields); +} + +export function initialValues(meta: FormMeta, given?: FormValues): FormValues { + const out: FormValues = {}; + for (const f of allFields(meta)) { + out[f.name] = given?.[f.name] ?? f.defaultValue ?? (f.type === 'checkbox' ? false : ''); + } + // keep extra keys (ids...) the caller passed + if (given) for (const [k, v] of Object.entries(given)) if (!(k in out)) out[k] = v; + return out; +} + +/** Payload = visible fields only (hidden and read-only/locked are skipped). Empty strings become null. */ +export function buildPayload(meta: FormMeta, values: FormValues, mode: FormMode): FormValues { + const out: FormValues = {}; + for (const f of allFields(meta)) { + if (isHidden(f, values, mode) || f.readOnly) continue; + const v = values[f.name]; + out[f.name] = v === '' ? null : v; + } + return out; +} diff --git a/web/src/components/MetaForm/sectionIcons.ts b/web/src/components/MetaForm/sectionIcons.ts new file mode 100644 index 0000000..3ab4292 --- /dev/null +++ b/web/src/components/MetaForm/sectionIcons.ts @@ -0,0 +1,42 @@ +import type { ElementType } from 'react'; +import InfoOutlined from '@mui/icons-material/InfoOutlined'; +import LocationOnOutlined from '@mui/icons-material/LocationOnOutlined'; +import PersonOutline from '@mui/icons-material/PersonOutlineOutlined'; +import BadgeOutlined from '@mui/icons-material/BadgeOutlined'; +import AttachFileOutlined from '@mui/icons-material/AttachFileOutlined'; +import VerifiedUserOutlined from '@mui/icons-material/VerifiedUserOutlined'; +import LocalShippingOutlined from '@mui/icons-material/LocalShippingOutlined'; +import DescriptionOutlined from '@mui/icons-material/DescriptionOutlined'; +import PaymentsOutlined from '@mui/icons-material/PaymentsOutlined'; +import ContactPhoneOutlined from '@mui/icons-material/ContactPhoneOutlined'; +import ForumOutlined from '@mui/icons-material/ForumOutlined'; +import ReceiptLongOutlined from '@mui/icons-material/ReceiptLongOutlined'; +import BusinessOutlined from '@mui/icons-material/BusinessOutlined'; +import CardMembershipOutlined from '@mui/icons-material/CardMembershipOutlined'; +import ShieldOutlined from '@mui/icons-material/ShieldOutlined'; +import SpeedOutlined from '@mui/icons-material/SpeedOutlined'; +import EmailOutlined from '@mui/icons-material/EmailOutlined'; +import EventOutlined from '@mui/icons-material/EventOutlined'; + +/** Icon for a section of a view page, chosen from its key and English title (same idea as mams' sectionIcon). */ +const RULES: [RegExp, ElementType][] = [ + [/ATT|DOCUMENT|FILE/, AttachFileOutlined], + [/ADDRESS|LOCATION|ESTATE|DESTINATION/, LocationOnOutlined], + [/REPLY|NOTE|REMARK|COMMENT/, ForumOutlined], + [/INSURANCE/, ShieldOutlined], + [/CAPACITY|WEIGHT|QUOTA/, SpeedOutlined], + [/LICEN[CS]E|CARD|VALIDITY/, CardMembershipOutlined], + [/OWNER|DRIVER|PERSON|EMPLOYEE|STAKEHOLDER|USER/, PersonOutline], + [/TRUCK|TRAILER|VEHICLE|FLEET|BUS\b|CAR\b|EQUIP/, LocalShippingOutlined], + [/FINANC|PAYMENT|INVOICE|BILLING|PRICE|AMOUNT/, PaymentsOutlined], + [/SUMMARY|LINES/, ReceiptLongOutlined], + [/REGISTRATION|COMPANY|ENTITY/, BusinessOutlined], + [/CONTACT|PHONE/, ContactPhoneOutlined], + [/EMAIL|MAIL/, EmailOutlined], + [/DATE|SCHEDULE|EVENT/, EventOutlined], + [/PERMIT|ORDER|REQUEST|DETAILS/, DescriptionOutlined], + [/VERIF|SECURITY|AUTH/, VerifiedUserOutlined], + [/PERSONAL|IDENT/, BadgeOutlined], +]; + +export const sectionIcon = (hint: string): ElementType => RULES.find(([re]) => re.test(hint.toUpperCase()))?.[1] ?? InfoOutlined; diff --git a/web/src/components/PageHeader.tsx b/web/src/components/PageHeader.tsx new file mode 100644 index 0000000..ef9b2c1 --- /dev/null +++ b/web/src/components/PageHeader.tsx @@ -0,0 +1,50 @@ +import type { ReactNode } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { Box, IconButton, Stack, Tooltip, Typography, useTheme } from '@mui/material'; +import ArrowBackIcon from '@mui/icons-material/ArrowBack'; +import ArrowForwardIcon from '@mui/icons-material/ArrowForward'; +import { gridReturnUrl } from '@/components/DataGrid/gridReturn'; +import { useUi } from '@/i18n/useUi'; +import { tokens } from '@/theme/tokens'; + +export interface PageHeaderProps { + title: string; + subtitle?: string; + /** Buttons on the end side (e.g. "New"). */ + actions?: ReactNode; + /** Record status chip: shown right after the title on the START side (right in Arabic), not with the buttons. */ + status?: ReactNode; + /** Shows a round back button at the start of the header that goes to this path (record / view pages). */ + backTo?: string; +} + +export function PageHeader({ title, subtitle, actions, status, backTo }: PageHeaderProps) { + const navigate = useNavigate(); + const { t } = useUi(); + const rtl = useTheme().direction === 'rtl'; + return ( + + + {backTo && ( + + navigate(gridReturnUrl(backTo))} + sx={{ border: 1, borderColor: 'divider', width: 38, height: 38, flexShrink: 0 }} + > + {/* "back" points to the start side: right in Arabic, left in English */} + {rtl ? : } + + + )} + + + ({ fontWeight: 800, color: tokens[th.palette.mode].title })}>{title} + {status} + + {subtitle && {subtitle}} + + + {actions && {actions}} + + ); +} diff --git a/web/src/components/SectionPaper.tsx b/web/src/components/SectionPaper.tsx new file mode 100644 index 0000000..8417c43 --- /dev/null +++ b/web/src/components/SectionPaper.tsx @@ -0,0 +1,17 @@ +import { alpha, Paper, type PaperProps, type SxProps, type Theme } from '@mui/material'; + +/** + * The framed look of a record section (mams style): a clear 1.5px border tinted with the primary colour and rounded corners. + * One definition for every view / form screen so all sections look the same: MetaForm sections, the permit view page, + * the registry cards, ... + */ +export const sectionFrameSx: SxProps = (t) => ({ + border: '1.5px solid', + borderColor: alpha(t.palette.primary.main, t.palette.mode === 'dark' ? 0.5 : 0.35), + borderRadius: 2, +}); + +/** `` with the section frame; extra `sx` is merged after it. */ +export function SectionPaper({ sx, ...rest }: PaperProps) { + return } />; +} diff --git a/web/src/components/StatusChip.tsx b/web/src/components/StatusChip.tsx new file mode 100644 index 0000000..3ace621 --- /dev/null +++ b/web/src/components/StatusChip.tsx @@ -0,0 +1,17 @@ +import { Chip } from '@mui/material'; +import type { StatusMeta } from '@/components/meta/types'; +import { useUi } from '@/i18n/useUi'; + +export interface StatusChipProps { + value: string | number | null | undefined; + statuses: StatusMeta[]; + size?: 'small' | 'medium'; +} + +/** Chip for a status value, label/colour from a StatusMeta table; unknown values render as plain text chip. */ +export function StatusChip({ value, statuses, size = 'small' }: StatusChipProps) { + const { tr } = useUi(); + if (value === null || value === undefined || value === '') return null; + const s = statuses.find((x) => String(x.value) === String(value)); + return ; +} diff --git a/web/src/components/ViewItem.tsx b/web/src/components/ViewItem.tsx new file mode 100644 index 0000000..6fb12f3 --- /dev/null +++ b/web/src/components/ViewItem.tsx @@ -0,0 +1,23 @@ +import type { ReactNode } from 'react'; +import { Box, Typography } from '@mui/material'; + +/** + * Read-only caption + value used on every view screen (record pages): the caption in the primary blue at regular weight, the + * value below it in the brand navy at regular weight, an empty value as a grey dash. One definition so all views match. + */ +export function ViewItem({ label, children, empty, preWrap }: { label: ReactNode; children?: ReactNode; empty?: boolean; preWrap?: boolean }) { + const isEmpty = empty ?? (children === undefined || children === null || children === '' || children === false); + return ( + + + {label} + + + {isEmpty ? '—' : children} + + + ); +} diff --git a/web/src/components/meta/format.ts b/web/src/components/meta/format.ts new file mode 100644 index 0000000..fb3fdc9 --- /dev/null +++ b/web/src/components/meta/format.ts @@ -0,0 +1,33 @@ +import type { Lang } from '@/i18n/ui'; + +/** Display locale with latin digits (plates, numbers and dates must read the same in both languages). */ +const locale = (lang: Lang) => (lang === 'ar' ? 'ar-OM-u-nu-latn' : 'en-GB'); + +const p2 = (n: number) => String(n).padStart(2, '0'); + +/** dd/MM/yyyy with latin digits and no bidi marks (render inside a dir="ltr" element). */ +export function formatDate(iso: unknown, _lang?: Lang): string { + if (!iso) return ''; + const s = String(iso); + const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s); + if (m) return `${m[3]}/${m[2]}/${m[1]}`; + const d = new Date(s); + return Number.isNaN(d.getTime()) ? s : `${p2(d.getDate())}/${p2(d.getMonth() + 1)}/${d.getFullYear()}`; +} + +export function formatDateTime(iso: unknown, _lang?: Lang): string { + if (!iso) return ''; + const d = new Date(String(iso)); + if (Number.isNaN(d.getTime())) return String(iso); + return `${p2(d.getDate())}/${p2(d.getMonth() + 1)}/${d.getFullYear()} ${p2(d.getHours())}:${p2(d.getMinutes())}`; +} + +export function formatNumber(n: unknown, lang: Lang): string { + if (n === null || n === undefined || n === '') return ''; + const v = Number(n); + return Number.isNaN(v) ? String(n) : new Intl.NumberFormat(locale(lang)).format(v); +} + +export function getPath(row: unknown, path: string): unknown { + return path.split('.').reduce((o, k) => (o && typeof o === 'object' ? (o as Record)[k] : undefined), row); +} diff --git a/web/src/components/meta/types.ts b/web/src/components/meta/types.ts new file mode 100644 index 0000000..a08ebcc --- /dev/null +++ b/web/src/components/meta/types.ts @@ -0,0 +1,177 @@ +/** + * Declarative metadata for generic grids and forms. Entity code = small tables of these types only. + * See docs/MIGRATION.md "Front-end foundation notes". + */ +import type { ReactNode } from 'react'; +import type { L10n, Lang } from '@/i18n/ui'; + +export type { L10n, Lang }; +export type { PagedResult } from '@/api/client'; + +// ---------------------------------------------------------------- options +export interface OptionItem { + value: string | number; + /** Plain text, or a bilingual label. Legacy convention: caption when present, else name. */ + label: string | L10n; + disabled?: boolean; +} + +/** Async option loader: cached by React Query under ['options', key, lang, dependsOnValue]. */ +export interface OptionsLoader { + /** Stable cache key, e.g. 'grains.companies'. */ + key: string; + load: (ctx: { lang: Lang; parent?: unknown }) => Promise; + /** ms; default 5 min (lookups are mostly static). */ + staleTime?: number; +} +export type OptionsSource = OptionItem[] | OptionsLoader; + +// ---------------------------------------------------------------- conditional rules +export type FormValues = Record; + +export type Cond = { + field: string; + /** default 'truthy' */ + op?: 'eq' | 'ne' | 'in' | 'nin' | 'empty' | 'notEmpty' | 'truthy' | 'falsy'; + value?: unknown; +}; +/** Declarative boolean expression over the form values. Evaluated by ONE function (rules.ts). */ +export type Rule = Cond | { all: Rule[] } | { any: Rule[] } | { not: Rule }; + +// ---------------------------------------------------------------- fields +export type FieldType = 'text' | 'number' | 'date' | 'select' | 'autocomplete' | 'checkbox' | 'textarea' | 'attachment'; + +/** Inputs that must stay left-to-right inside an RTL page. */ +export type InputKind = 'plate' | 'phone' | 'email' | 'code'; + +export interface FieldMeta { + name: string; + type: FieldType; + label: L10n; + required?: boolean; + /** Always read-only (shown disabled). */ + readOnly?: boolean; + /** Hidden on create (system-generated numbers/dates/status); shown on edit/view. */ + hiddenOnCreate?: boolean; + hiddenWhen?: Rule; + requiredWhen?: Rule; + disabledWhen?: Rule; + defaultValue?: unknown; + + maxLength?: number; + min?: number; + max?: number; + pattern?: { regex: RegExp; message: L10n }; + rows?: number; // textarea + placeholder?: L10n; + helper?: L10n; + + options?: OptionsSource; + /** Field name whose value is passed to the options loader (and cleared when the parent changes). */ + dependsOn?: string; + + inputKind?: InputKind; + /** Force dir="ltr" on the input (implied by inputKind). */ + ltr?: boolean; + + /** Grid span at >= sm (md=2 cols, lg=3 cols). 'full' = whole row. Default 1. */ + span?: 1 | 2 | 3 | 'full'; + + attachment?: { endpoint?: string; accept?: string }; +} + +export interface SectionMeta { + key: string; + /** Omit (or single section + hideTitle) so a title never just repeats the page name. */ + title?: L10n; + /** Max columns at the widest breakpoint (default 3): 1 / 2 / 3 responsive. */ + columns?: 1 | 2 | 3; + fields: FieldMeta[]; +} + +export interface FormMeta { + key: string; + sections: SectionMeta[]; +} + +export type FormMode = 'create' | 'edit' | 'view'; + +// ---------------------------------------------------------------- filters (subset of field metadata) +export type FilterMeta = Pick< + FieldMeta, + 'name' | 'type' | 'label' | 'options' | 'dependsOn' | 'inputKind' | 'ltr' | 'placeholder' +>; + +// ---------------------------------------------------------------- grid +export type StatusColor = 'default' | 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'info'; + +export interface StatusMeta { + value: string | number; + label: L10n; + color: StatusColor; +} + +export type ColumnFormat = 'text' | 'number' | 'date' | 'datetime' | 'boolean' | 'status'; + +export interface ColumnMeta { + key: string; + header: L10n; + /** Property of the row (dot path allowed). Defaults to `key`. */ + field?: string; + format?: ColumnFormat; + /** For format 'status': the status table used for chip label/color. */ + statuses?: StatusMeta[]; + /** Custom cell. Wins over `format`. */ + render?: (row: T, ctx: { lang: Lang }) => ReactNode; + align?: 'start' | 'end' | 'center'; + width?: number | string; + /** Keep LTR (plates, phones, codes). */ + ltr?: boolean; + /** Hide this column below a breakpoint (responsive). */ + hideBelow?: 'sm' | 'md' | 'lg'; +} + +export interface RowAction { + key: string; + label: L10n; + icon?: ReactNode; + onClick: (row: T) => void; + hidden?: (row: T) => boolean; + danger?: boolean; +} + +export interface GridQuery { + page: number; // 1-based + pageSize: number; + /** All active filters, already trimmed (no empty values) - ready for the query string. */ + filters: Record; +} + +export interface GridMeta { + key: string; + /** GET endpoint (relative to /api/v1) returning PagedResult; params: page,pageSize + filters. */ + endpoint?: string; + /** Or a custom fetcher. */ + fetcher?: (q: GridQuery) => Promise>; + rowKey: (row: T) => string | number; + columns: ColumnMeta[]; + filters?: FilterMeta[]; + /** Status chips (+ "All"): the chosen value is sent as query param `param`. */ + status?: { param: string; options: StatusMeta[]; showAll?: boolean }; + /** Seeded BEFORE the first request (no duplicate/unfiltered request). Keys are filter names or status param. */ + defaultFilters?: Record; + /** With no rows, keep the table (headers) and show the "no results" line inside it instead of the empty-state card. */ + emptyAsGrid?: boolean; + /** The server refuses unfiltered loads: show an info alert and do not fire until a filter exists. */ + requireFilter?: boolean; + pageSize?: number; + pageSizeOptions?: number[]; + rowActions?: RowAction[]; + onRowClick?: (row: T) => void; + /** + * Legacy grids (ColdFusion cfgrid) are always laid out left to right, even on Arabic pages: the actions column is on the + * LEFT and the first listed column next to it. With this flag the screen shows the columns left-to-right in the listed + * order in BOTH languages (in Arabic the table is rendered in reverse so it reads like the legacy grid). + */ + visualLtr?: boolean; +} diff --git a/web/src/components/meta/useOptions.ts b/web/src/components/meta/useOptions.ts new file mode 100644 index 0000000..6c1cb2d --- /dev/null +++ b/web/src/components/meta/useOptions.ts @@ -0,0 +1,24 @@ +import { useQuery } from '@tanstack/react-query'; +import { useLanguage } from '@/providers/LanguageProvider'; +import type { OptionItem, OptionsSource } from './types'; + +const NONE: OptionItem[] = []; + +/** + * Resolve an options source: static array as-is, or an async loader through React Query + * (key includes the language, because the backend answers in the session language). + * `parent` is the value of the `dependsOn` field; the loader waits until it is set. + */ +export function useOptions(source: OptionsSource | undefined, parent?: unknown, dependent = false) { + const { lang, langReady } = useLanguage(); + const loader = source && !Array.isArray(source) ? source : undefined; + const q = useQuery({ + queryKey: ['options', loader?.key ?? '', lang, parent ?? null], + queryFn: () => loader!.load({ lang, parent }), + enabled: !!loader && langReady && (!dependent || (parent !== undefined && parent !== '' && parent !== null)), + staleTime: loader?.staleTime ?? 5 * 60_000, + }); + if (!source) return { options: NONE, loading: false }; + if (Array.isArray(source)) return { options: source, loading: false }; + return { options: q.data ?? NONE, loading: q.isFetching }; +} diff --git a/web/src/features/_example/api.ts b/web/src/features/_example/api.ts new file mode 100644 index 0000000..918429b --- /dev/null +++ b/web/src/features/_example/api.ts @@ -0,0 +1,30 @@ +import { useQuery } from '@tanstack/react-query'; +import { api } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; +import type { Vehicle } from './types'; + +/** Per-feature hooks: thin wrappers over the shared client. */ +export const vehicleKey = (id: string | number) => ['example.vehicle', String(id)] as const; + +export function useVehicle(id: string | undefined) { + return useQuery({ + queryKey: vehicleKey(id ?? ''), + queryFn: () => api.get(`/example/vehicles/${id}`), + enabled: !!id, + }); +} + +export function useSaveVehicle(id: string | undefined) { + return useWrite( + (payload: Record) => + id ? api.put<{ message?: string }>(`/example/vehicles/${id}`, payload) : api.post<{ id: number; message?: string }>('/example/vehicles', payload), + { invalidate: [gridKey('example.vehicles'), ['example.vehicle']] }, + ); +} + +export function useDeleteVehicle() { + return useWrite((id: number) => api.delete<{ message?: string }>(`/example/vehicles/${id}`), { + invalidate: [gridKey('example.vehicles')], + }); +} diff --git a/web/src/features/_example/meta.tsx b/web/src/features/_example/meta.tsx new file mode 100644 index 0000000..cfdcf93 --- /dev/null +++ b/web/src/features/_example/meta.tsx @@ -0,0 +1,116 @@ +import { api } from '@/api/client'; +import type { FormMeta, GridMeta, OptionItem, OptionsLoader, StatusMeta } from '@/components/meta/types'; +import type { Vehicle } from './types'; + +/** Declarative tables only: this file is what a slice agent writes per entity. */ + +export const statuses: StatusMeta[] = [ + { value: 'ACTIVE', label: { en: 'Active', ar: 'فعّال' }, color: 'success' }, + { value: 'PENDING', label: { en: 'Pending', ar: 'قيد المراجعة' }, color: 'warning' }, + { value: 'BLOCKED', label: { en: 'Blocked', ar: 'محظور' }, color: 'error' }, +]; + +const nationalities: OptionItem[] = [ + { value: 'OM', label: { en: 'Omani', ar: 'عماني' } }, + { value: 'AE', label: { en: 'Emirati', ar: 'إماراتي' } }, + { value: 'IN', label: { en: 'Indian', ar: 'هندي' } }, + { value: 'PK', label: { en: 'Pakistani', ar: 'باكستاني' } }, +]; + +/** Async option loader (React Query caches it under ['options', key, lang, parent]). */ +export const categoryOptions: OptionsLoader = { + key: 'example.categories', + load: () => api.get('/example/categories', undefined, { silent: true }), +}; + +export const vehicleGrid = (h: { onOpen: (v: Vehicle) => void; onDelete: (v: Vehicle) => void }): GridMeta => ({ + key: 'example.vehicles', + endpoint: '/example/vehicles', + rowKey: (r) => r.id, + status: { param: 'status', options: statuses }, + onRowClick: h.onOpen, + columns: [ + { key: 'plate', header: { en: 'Plate', ar: 'رقم اللوحة' }, render: (r) => {r.plateNumber} {r.plateCode} }, + { key: 'ownerName', header: { en: 'Owner', ar: 'المالك' } }, + { + key: 'nationality', header: { en: 'Nationality', ar: 'الجنسية' }, hideBelow: 'md', + render: (r, { lang }) => { const n = nationalities.find((x) => x.value === r.nationality); return n ? (n.label as { en: string; ar: string })[lang] : r.nationality; }, + }, + { key: 'category', header: { en: 'Category', ar: 'الفئة' }, hideBelow: 'sm' }, + { key: 'phone', header: { en: 'Phone', ar: 'الهاتف' }, ltr: true, hideBelow: 'lg' }, + { key: 'expiryDate', header: { en: 'Expiry', ar: 'تاريخ الانتهاء' }, format: 'date', hideBelow: 'md' }, + { key: 'status', header: { en: 'Status', ar: 'الحالة' }, format: 'status', statuses }, + ], + filters: [ + { name: 'plateNumber', type: 'text', label: { en: 'Plate number', ar: 'رقم اللوحة' }, inputKind: 'plate' }, + { name: 'ownerName', type: 'text', label: { en: 'Owner', ar: 'المالك' } }, + { name: 'nationality', type: 'select', label: { en: 'Nationality', ar: 'الجنسية' }, options: nationalities }, + { name: 'category', type: 'autocomplete', label: { en: 'Category', ar: 'الفئة' }, options: categoryOptions }, + { name: 'expiryFrom', type: 'date', label: { en: 'Expires from', ar: 'ينتهي من' } }, + ], + rowActions: [ + { key: 'open', label: { en: 'Open', ar: 'فتح' }, onClick: h.onOpen }, + { key: 'delete', label: { en: 'Delete', ar: 'حذف' }, danger: true, hidden: (r) => r.status === 'BLOCKED', onClick: h.onDelete }, + ], +}); + +export const vehicleForm: FormMeta = { + key: 'example.vehicle', + sections: [ + { + key: 'vehicle', + title: { en: 'Vehicle', ar: 'المركبة' }, + fields: [ + { name: 'plateNumber', type: 'text', label: { en: 'Plate number', ar: 'رقم اللوحة' }, required: true, inputKind: 'plate', maxLength: 8 }, + { name: 'plateCode', type: 'text', label: { en: 'Plate code', ar: 'رمز اللوحة' }, required: true, inputKind: 'code', maxLength: 2 }, + { name: 'category', type: 'autocomplete', label: { en: 'Category', ar: 'الفئة' }, required: true, options: categoryOptions }, + { + name: 'status', type: 'select', label: { en: 'Status', ar: 'الحالة' }, hiddenOnCreate: true, readOnly: true, + options: statuses.map((s) => ({ value: s.value, label: s.label })), + }, + ], + }, + { + key: 'owner', + title: { en: 'Owner', ar: 'المالك' }, + fields: [ + { name: 'nationality', type: 'select', label: { en: 'Nationality', ar: 'الجنسية' }, required: true, options: nationalities }, + // national id: Omani only (required when shown). passport: non-Omani only (required when shown). + { + name: 'nationalId', type: 'text', label: { en: 'National ID', ar: 'الرقم المدني' }, inputKind: 'code', maxLength: 10, + hiddenWhen: { not: { field: 'nationality', op: 'eq', value: 'OM' } }, + requiredWhen: { field: 'nationality', op: 'eq', value: 'OM' }, + }, + { + name: 'passportNo', type: 'text', label: { en: 'Passport number', ar: 'رقم الجواز' }, inputKind: 'code', + hiddenWhen: { any: [{ field: 'nationality', op: 'eq', value: 'OM' }, { field: 'nationality', op: 'empty' }] }, + requiredWhen: { field: 'nationality', op: 'notEmpty' }, + }, + { name: 'ownerIsStakeholder', type: 'checkbox', label: { en: 'Vehicle belongs to the stakeholder', ar: 'المركبة مملوكة للجهة' } }, + { + name: 'ownerName', type: 'text', label: { en: 'Owner name', ar: 'اسم المالك' }, + requiredWhen: { not: { field: 'ownerIsStakeholder' } }, + disabledWhen: { field: 'ownerIsStakeholder' }, + }, + { + name: 'phone', type: 'text', label: { en: 'Phone', ar: 'الهاتف' }, inputKind: 'phone', + pattern: { regex: /^\+?\d{8,15}$/, message: { en: 'Digits only, 8-15 characters', ar: 'أرقام فقط، من 8 إلى 15 رقماً' } }, + }, + { + name: 'email', type: 'text', label: { en: 'Email', ar: 'البريد الإلكتروني' }, inputKind: 'email', + pattern: { regex: /^[^@\s]+@[^@\s]+\.[^@\s]+$/, message: { en: 'Enter a valid email', ar: 'أدخل بريداً إلكترونياً صحيحاً' } }, + }, + ], + }, + { + key: 'validity', + title: { en: 'Validity and documents', ar: 'الصلاحية والمستندات' }, + fields: [ + { name: 'issueDate', type: 'date', label: { en: 'Issue date', ar: 'تاريخ الإصدار' }, required: true }, + { name: 'expiryDate', type: 'date', label: { en: 'Expiry date', ar: 'تاريخ الانتهاء' }, required: true }, + { name: 'attachmentId', type: 'attachment', label: { en: 'Registration card', ar: 'بطاقة التسجيل' }, attachment: { accept: 'image/*,.pdf' } }, + { name: 'notes', type: 'textarea', label: { en: 'Notes', ar: 'ملاحظات' }, span: 'full', maxLength: 300 }, + ], + }, + ], +}; diff --git a/web/src/features/_example/mock.ts b/web/src/features/_example/mock.ts new file mode 100644 index 0000000..5699559 --- /dev/null +++ b/web/src/features/_example/mock.ts @@ -0,0 +1,71 @@ +import { MockHttpError, registerMock } from '@/api/mock'; +import type { Vehicle, VehicleStatus } from './types'; + +const cats = ['Heavy truck', 'Trailer head', 'Pickup', 'Tanker', 'Flatbed']; +const owners = ['Ahmed Al Balushi', 'Salim Al Harthi', 'Fatma Al Rawahi', 'Khalid Al Siyabi', 'Nasser Al Kindi', 'Mariam Al Busaidi']; +const nats = ['OM', 'OM', 'OM', 'AE', 'IN', 'PK']; +const stat: VehicleStatus[] = ['ACTIVE', 'ACTIVE', 'PENDING', 'BLOCKED']; + +let rows: Vehicle[] = Array.from({ length: 57 }, (_, i) => { + const nat = nats[i % nats.length]!; + return { + id: i + 1, + plateNumber: String(1000 + i * 37), + plateCode: 'ABC'.charAt(i % 3) + 'D'.charAt(0), + category: cats[i % cats.length]!, + status: stat[i % stat.length]!, + nationality: nat, + nationalId: nat === 'OM' ? String(10000000 + i * 91) : null, + passportNo: nat === 'OM' ? null : `P${200000 + i}`, + ownerIsStakeholder: false, + ownerName: owners[i % owners.length]!, + phone: `+9689${String(1000000 + i * 1234).slice(0, 7)}`, + email: `owner${i + 1}@example.com`, + issueDate: '2024-03-15', + expiryDate: `2026-${String((i % 12) + 1).padStart(2, '0')}-${String((i % 27) + 1).padStart(2, '0')}`, + attachmentId: null, + notes: null, + }; +}); +let nextId = rows.length + 1; + +registerMock('GET', /^\/example\/categories$/, () => cats.map((c) => ({ value: c, label: c }))); + +registerMock('GET', /^\/example\/vehicles$/, ({ params }) => { + const page = Number(params.page) || 1; + const pageSize = Number(params.pageSize) || 20; + let r = rows; + if (params.status) r = r.filter((x) => x.status === params.status); + if (params.plateNumber) r = r.filter((x) => x.plateNumber.includes(params.plateNumber!)); + if (params.ownerName) r = r.filter((x) => (x.ownerName ?? '').toLowerCase().includes(params.ownerName!.toLowerCase())); + if (params.nationality) r = r.filter((x) => x.nationality === params.nationality); + if (params.category) r = r.filter((x) => x.category === params.category); + if (params.expiryFrom) r = r.filter((x) => (x.expiryDate ?? '') >= params.expiryFrom!); + return { items: r.slice((page - 1) * pageSize, page * pageSize), page, pageSize, totalCount: r.length }; +}); + +registerMock('GET', /^\/example\/vehicles\/(\d+)$/, ({ match }) => { + const v = rows.find((x) => x.id === Number(match[1])); + if (!v) throw new MockHttpError(404, 'المركبة غير موجودة'); + return v; +}); + +registerMock('POST', /^\/example\/vehicles$/, ({ body }) => { + const b = body as Partial; + if (rows.some((x) => x.plateNumber === b.plateNumber && x.plateCode === b.plateCode)) { + throw new MockHttpError(400, 'رقم اللوحة مسجل مسبقاً', { code: 'PLATE_EXISTS', errors: { plateNumber: ['رقم اللوحة مسجل مسبقاً'] } }); + } + const v = { ...(b as Vehicle), id: nextId++, status: 'PENDING' as const }; + rows = [v, ...rows]; + return { id: v.id, message: 'تم إنشاء المركبة بنجاح' }; +}); + +registerMock('PUT', /^\/example\/vehicles\/(\d+)$/, ({ match, body }) => { + rows = rows.map((x) => (x.id === Number(match[1]) ? { ...x, ...(body as Partial) } : x)); + return { message: 'تم تحديث المركبة' }; +}); + +registerMock('DELETE', /^\/example\/vehicles\/(\d+)$/, ({ match }) => { + rows = rows.filter((x) => x.id !== Number(match[1])); + return { message: 'تم حذف المركبة' }; +}); diff --git a/web/src/features/_example/pages.tsx b/web/src/features/_example/pages.tsx new file mode 100644 index 0000000..8e20f43 --- /dev/null +++ b/web/src/features/_example/pages.tsx @@ -0,0 +1,79 @@ +import { useMemo, useState } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; +import { Alert, Button } from '@mui/material'; +import AddIcon from '@mui/icons-material/Add'; +import { ApiError } from '@/api/client'; +import { DataGrid } from '@/components/DataGrid'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { MetaForm } from '@/components/MetaForm'; +import { PageHeader } from '@/components/PageHeader'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useDeleteVehicle, useSaveVehicle, useVehicle } from './api'; +import { vehicleForm, vehicleGrid } from './meta'; +import strings from './strings'; + +export function VehiclesListPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const confirm = useConfirm(); + const del = useDeleteVehicle(); + + const meta = useMemo( + () => + vehicleGrid({ + onOpen: (v) => navigate(`/example/vehicles/${v.id}`), + onDelete: async (v) => { + if (await confirm({ message: t('ex.deleteConfirm', { plate: `${v.plateNumber} ${v.plateCode}` }), danger: true })) del.mutate(v.id); + }, + }), + // eslint-disable-next-line react-hooks/exhaustive-deps + [navigate, confirm, t], + ); + + return ( + <> + } onClick={() => navigate('/example/vehicles/new')}>{t('common.create')}} + /> + + + ); +} + +export function VehicleFormPage() { + const { id } = useParams(); + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const q = useVehicle(id); + const save = useSaveVehicle(id); + const [serverErrors, setServerErrors] = useState>({}); + + return ( + <> + + {id && q.isPending && } + {id && q.isError && {q.error instanceof ApiError ? q.error.message : t('error.generic')}} + {(!id || q.data) && ( + | undefined} + serverErrors={serverErrors} + onCancel={() => navigate('/example/vehicles')} + onSubmit={(payload) => + new Promise((resolve) => { + setServerErrors({}); + save.mutate(payload, { + onSuccess: () => { resolve(); navigate('/example/vehicles'); }, + onError: (e) => { setServerErrors({ ...e.fieldErrors }); resolve(); }, + }); + }) + } + /> + )} + + ); +} diff --git a/web/src/features/_example/routes.tsx b/web/src/features/_example/routes.tsx new file mode 100644 index 0000000..379c040 --- /dev/null +++ b/web/src/features/_example/routes.tsx @@ -0,0 +1,39 @@ +import type { RouteObject } from 'react-router-dom'; +import LocalShippingIcon from '@mui/icons-material/LocalShipping'; +import ScienceIcon from '@mui/icons-material/Science'; +import { MOCK } from '@/api/client'; +import type { MenuItem } from '@/shell/types'; +import './mock'; +import strings from './strings'; +import { VehicleFormPage, VehiclesListPage } from './pages'; + +/** + * Example/demo feature: proves grid + form in AR/EN, light/dark. Hidden (no routes, no menu) unless VITE_MOCK=1. + * A real feature exports the same two names: `routes` and `menu`. + */ +export const routes: RouteObject[] = MOCK + ? [ + { path: '/example/vehicles', element: }, + { path: '/example/vehicles/new', element: , handle: { crumb: strings['ex.form.crumbNew'] } }, + { path: '/example/vehicles/:id', element: , handle: { crumb: strings['ex.form.crumbEdit'] } }, + ] + : []; + +export const menu: MenuItem[] = MOCK + ? [ + { + key: 'example', + title: strings['ex.menu.group'], + icon: ScienceIcon, + children: [ + { + key: 'example.vehicles', + title: strings['ex.menu.vehicles'], + icon: LocalShippingIcon, + path: '/example/vehicles', + createPath: '/example/vehicles/new', + }, + ], + }, + ] + : []; diff --git a/web/src/features/_example/strings.ts b/web/src/features/_example/strings.ts new file mode 100644 index 0000000..c4eb26f --- /dev/null +++ b/web/src/features/_example/strings.ts @@ -0,0 +1,15 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** Feature strings live here (merged by useFeatureUi); never edit i18n/ui.ts per slice. */ +export default defineStrings({ + 'ex.menu.group': { en: 'Example (mock)', ar: 'مثال (تجريبي)' }, + 'ex.menu.vehicles': { en: 'Vehicles', ar: 'المركبات' }, + 'ex.list.title': { en: 'Vehicles', ar: 'المركبات' }, + 'ex.list.subtitle': { en: 'Demo list driven by metadata and fake data', ar: 'قائمة تجريبية مبنية على البيانات الوصفية وبيانات وهمية' }, + 'ex.form.createTitle': { en: 'New vehicle', ar: 'مركبة جديدة' }, + 'ex.form.editTitle': { en: 'Edit vehicle', ar: 'تعديل مركبة' }, + 'ex.form.crumbNew': { en: 'New', ar: 'جديد' }, + 'ex.form.crumbEdit': { en: 'Edit', ar: 'تعديل' }, + 'ex.deleteConfirm': { en: 'Delete vehicle {plate}?', ar: 'حذف المركبة {plate}؟' }, + 'ex.deleted': { en: 'Vehicle deleted', ar: 'تم حذف المركبة' }, +}); diff --git a/web/src/features/_example/types.ts b/web/src/features/_example/types.ts new file mode 100644 index 0000000..cd0b0fe --- /dev/null +++ b/web/src/features/_example/types.ts @@ -0,0 +1,20 @@ +export type VehicleStatus = 'ACTIVE' | 'PENDING' | 'BLOCKED'; + +export interface Vehicle { + id: number; + plateNumber: string; + plateCode: string; + category: string; + status: VehicleStatus; + nationality: string; + nationalId: string | null; + passportNo: string | null; + ownerIsStakeholder: boolean; + ownerName: string | null; + phone: string | null; + email: string | null; + issueDate: string | null; + expiryDate: string | null; + attachmentId: string | null; + notes: string | null; +} diff --git a/web/src/features/grains-orders/api.ts b/web/src/features/grains-orders/api.ts new file mode 100644 index 0000000..6aef2e8 --- /dev/null +++ b/web/src/features/grains-orders/api.ts @@ -0,0 +1,153 @@ +import { useQuery } from '@tanstack/react-query'; +import { api, API_BASE, ApiError, getToken, MOCK } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; +import type { OptionItem, OptionsLoader } from '@/components/meta/types'; +import { useLanguage } from '@/providers/LanguageProvider'; +import type { + BillingPermit, CompanyDestinations, CompanyOption, FinancialBillingPage, LookupOption, OrdersResult, + PermitWeights, TenderOrderReport, +} from './types'; + +const BASE = '/grains/orders'; + +// ---------------------------------------------------------------- option loaders (cached by React Query, keyed by language) +const lookup = (key: string, path: string): OptionsLoader => ({ + key: `grains.orders.${key}`, + load: async () => (await api.get(`${BASE}/lookups/${path}`, undefined, { silent: true })) + .map((o) => ({ value: o.id, label: o.name ?? String(o.id) })), +}); + +export const cargoTypeOptions = lookup('cargo', 'cargo-types'); +export const loadingLocationOptions = lookup('loading', 'loading-locations'); +export const destinationOptions = lookup('destinations', 'destinations'); +export const billingDestinationOptions = lookup('billingDest', 'billing-destinations'); + +export const companyOptions: OptionsLoader = { + key: 'grains.orders.companies', + load: async () => (await api.get(`${BASE}/lookups/companies`, undefined, { silent: true })) + .map((c) => ({ value: c.scac, label: c.label ?? String(c.scac) })), +}; + +/** Invoice numbers of the company chosen in the parent field. */ +export const invoiceNumberOptions: OptionsLoader = { + key: 'grains.orders.invoiceNumbers', + load: async ({ parent }) => + (await api.get(`${BASE}/reports/invoice-numbers`, { scac: parent }, { silent: true })) + .map((n) => ({ value: n, label: String(n) })), + staleTime: 30_000, +}; + +// ---------------------------------------------------------------- queries +export function useCompanies() { + const { lang, langReady } = useLanguage(); + return useQuery({ + queryKey: ['grains.orders.companies.list', lang], + queryFn: () => api.get(`${BASE}/lookups/companies`, undefined, { silent: true }), + enabled: langReady, + staleTime: 5 * 60_000, + }); +} + +export function usePackedDestinations() { + const { lang, langReady } = useLanguage(); + return useQuery({ + queryKey: ['grains.orders.packedDest', lang], + queryFn: () => api.get(`${BASE}/lookups/packed-destinations`, undefined, { silent: true }), + enabled: langReady, + staleTime: 5 * 60_000, + }); +} + +export function useCompanyDestinations(scac: number | null) { + return useQuery({ + queryKey: ['grains.orders.companyDest', scac], + queryFn: () => api.get(`${BASE}/company-destinations/${scac}`), + enabled: scac !== null, + }); +} + +export function useTenderOrderReport(orderDate: string) { + const { langReady } = useLanguage(); + return useQuery({ + queryKey: ['grains.orders.report', orderDate], + queryFn: () => api.get(`${BASE}/reports/tender-orders`, { orderDate }), + enabled: langReady && !!orderDate, + }); +} + +export const fetchBillingPermit = (pn: string, scac: string) => + api.get(`${BASE}/billing/permit/${encodeURIComponent(pn)}`, { scac }); + +export const fetchPermitWeights = (pn: string) => api.get(`${BASE}/weights/${encodeURIComponent(pn)}`); + +export const fetchFinancialBilling = (params: Record) => + api.get(`${BASE}/reports/financial-billing`, params); + +// ---------------------------------------------------------------- writes +export function useCreateOrder() { + return useWrite((payload: Record) => api.post(BASE, payload), { + invalidate: [gridKey('grains.orders'), ['grains.orders.report']], + }); +} + +export function useDeleteOrder() { + return useWrite((id: number) => api.delete(`${BASE}/${id}`), { + invalidate: [gridKey('grains.orders'), ['grains.orders.report']], + }); +} + +export function usePublishOrder() { + return useWrite((v: { id: number; show: boolean }) => api.put(`${BASE}/${v.id}/mobile`, { show: v.show }), { + invalidate: [gridKey('grains.orders')], + }); +} + +export function useSetQuota() { + return useWrite( + (v: { destinationId: number; quotaDate: string; quota: number }) => api.put(`${BASE}/quotas`, v), + { invalidate: [gridKey('grains.orders.quotas')] }, + ); +} + +export function useAddBilling() { + return useWrite((payload: Record) => api.post(`${BASE}/billing`, payload), { + invalidate: [gridKey('grains.orders.billing')], + }); +} + +export function useSaveWeights() { + return useWrite((payload: Record) => api.post(`${BASE}/weights`, payload)); +} + +export function useSaveCompanyDestinations(scac: number | null) { + return useWrite( + (locationIds: number[]) => api.put(`${BASE}/company-destinations/${scac}`, { locationIds }), + { invalidate: [['grains.orders.companyDest']] }, + ); +} + +// ---------------------------------------------------------------- CSV / Excel download (bearer token, so not a plain link) +export async function downloadExport(path: string, params: Record, fallbackName: string): Promise { + if (MOCK) return; + const qs = new URLSearchParams(); + for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== '') qs.append(k, String(v)); + const token = getToken(); + const res = await fetch(`${API_BASE}${BASE}${path}?${qs}`, { headers: token ? { Authorization: `Bearer ${token}` } : {} }); + if (!res.ok) { + let problem: { detail?: string; title?: string } | undefined; + try { problem = await res.json(); } catch { /* not JSON */ } + throw new ApiError(res.status, problem?.detail || problem?.title || res.statusText, problem); + } + const disposition = res.headers.get('Content-Disposition') ?? ''; + const match = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(disposition); + const name = match ? decodeURIComponent(match[1]) : fallbackName; + const url = URL.createObjectURL(await res.blob()); + const a = document.createElement('a'); + a.href = url; + a.download = name; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); +} diff --git a/web/src/features/grains-orders/meta/billing.tsx b/web/src/features/grains-orders/meta/billing.tsx new file mode 100644 index 0000000..9d67c93 --- /dev/null +++ b/web/src/features/grains-orders/meta/billing.tsx @@ -0,0 +1,158 @@ +import type { FormMeta, GridMeta, StatusMeta } from '@/components/meta/types'; +import { + billingDestinationOptions, cargoTypeOptions, companyOptions, fetchFinancialBilling, invoiceNumberOptions, +} from '../api'; +import type { BillingRow, FinancialBillingRow, FinancialBillingTotals, InvoiceRow } from '../types'; + +/** Declarative tables for billing, invoices, loading weights and the financial report. */ + +// ---------------------------------------------------------------- billing list (BillingGrid.cfm) +export const billingGrid = (): GridMeta => ({ + key: 'grains.orders.billing', + endpoint: '/grains/orders/billing', + rowKey: (r) => r.id, + requireFilter: true, // legacy returned an empty grid without a filter + filters: [ + { name: 'pn', type: 'text', label: { en: 'Permit number', ar: 'رقم الارسالية' }, inputKind: 'code' }, + { name: 'tn', type: 'text', label: { en: 'Trailer number', ar: 'رقم المقطورة' }, inputKind: 'code' }, + { name: 'scac', type: 'autocomplete', label: { en: 'Company', ar: 'اسم الشركة' }, options: companyOptions }, + ], + columns: [ + { key: 'pn', header: { en: 'Permit no.', ar: 'رقم الارسالية' }, ltr: true }, + { key: 'tn', header: { en: 'Trailer no.', ar: 'رقم المقطورة' }, ltr: true }, + { key: 'scac', header: { en: 'Company', ar: 'اسم الشركة' }, hideBelow: 'sm' }, + { key: 'cargoType', header: { en: 'Cargo', ar: 'نوع المادة' }, hideBelow: 'md' }, + { key: 'destination', header: { en: 'Destination', ar: 'الوجهة' } }, + { key: 'loadDate', header: { en: 'Load date', ar: 'تاريخ التحميل' }, format: 'date', ltr: true, hideBelow: 'md' }, + { key: 'dischargeDate', header: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, format: 'date', ltr: true, hideBelow: 'md' }, + { key: 'lnw', header: { en: 'Sent weight', ar: 'الوزن المرسل' }, format: 'number', align: 'end' }, + { key: 'dnw', header: { en: 'Received weight', ar: 'الوزن المستلم' }, format: 'number', align: 'end' }, + ], +}); + +// ---------------------------------------------------------------- billing entry form (BillingScreen.cfm) +/** Fields the legacy page marked readonly are filled from the permit (weights, prices) and are not sent. */ +export const billingForm: FormMeta = { + key: 'grains.orders.billing.form', + sections: [ + { + key: 'claim', + columns: 2, + fields: [ + { name: 'invoiceNumber', type: 'text', label: { en: 'Invoice number', ar: 'رقم المطالبة' }, required: true, inputKind: 'code', maxLength: 12, pattern: { regex: /^\d+$/, message: { en: 'Digits only', ar: 'أرقام فقط' } } }, + { name: 'serialNo', type: 'text', label: { en: 'Document number', ar: 'رقم المستند' }, required: true, inputKind: 'code', maxLength: 30 }, + { name: 'loadDate', type: 'date', label: { en: 'Load date', ar: 'تاريخ التحميل' }, required: true }, + { name: 'dischargeDate', type: 'date', label: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, required: true }, + { name: 'origin', type: 'text', label: { en: 'From', ar: 'من' }, readOnly: true }, + { name: 'destination', type: 'select', label: { en: 'To', ar: 'الى' }, required: true, options: billingDestinationOptions }, + { name: 'cargoType', type: 'select', label: { en: 'Cargo type', ar: 'نوع المادة' }, required: true, options: cargoTypeOptions }, + { name: 'tn', type: 'text', label: { en: 'Truck number', ar: 'رقم السيارة' }, required: true, inputKind: 'plate', maxLength: 20 }, + { name: 'lnw', type: 'number', label: { en: 'Sent weight', ar: 'الوزن المرسل' }, readOnly: true }, + { name: 'dnw', type: 'number', label: { en: 'Received weight', ar: 'الوزن المستلم' }, readOnly: true }, + { name: 'price', type: 'number', label: { en: 'Price', ar: 'السعر' }, readOnly: true }, + { name: 'finePrice', type: 'number', label: { en: 'Fine price', ar: 'سعر التغريم' }, readOnly: true }, + ], + }, + ], +}; + +// ---------------------------------------------------------------- invoices (InvoiceGrid.cfm) +export const invoiceStatuses: StatusMeta[] = [ + { value: 'ARCHIVED', label: { en: 'Archived', ar: 'مؤرشف' }, color: 'default' }, +]; + +const slashDate = (s: string | null) => { + const m = s ? /^(\d{4})\/(\d{2})\/(\d{2})/.exec(s) : null; + return m ? `${m[3]}/${m[2]}/${m[1]}` : (s ?? ''); +}; + +export const invoiceGrid = (h: { onExport: (r: InvoiceRow, format: 'csv' | 'xlsx') => void }): GridMeta => ({ + key: 'grains.orders.invoices', + endpoint: '/grains/orders/invoices', + rowKey: (r) => r.id, + requireFilter: true, + filters: [{ name: 'invoiceNumber', type: 'text', label: { en: 'Invoice number', ar: 'رقم الفاتورة' }, inputKind: 'code' }], + columns: [ + { key: 'invoiceNumber', header: { en: 'Invoice number', ar: 'رقم الفاتورة' }, ltr: true }, + { key: 'companyName', header: { en: 'Company', ar: 'الشركة' } }, + { key: 'invoiceDate', header: { en: 'Entry date', ar: 'تاريخ الإدخال' }, ltr: true, hideBelow: 'sm', render: (r) => slashDate(r.invoiceDate) }, + { key: 'count', header: { en: 'Count', ar: 'العدد' }, format: 'number', align: 'end' }, + { key: 'statusCode', header: { en: 'Status', ar: 'الحالة' }, format: 'status', statuses: invoiceStatuses }, + ], + rowActions: [ + { key: 'xlsx', label: { en: 'Print Excel', ar: 'طباعة XLS' }, onClick: (r) => h.onExport(r, 'xlsx') }, + { key: 'csv', label: { en: 'Export CSV', ar: 'تصدير CSV' }, onClick: (r) => h.onExport(r, 'csv') }, + ], +}); + +// ---------------------------------------------------------------- loading weights (addGrainsWeights.cfm) +const fiveDigits = { regex: /^\d{5}$/, message: { en: 'Exactly 5 digits', ar: 'يجب ان يكون الوزن من 5 خانات' } }; + +export const weightsForm: FormMeta = { + key: 'grains.orders.weights.form', + sections: [ + { + key: 'truck', + columns: 3, + fields: [ + { name: 'tn', type: 'text', label: { en: 'Truck number', ar: 'رقم القاطرة' }, readOnly: true, inputKind: 'plate' }, + { name: 'trn', type: 'text', label: { en: 'Trailer number', ar: 'رقم المقطورة' }, readOnly: true, inputKind: 'plate' }, + { name: 'driver', type: 'text', label: { en: 'Driver', ar: 'السائق' }, readOnly: true }, + ], + }, + { + key: 'weights', + columns: 3, + fields: [ + { name: 'emptyWeight', type: 'text', label: { en: 'Empty weight', ar: 'الوزن الفارغ' }, required: true, inputKind: 'code', maxLength: 5, pattern: fiveDigits }, + { name: 'grossWeight', type: 'text', label: { en: 'Gross weight', ar: 'الوزن القائم' }, required: true, inputKind: 'code', maxLength: 5, pattern: fiveDigits }, + { + name: 'documentNumber', type: 'text', label: { en: 'Shipping document number', ar: 'رقم مستند الشحن' }, required: true, inputKind: 'code', maxLength: 12, + pattern: { regex: /^\d{1,12}$/, message: { en: 'Digits only (up to 12)', ar: 'أرقام فقط (حتى 12)' } }, + }, + ], + }, + ], +}; + +// ---------------------------------------------------------------- financial billing report (FinancialBilling.cfm) +export const financialGrid = (h: { onTotals: (t: FinancialBillingTotals | null) => void }): GridMeta => ({ + key: 'grains.orders.financial', + rowKey: (r) => r.id, + requireFilter: true, + pageSize: 50, + pageSizeOptions: [25, 50, 100, 200], + filters: [ + { name: 'scac', type: 'autocomplete', label: { en: 'Company', ar: 'اسم الشركة' }, options: companyOptions }, + { name: 'invoiceNumber', type: 'select', label: { en: 'Invoice number', ar: 'رقم المطالبة' }, options: invoiceNumberOptions, dependsOn: 'scac' }, + ], + // both filters are needed; one request per action, totals come back with the page + fetcher: async (q) => { + const { scac, invoiceNumber } = q.filters; + if (!scac || !invoiceNumber) { + h.onTotals(null); + return { items: [], page: q.page, pageSize: q.pageSize, totalCount: 0 }; + } + const r = await fetchFinancialBilling({ scac, invoiceNumber, page: q.page, pageSize: q.pageSize }); + h.onTotals(r.totals); + return r; + }, + columns: [ + { key: 'pn', header: { en: 'Permit no.', ar: 'رقم الارسالية' }, ltr: true }, + { key: 'serialNo', header: { en: 'Document no.', ar: 'رقم المستند' }, ltr: true, hideBelow: 'md' }, + { key: 'loadDate', header: { en: 'Load date', ar: 'تاريخ التحميل' }, ltr: true, hideBelow: 'md' }, + { key: 'destination', header: { en: 'To', ar: 'الى' } }, + { key: 'cargoType', header: { en: 'Cargo', ar: 'نوع المادة' }, hideBelow: 'lg' }, + { key: 'tn', header: { en: 'Truck', ar: 'رقم السيارة' }, ltr: true, hideBelow: 'sm' }, + { key: 'lnw', header: { en: 'Sent weight', ar: 'الوزن المرسل' }, format: 'number', align: 'end' }, + { key: 'dischargeDate', header: { en: 'Discharge date', ar: 'تاريخ التفريغ' }, ltr: true, hideBelow: 'lg' }, + { key: 'dnw', header: { en: 'Received weight', ar: 'الوزن المستلم' }, format: 'number', align: 'end' }, + { key: 'difference', header: { en: 'Difference', ar: 'الفرق' }, format: 'number', align: 'end', hideBelow: 'md' }, + { key: 'price', header: { en: 'Price', ar: 'السعر' }, format: 'number', align: 'end', hideBelow: 'lg' }, + { key: 'finePrice', header: { en: 'Fine price', ar: 'سعر التغريم' }, format: 'number', align: 'end', hideBelow: 'lg' }, + { key: 'loseFine', header: { en: 'Shortage fine', ar: 'غرامة النقص' }, format: 'number', align: 'end', hideBelow: 'md' }, + { key: 'demurrageFine', header: { en: 'Demurrage fine', ar: 'غرامة التاخير' }, format: 'number', align: 'end', hideBelow: 'lg' }, + { key: 'otherFine', header: { en: 'Other fines', ar: 'غرامات آخرى' }, format: 'number', align: 'end', hideBelow: 'lg' }, + { key: 'finalCost', header: { en: 'Final value', ar: 'القيمة النهائية' }, format: 'number', align: 'end' }, + ], +}); diff --git a/web/src/features/grains-orders/meta/orders.tsx b/web/src/features/grains-orders/meta/orders.tsx new file mode 100644 index 0000000..b1b0283 --- /dev/null +++ b/web/src/features/grains-orders/meta/orders.tsx @@ -0,0 +1,143 @@ +import { Chip } from '@mui/material'; +import type { FormMeta, GridMeta, L10n, OptionItem } from '@/components/meta/types'; +import { cargoTypeOptions, destinationOptions, loadingLocationOptions } from '../api'; +import type { Quota, TenderOrder } from '../types'; + +/** Declarative tables for tender orders and daily quotas (legacy tenderOrderGrid.cfm, createNewTenderOrder.cfm, quotaGrid.cfm). */ + +/** CARGOTYPE.ID 41 = packed cargo; destinations 350/440/465 always take tipper trucks (legacy hard-codes). */ +export const PACKED_CARGO_ID = 41; +export const TIPPER_DESTINATION_IDS = [350, 440, 465]; + +const p2 = (n: number) => String(n).padStart(2, '0'); +export const toIsoDate = (d: Date) => `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`; +export const todayIso = () => toIsoDate(new Date()); + +/** The legacy dropdown offered today .. today + 4 days. */ +export function orderDateOptions(): OptionItem[] { + return Array.from({ length: 5 }, (_, i) => { + const d = new Date(); + d.setDate(d.getDate() + i); + return { value: toIsoDate(d), label: `${p2(d.getDate())}/${p2(d.getMonth() + 1)}/${d.getFullYear()}` }; + }); +} + +export const shiftLabels: Record = { + 1: { en: 'Morning', ar: 'صباحي' }, + 2: { en: 'Evening', ar: 'مسائي' }, + 3: { en: 'Night', ar: 'ليلي' }, +}; + +const typeLabels: Record = { + COMP: { en: 'Companies', ar: 'شركات' }, + AHALE: { en: 'Individuals', ar: 'أفراد' }, +}; +const everyone: L10n = { en: 'Everyone', ar: 'الكل' }; + +const shiftOptions: OptionItem[] = [1, 2, 3].map((v) => ({ value: v, label: shiftLabels[v]! })); +const typeOptions: OptionItem[] = [ + { value: 'AHALE', label: { en: 'Individuals - locals', ar: 'أفراد - أهالي' } }, + { value: 'COMP', label: { en: 'Companies', ar: 'شركات' } }, +]; + +export interface OrderGridHandlers { + onDelete: (o: TenderOrder) => void; + onMobile: (o: TenderOrder, show: boolean) => void; +} + +export const tenderOrderGrid = (h: OrderGridHandlers): GridMeta => ({ + key: 'grains.orders', + endpoint: '/grains/orders', + rowKey: (r) => r.id, + emptyAsGrid: true, // no orders for the day: the headers stay, "no results" shows inside the table + // The legacy grid stayed empty until a date was typed: start on today (clear the filter to list every day). + defaultFilters: { orderDate: todayIso() }, + filters: [{ name: 'orderDate', type: 'date', label: { en: 'Order date', ar: 'تاريخ الطلبية' } }], + columns: [ + { key: 'cargoType', header: { en: 'Cargo type', ar: 'نمط الحمولة' } }, + { key: 'location', header: { en: 'Loading site', ar: 'موقع التحميل' }, hideBelow: 'sm' }, + { key: 'destination', header: { en: 'Destination', ar: 'الوجهه' } }, + { key: 'orderDate', header: { en: 'Order date', ar: 'تاريخ الطلبية' }, format: 'date', ltr: true }, + { + key: 'mobileShift', header: { en: 'Shift', ar: 'الفترة' }, hideBelow: 'md', + render: (r, { lang }) => (r.mobileShift && shiftLabels[r.mobileShift] ? shiftLabels[r.mobileShift]![lang] : ''), + }, + { key: 'quantity', header: { en: 'Trucks', ar: 'عدد السيارات' }, format: 'number', align: 'end' }, + { key: 'usedQuota', header: { en: 'Used', ar: 'المستخدم' }, format: 'number', align: 'end', hideBelow: 'sm' }, + { key: 'isTipper', header: { en: 'Tipper', ar: 'قلاب' }, format: 'boolean', hideBelow: 'lg' }, + { + key: 'type', header: { en: 'Individuals / companies', ar: 'افراد - شركات' }, hideBelow: 'md', + render: (r, { lang }) => (r.type && typeLabels[r.type] ? typeLabels[r.type]![lang] : everyone[lang]), + }, + { + key: 'mobileShow', header: { en: 'On mobile', ar: 'على الموبايل' }, hideBelow: 'md', + render: (r, { lang }) => + r.mobileShow === null ? '' : ( + + ), + }, + ], + rowActions: [ + { + key: 'mobileHide', label: { en: 'Hide on mobile', ar: 'إخفاء على الموبايل' }, + hidden: (r) => r.mobileShow !== true, onClick: (r) => h.onMobile(r, false), + }, + { + key: 'mobileShow', label: { en: 'Show on mobile', ar: 'اظهار على الموبايل' }, + hidden: (r) => r.mobileShow !== false, onClick: (r) => h.onMobile(r, true), + }, + { key: 'delete', label: { en: 'Delete', ar: 'حذف' }, danger: true, hidden: (r) => !r.canDelete, onClick: h.onDelete }, + ], +}); + +export const tenderOrderForm = (): FormMeta => ({ + key: 'grains.orders.form', + sections: [ + { + key: 'order', + columns: 2, + fields: [ + { name: 'cargoType', type: 'select', label: { en: 'Cargo type', ar: 'نمط الحمولة' }, required: true, options: cargoTypeOptions }, + { name: 'location', type: 'select', label: { en: 'Loading site', ar: 'موقع التحميل' }, required: true, options: loadingLocationOptions }, + { name: 'destination', type: 'select', label: { en: 'Destination', ar: 'الوجهه' }, required: true, options: destinationOptions }, + { name: 'orderDate', type: 'select', label: { en: 'Order date', ar: 'تاريخ الطلبية' }, required: true, options: orderDateOptions() }, + { name: 'shift', type: 'select', label: { en: 'Shift', ar: 'الفترة' }, required: true, options: shiftOptions }, + { name: 'quantity', type: 'number', label: { en: 'Number of trucks', ar: 'عدد السيارات' }, required: true, min: 1, max: 200 }, + { + // packed cargo and the tipper destinations lock this box (legacy checkIfGallab); the backend derives CT anyway + name: 'isTipper', type: 'checkbox', label: { en: 'Tipper', ar: 'قلاب' }, + disabledWhen: { any: [{ field: 'cargoType', op: 'eq', value: PACKED_CARGO_ID }, { field: 'destination', op: 'in', value: TIPPER_DESTINATION_IDS }] }, + helper: { en: 'Locked for packed cargo; applied automatically for tipper destinations.', ar: 'مقفل للمشوّل؛ ويُطبّق تلقائياً لوجهات القلاب.' }, + }, + { + name: 'type', type: 'select', label: { en: 'Companies / individuals', ar: 'شركات \\ أفراد' }, + options: typeOptions, + hiddenWhen: { field: 'cargoType', op: 'eq', value: PACKED_CARGO_ID }, + requiredWhen: { not: { field: 'cargoType', op: 'eq', value: PACKED_CARGO_ID } }, + }, + ], + }, + ], +}); + +// ---------------------------------------------------------------- quotas +export const quotaGrid = (h: { onEdit: (q: Quota) => void }): GridMeta => ({ + key: 'grains.orders.quotas', + endpoint: '/grains/orders/quotas', + rowKey: (r) => r.destinationId, + defaultFilters: { date: todayIso() }, + filters: [{ name: 'date', type: 'date', label: { en: 'Day', ar: 'اليوم' } }], + pageSize: 50, + pageSizeOptions: [25, 50, 100], + onRowClick: h.onEdit, + columns: [ + { key: 'name', header: { en: 'Destination', ar: 'الموقع' } }, + { key: 'quotaDate', header: { en: 'Day', ar: 'اليوم' }, format: 'date', ltr: true, hideBelow: 'sm' }, + { key: 'quota', header: { en: 'Daily quota', ar: 'الحصة اليومية' }, format: 'number', align: 'end' }, + { key: 'doneQuota', header: { en: 'Used quota', ar: 'الحصة المستخدمة' }, format: 'number', align: 'end' }, + { key: 'createdBy', header: { en: 'Changed by', ar: 'تعديل من قبل' }, hideBelow: 'md' }, + { key: 'creationDate', header: { en: 'Changed on', ar: 'تاريخ التعديل' }, format: 'datetime', ltr: true, hideBelow: 'md' }, + ], + rowActions: [{ key: 'edit', label: { en: 'Edit quota', ar: 'تعديل الحصة' }, onClick: h.onEdit }], +}); diff --git a/web/src/features/grains-orders/pages.tsx b/web/src/features/grains-orders/pages.tsx new file mode 100644 index 0000000..4b7227e --- /dev/null +++ b/web/src/features/grains-orders/pages.tsx @@ -0,0 +1,617 @@ +import { useEffect, useMemo, useState, type KeyboardEvent } from 'react'; +import { useNavigate, useSearchParams } from 'react-router-dom'; +import { + Alert, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Paper, Stack, + Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography, +} from '@mui/material'; +import AddIcon from '@mui/icons-material/Add'; +import AssessmentIcon from '@mui/icons-material/Assessment'; +import DownloadIcon from '@mui/icons-material/Download'; +import SearchIcon from '@mui/icons-material/Search'; +import { ApiError } from '@/api/client'; +import { DataGrid } from '@/components/DataGrid'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { MetaForm } from '@/components/MetaForm'; +import { PageHeader } from '@/components/PageHeader'; +import { formatNumber } from '@/components/meta/format'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { + downloadExport, fetchBillingPermit, fetchPermitWeights, useAddBilling, useCompanies, useCompanyDestinations, + useCreateOrder, useDeleteOrder, usePackedDestinations, usePublishOrder, useSaveCompanyDestinations, useSaveWeights, + useSetQuota, useTenderOrderReport, +} from './api'; +import { billingForm, billingGrid, financialGrid, invoiceGrid, weightsForm } from './meta/billing'; +import { + quotaGrid, tenderOrderForm, tenderOrderGrid, todayIso, +} from './meta/orders'; +import strings from './strings'; +import type { BillingPermit, FinancialBillingTotals, InvoiceRow, PermitWeights, Quota } from './types'; + +const INDIVIDUALS_SCAC = 327; + +// Backend-driven (GET /auth/permissions), replacing the legacy hard-coded read-only roles (GOO, OPOFF, ONO). +function useCanCreateOrders() { + const { can } = useAuth(); + return can('grains.orders.create'); +} +function useCanSeeOrdersReport() { + const { can } = useAuth(); + return can('grains.orders.reportOrders'); +} + +const errText = (e: unknown, fallback: string) => (e instanceof ApiError ? e.message : fallback); + +// ================================================================= tender orders +export function TenderOrdersPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const confirm = useConfirm(); + const del = useDeleteOrder(); + const pub = usePublishOrder(); + const canCreate = useCanCreateOrders(); + const canReport = useCanSeeOrdersReport(); + + const meta = useMemo( + () => + tenderOrderGrid({ + onDelete: async (o) => { + if (await confirm({ message: t('ord.orders.deleteConfirm'), danger: true })) del.mutate(o.id); + }, + onMobile: async (o, show) => { + if (await confirm({ message: t(show ? 'ord.orders.mobileShowConfirm' : 'ord.orders.mobileHideConfirm') })) pub.mutate({ id: o.id, show }); + }, + }), + // eslint-disable-next-line react-hooks/exhaustive-deps + [confirm, t], + ); + + return ( + <> + + {canReport && ( + + )} + {canCreate && ( + + )} + + )} + /> + + + ); +} + +export function TenderOrderCreatePage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const create = useCreateOrder(); + const canManage = useCanCreateOrders(); + const meta = useMemo(() => tenderOrderForm(), []); + const [serverErrors, setServerErrors] = useState>({}); + const initial = useMemo(() => ({ orderDate: todayIso() }), []); + + if (!canManage) return {t('ord.forbidden')}; + + return ( + <> + + navigate('/grains/orders')} + onSubmit={(payload) => + new Promise((resolve) => { + setServerErrors({}); + create.mutate( + { ...payload, quantity: Number(payload.quantity), shift: Number(payload.shift), isTipper: payload.isTipper === true }, + { + onSuccess: () => { resolve(); navigate('/grains/orders'); }, + onError: (e) => { setServerErrors({ ...e.fieldErrors }); resolve(); }, + }, + ); + }) + } + /> + + ); +} + +// ================================================================= quotas +export function QuotasPage() { + const { t } = useFeatureUi(strings); + const confirm = useConfirm(); + const toast = useToast(); + const setQuota = useSetQuota(); + const [editing, setEditing] = useState(null); + const [value, setValue] = useState(''); + const meta = useMemo(() => quotaGrid({ onEdit: (q) => { setEditing(q); setValue(q.quota === null ? '' : String(q.quota)); } }), []); + + const parsed = /^\d+$/.test(value.trim()) ? Number(value) : NaN; + const invalid = Number.isNaN(parsed) || (editing ? parsed < editing.doneQuota : false); + + async function save() { + if (!editing || invalid) return; + if (!(await confirm({ message: t('ord.quota.confirm') }))) return; + setQuota.mutate( + { destinationId: editing.destinationId, quotaDate: editing.quotaDate, quota: parsed }, + { onSuccess: () => setEditing(null), onError: (e) => toast.error(e.message) }, + ); + } + + return ( + <> + + + setEditing(null)} fullWidth maxWidth="xs"> + {t('ord.quota.dialogTitle', { name: editing?.name ?? '' })} + + + {t('ord.quota.used', { n: editing?.doneQuota ?? 0 })} + setValue(e.target.value)} + onKeyDown={(e: KeyboardEvent) => { if (e.key === 'Enter') { e.preventDefault(); void save(); } }} + error={value !== '' && invalid} helperText={value !== '' && invalid ? t('ord.quota.invalid') : undefined} + slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr' } }} + /> + + + + + + + + + ); +} + +// ================================================================= billing +export function BillingListPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const meta = useMemo(() => billingGrid(), []); + return ( + <> + } onClick={() => navigate('/grains/orders/billing/new')}>{t('ord.billing.new')}} + /> + + + ); +} + +/** Company + permit-number picker shared by the billing and weights screens. */ +function PermitBar(props: { + withCompany: boolean; + scac: string; + pn: string; + onScac: (v: string) => void; + onPn: (v: string) => void; + onLoad: () => void; + hint: string; +}) { + const { t } = useFeatureUi(strings); + const companies = useCompanies(); + return ( + + {props.hint} + + {props.withCompany && ( + props.onScac(e.target.value)} + slotProps={{ select: { native: true }, inputLabel: { shrink: true } }} + sx={{ flex: 2 }} + > + + {(companies.data ?? []).map((c) => )} + + )} + props.onPn(e.target.value.replace(/\D/g, '').slice(0, 12))} + onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); props.onLoad(); } }} + slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr', style: { textAlign: 'start' } } }} + sx={{ flex: 1 }} + /> + + + + ); +} + +export function BillingEntryPage() { + const { t, tr } = useFeatureUi(strings); + const navigate = useNavigate(); + const toast = useToast(); + const add = useAddBilling(); + const [scac, setScac] = useState(''); + const [pn, setPn] = useState(''); + const [permit, setPermit] = useState(null); + const [serverErrors, setServerErrors] = useState>({}); + + async function load() { + if (!pn || !scac) return; + try { + setPermit(await fetchBillingPermit(pn, scac)); + setServerErrors({}); + } catch (e) { + setPermit(null); + toast.error(errText(e, t('error.generic'))); + } + } + + const initial = useMemo( + () => + permit && { + invoiceNumber: permit.lastInvoice ?? '', + serialNo: '', + loadDate: permit.loadDate ?? '', + dischargeDate: permit.dischargeDate ?? '', + origin: tr({ en: 'Aqaba', ar: 'العقبة' }), + destination: permit.destination ?? '', + cargoType: permit.cargoType ?? '', + tn: permit.tn ?? '', + lnw: permit.lnw, + dnw: permit.dnw ?? '', + price: permit.price ?? '', + finePrice: permit.finePrice ?? '', + }, + [permit, tr], + ); + + return ( + <> + + { setScac(v); setPermit(null); }} onPn={(v) => { setPn(v); setPermit(null); }} onLoad={() => void load()} hint={t('ord.billing.entryHint')} /> + {permit && initial ? ( + navigate('/grains/orders/billing')} + onSubmit={(payload) => + new Promise((resolve) => { + setServerErrors({}); + add.mutate( + { ...payload, pn: Number(pn), scac: Number(scac) }, + { + onSuccess: () => { setPermit(null); setPn(''); resolve(); }, + onError: (e) => { setServerErrors({ ...e.fieldErrors }); resolve(); }, + }, + ); + }) + } + /> + ) : ( + {t('ord.billing.notLoaded')} + )} + + ); +} + +// ================================================================= invoices +export function InvoicesPage() { + const { t } = useFeatureUi(strings); + const toast = useToast(); + const meta = useMemo( + () => + invoiceGrid({ + onExport: (r: InvoiceRow, format) => + downloadExport('/reports/financial-billing/export', { scac: r.scac, invoiceNumber: r.invoiceNumber, format }, `FinancialReport_${r.scac}_${r.invoiceNumber}.${format}`) + .catch((e) => toast.error(errText(e, t('ord.export.failed')))), + }), + [toast, t], + ); + return ( + <> + + + + ); +} + +// ================================================================= loading weights +export function WeightsPage() { + const { t } = useFeatureUi(strings); + const toast = useToast(); + const save = useSaveWeights(); + const [pn, setPn] = useState(''); + const [data, setData] = useState(null); + const [serverErrors, setServerErrors] = useState>({}); + + async function load() { + if (!pn) return; + try { + setData(await fetchPermitWeights(pn)); + setServerErrors({}); + } catch (e) { + setData(null); + toast.error(errText(e, t('error.generic'))); + } + } + + const initial = useMemo( + () => data && { + tn: data.tn ?? '', trn: data.trn ?? '', driver: data.driver ?? '', + emptyWeight: data.emptyWeight ?? '', grossWeight: data.grossWeight ?? '', documentNumber: data.documentNumber ?? '', + }, + [data], + ); + + return ( + <> + + {}} onPn={(v) => { setPn(v); setData(null); }} onLoad={() => void load()} hint={t('ord.weights.hint')} /> + {data && initial ? ( + + new Promise((resolve) => { + setServerErrors({}); + save.mutate( + { pn: Number(pn), emptyWeight: payload.emptyWeight, grossWeight: payload.grossWeight, documentNumber: payload.documentNumber }, + { + onSuccess: () => { setData(null); setPn(''); resolve(); }, + onError: (e) => { setServerErrors({ ...e.fieldErrors }); resolve(); }, + }, + ); + }) + } + /> + ) : ( + {t('ord.billing.notLoaded')} + )} + + ); +} + +// ================================================================= company destinations +export function CompanyDestinationsPage() { + const { t } = useFeatureUi(strings); + const confirm = useConfirm(); + const companies = useCompanies(); + const packed = usePackedDestinations(); + const [scac, setScac] = useState(null); + const current = useCompanyDestinations(scac); + const save = useSaveCompanyDestinations(scac); + const [checked, setChecked] = useState>(new Set()); + + useEffect(() => { + setChecked(new Set(current.data?.locationIds ?? [])); + }, [current.data]); + + const list = packed.data ?? []; + const toggle = (id: number) => setChecked((s) => { const n = new Set(s); if (n.has(id)) n.delete(id); else n.add(id); return n; }); + + async function onSave() { + if (scac === null) return; + if (!(await confirm({ message: t('ord.compDest.saveConfirm') }))) return; + save.mutate([...checked].filter((id) => list.some((d) => d.id === id))); + } + + return ( + <> + + + + setScac(e.target.value ? Number(e.target.value) : null)} + slotProps={{ select: { native: true }, inputLabel: { shrink: true } }} + > + + {(companies.data ?? []).filter((c) => c.scac !== INDIVIDUALS_SCAC).map((c) => )} + + + {scac === null && {t('ord.compDest.pick')}} + {scac !== null && (current.isPending || packed.isPending) && } + {current.isError && {errText(current.error, t('error.generic'))}} + + {scac !== null && current.data && ( + <> + + {t('ord.compDest.packed')} + + + + {list.length === 0 && {t('ord.compDest.empty')}} + + {list.map((d) => ( + toggle(d.id)} />} + label={<>{d.id} - {d.name}} + /> + ))} + + + + + + )} + + + + ); +} + +// ================================================================= reports +export function TenderOrderReportPage() { + const { t, lang, tr } = useFeatureUi(strings); + const toast = useToast(); + const canManage = useCanSeeOrdersReport(); + const [date, setDate] = useState(todayIso()); + const q = useTenderOrderReport(canManage ? date : ''); + const n = (v: number) => formatNumber(v, lang); + const typeLabel = (v: string | null) => (v === 'AHALE' ? tr({ en: 'Individuals', ar: 'أفراد' }) : v === 'COMP' ? tr({ en: 'Companies', ar: 'شركات' }) : ''); + + if (!canManage) return {t('ord.forbidden')}; + + const exportAs = (format: 'csv' | 'xlsx') => + downloadExport('/reports/tender-orders/export', { orderDate: date, format }, `ordersReport_${date}.${format}`) + .catch((e) => toast.error(errText(e, t('ord.export.failed')))); + + return ( + <> + + + + + } + /> + + setDate(e.target.value)} + slotProps={{ inputLabel: { shrink: true }, htmlInput: { dir: 'ltr' } }} sx={{ maxWidth: 260 }} + /> + {!date && {t('ord.orders.reportPickDate')}} + {q.isPending && date && } + {q.isError && {errText(q.error, t('error.generic'))}} + {q.data && q.data.byType.length === 0 && q.data.byDestination.length === 0 && {t('ord.orders.noData')}} + {q.data && (q.data.byType.length > 0 || q.data.byDestination.length > 0) && ( + <> + {t('ord.orders.byType')} + + + + + {t('ord.orders.colType')} + {t('ord.orders.colCount')} + {t('ord.orders.colRatio')} + + + + {q.data.byType.map((r) => ( + + {typeLabel(r.type)} + {n(r.quantity)} + {r.percent}% + + ))} + + {t('ord.orders.colTotal')} + {n(q.data.typeTotal)} + 100% + + +
+
+ + {t('ord.orders.byDestination')} + + + + + {t('ord.orders.colDestination')} + {t('ord.orders.colIndividuals')} + {t('ord.orders.colIndividualsPct')} + {t('ord.orders.colCompanies')} + {t('ord.orders.colCompaniesPct')} + {t('ord.orders.colTotal')} + + + + {q.data.byDestination.map((r) => ( + + {r.destination} + {n(r.individuals)} + {r.individualsPercent}% + {n(r.companies)} + {r.companiesPercent}% + {n(r.total)} + + ))} + + {t('ord.orders.colTotal')} + {n(q.data.totalIndividuals)} + + {n(q.data.totalCompanies)} + + {n(q.data.totalIndividuals + q.data.totalCompanies)} + + +
+
+ + )} +
+ + ); +} + +export function FinancialReportPage() { + const { t, lang } = useFeatureUi(strings); + const toast = useToast(); + const [sp] = useSearchParams(); + const [totals, setTotals] = useState(null); + const meta = useMemo(() => financialGrid({ onTotals: setTotals }), []); + const scac = sp.get('scac') ?? ''; + const invoiceNumber = sp.get('invoiceNumber') ?? ''; + const n = (v: number) => formatNumber(v, lang); + + const exportAs = (format: 'csv' | 'xlsx') => + downloadExport('/reports/financial-billing/export', { scac, invoiceNumber, format }, `FinancialReport_${scac}_${invoiceNumber}.${format}`) + .catch((e) => toast.error(errText(e, t('ord.export.failed')))); + + return ( + <> + + + + + } + /> + {totals && scac && invoiceNumber && ( + + + {t('ord.fin.totals')} + {lang === 'ar' ? 'الوزن المرسل' : 'Sent'}: {n(totals.lnw)} + {lang === 'ar' ? 'الوزن المستلم' : 'Received'}: {n(totals.dnw)} + {lang === 'ar' ? 'غرامة النقص' : 'Shortage fine'}: {n(totals.loseFine)} + {lang === 'ar' ? 'غرامة التاخير' : 'Demurrage'}: {n(totals.demurrageFine)} + {lang === 'ar' ? 'غرامات آخرى' : 'Other fines'}: {n(totals.otherFine)} + {lang === 'ar' ? 'القيمة النهائية' : 'Final value'}: {n(totals.finalCost)} + + + )} + + + ); +} + diff --git a/web/src/features/grains-orders/routes.tsx b/web/src/features/grains-orders/routes.tsx new file mode 100644 index 0000000..787f5ab --- /dev/null +++ b/web/src/features/grains-orders/routes.tsx @@ -0,0 +1,50 @@ +import type { RouteObject } from 'react-router-dom'; +import AssessmentIcon from '@mui/icons-material/Assessment'; +import BusinessIcon from '@mui/icons-material/Business'; +import ListAltIcon from '@mui/icons-material/ListAlt'; +import PercentIcon from '@mui/icons-material/Percent'; +import ReceiptIcon from '@mui/icons-material/Receipt'; +import ReceiptLongIcon from '@mui/icons-material/ReceiptLong'; +import RequestQuoteIcon from '@mui/icons-material/RequestQuote'; +import ScaleIcon from '@mui/icons-material/Scale'; +import type { MenuItem } from '@/shell/types'; +import { + BillingEntryPage, BillingListPage, CompanyDestinationsPage, FinancialReportPage, InvoicesPage, QuotasPage, + TenderOrderCreatePage, TenderOrderReportPage, TenderOrdersPage, WeightsPage, +} from './pages'; +import strings from './strings'; + +/** + * Grains "orders" slice: tender orders, daily quota, billing, invoices, loading weights, company destinations and reports. + * Paths are absolute; longer paths are listed before their prefix only for readability (the router ranks by specificity). + */ +export const routes: RouteObject[] = [ + { path: '/grains/orders', element: }, + { path: '/grains/orders/new', element: , handle: { crumb: strings['ord.crumb.new'] } }, + { path: '/grains/orders/quotas', element: }, + { path: '/grains/orders/billing', element: }, + { path: '/grains/orders/billing/new', element: , handle: { crumb: strings['ord.crumb.new'] } }, + { path: '/grains/orders/invoices', element: }, + { path: '/grains/orders/weights', element: }, + { path: '/grains/orders/company-destinations', element: }, + { path: '/grains/orders/reports/tender-orders', element: }, + { path: '/grains/orders/reports/financial-billing', element: }, +]; + +export const menu: MenuItem[] = [ + { + key: 'grains.orders', + title: strings['ord.menu.group'], + icon: ReceiptLongIcon, + children: [ + { key: 'grains.orders.list', title: strings['ord.menu.orders'], icon: ListAltIcon, path: '/grains/orders', createPath: '/grains/orders/new', createKey: 'grains.orders.create' }, + { key: 'grains.orders.quotas', title: strings['ord.menu.quotas'], icon: PercentIcon, path: '/grains/orders/quotas' }, + { key: 'grains.orders.billing', title: strings['ord.menu.billing'], icon: RequestQuoteIcon, path: '/grains/orders/billing', createPath: '/grains/orders/billing/new' }, + { key: 'grains.orders.invoices', title: strings['ord.menu.invoices'], icon: ReceiptIcon, path: '/grains/orders/invoices' }, + { key: 'grains.orders.weights', title: strings['ord.menu.weights'], icon: ScaleIcon, path: '/grains/orders/weights' }, + { key: 'grains.orders.companyDest', title: strings['ord.menu.companyDest'], icon: BusinessIcon, path: '/grains/orders/company-destinations' }, + { key: 'grains.orders.reportOrders', title: strings['ord.menu.reportOrders'], icon: AssessmentIcon, path: '/grains/orders/reports/tender-orders' }, + { key: 'grains.orders.reportFinance', title: strings['ord.menu.reportFinance'], icon: AssessmentIcon, path: '/grains/orders/reports/financial-billing' }, + ], + }, +]; diff --git a/web/src/features/grains-orders/strings.ts b/web/src/features/grains-orders/strings.ts new file mode 100644 index 0000000..144736d --- /dev/null +++ b/web/src/features/grains-orders/strings.ts @@ -0,0 +1,98 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** Feature strings of the Grains "orders" slice (tender orders, quotas, billing, invoices, reports). */ +export default defineStrings({ + // ---- menu + 'ord.menu.group': { en: 'Orders and billing', ar: 'الطلبيات والمطالبات' }, + 'ord.menu.orders': { en: 'Tender orders', ar: 'الطلبيات' }, + 'ord.menu.quotas': { en: 'Daily quota', ar: 'الحصة اليومية' }, + 'ord.menu.billing': { en: 'Billing claims', ar: 'المطالبات المالية' }, + 'ord.menu.invoices': { en: 'Invoices', ar: 'فواتير التموين' }, + 'ord.menu.weights': { en: 'Loading weights', ar: 'تثبيت أوزان التحميل' }, + 'ord.menu.companyDest': { en: 'Company destinations', ar: 'وجهات الشركات' }, + 'ord.menu.reportOrders': { en: 'Orders report', ar: 'تقرير الطلبيات' }, + 'ord.menu.reportFinance': { en: 'Financial report', ar: 'التقرير المالي' }, + 'ord.crumb.new': { en: 'New', ar: 'جديد' }, + + // ---- shared + 'ord.forbidden': { en: 'You are not allowed to use this page.', ar: 'غير مصرح لك باستخدام هذه الصفحة.' }, + 'ord.export.csv': { en: 'Export CSV', ar: 'تصدير CSV' }, + 'ord.export.xlsx': { en: 'Export Excel', ar: 'تصدير Excel' }, + 'ord.export.failed': { en: 'Could not download the file', ar: 'تعذر تنزيل الملف' }, + 'ord.company': { en: 'Company', ar: 'الشركة' }, + 'ord.selectCompany': { en: 'Select a company', ar: 'اختر الشركة' }, + 'ord.load': { en: 'Load', ar: 'تحميل' }, + + // ---- tender orders + 'ord.orders.title': { en: 'Tender orders', ar: 'الطلبيات' }, + 'ord.orders.subtitle': { en: 'Daily truck orders per loading site and destination', ar: 'طلبيات الشاحنات اليومية حسب موقع التحميل والوجهة' }, + 'ord.orders.new': { en: 'New order', ar: 'طلبية جديدة' }, + 'ord.orders.report': { en: 'Report', ar: 'تقرير' }, + 'ord.orders.createTitle': { en: 'Register an order', ar: 'تسجيل طلبية' }, + 'ord.orders.deleteConfirm': { en: 'Are you sure you want to delete this order?', ar: 'هل انت متأكد من حذف هذه الطلبية؟' }, + 'ord.orders.mobileShowConfirm': { en: 'Show this order on the mobile app?', ar: 'اظهار هذه الطلبية على الموبايل؟' }, + 'ord.orders.mobileHideConfirm': { en: 'Hide this order from the mobile app?', ar: 'إخفاء هذه الطلبية على الموبايل؟' }, + 'ord.orders.tipperHelper': { en: 'Applied automatically for this destination or cargo.', ar: 'يُطبّق تلقائياً لهذه الوجهة أو الحمولة.' }, + 'ord.orders.reportTitle': { en: 'Distribution ratios of bulk orders', ar: 'نسب التوزيع في طلبيات السائب' }, + 'ord.orders.reportSubtitle': { en: 'Individuals and companies share per day and destination', ar: 'حصة الأفراد والشركات لكل يوم ووجهة' }, + 'ord.orders.reportPickDate': { en: 'Choose an order date to see the report.', ar: 'الرجاء اختيار تاريخ الطلبية لعرض التقرير.' }, + 'ord.orders.byType': { en: 'By individuals / companies', ar: 'حسب الأفراد / الشركات' }, + 'ord.orders.byDestination': { en: 'By destination', ar: 'حسب الوجهة' }, + 'ord.orders.colType': { en: 'Individuals / Companies', ar: 'افراد \\ شركات' }, + 'ord.orders.colCount': { en: 'Count', ar: 'العدد' }, + 'ord.orders.colRatio': { en: 'Ratio', ar: 'النسبة' }, + 'ord.orders.colDestination': { en: 'Destination', ar: 'الوجهة' }, + 'ord.orders.colIndividuals': { en: 'Individuals', ar: 'عدد الافراد' }, + 'ord.orders.colIndividualsPct': { en: 'Individuals %', ar: 'نسبة الافراد' }, + 'ord.orders.colCompanies': { en: 'Companies', ar: 'عدد الشركات' }, + 'ord.orders.colCompaniesPct': { en: 'Companies %', ar: 'نسبة الشركات' }, + 'ord.orders.colTotal': { en: 'Total', ar: 'المجموع' }, + 'ord.orders.noData': { en: 'No data for this date.', ar: 'لايوجد معلومات' }, + + // ---- quotas + 'ord.quota.title': { en: 'Daily quota', ar: 'الحصة اليومية' }, + 'ord.quota.subtitle': { en: 'Maximum trucks per destination for the chosen day', ar: 'أقصى عدد شاحنات لكل وجهة في اليوم المختار' }, + 'ord.quota.edit': { en: 'Edit quota', ar: 'تعديل الحصة' }, + 'ord.quota.dialogTitle': { en: 'Edit daily quota - {name}', ar: 'تعديل الحصة اليومية - {name}' }, + 'ord.quota.used': { en: 'Used quota: {n}', ar: 'الحصة المستخدمة: {n}' }, + 'ord.quota.field': { en: 'Daily quota', ar: 'الحصة اليومية' }, + 'ord.quota.invalid': { en: 'Enter a whole number that is not below the used quota.', ar: 'أدخل عدداً صحيحاً لا يقل عن الحصة المستخدمة.' }, + 'ord.quota.confirm': { en: 'Save the new daily quota?', ar: 'حفظ الحصة اليومية الجديدة؟' }, + + // ---- billing + 'ord.billing.listTitle': { en: 'Billing claims', ar: 'شاشة المطالبات المالية' }, + 'ord.billing.listSubtitle': { en: 'Claims already entered per permit', ar: 'المطالبات المدخلة لكل ارسالية' }, + 'ord.billing.new': { en: 'New claim', ar: 'إدخال مطالبة' }, + 'ord.billing.entryTitle': { en: 'Enter a billing claim', ar: 'شاشة ادخال المطالبة' }, + 'ord.billing.entryHint': { en: 'Choose the company, type the permit number and press Enter to load its data.', ar: 'اختر الشركة وأدخل رقم الارسالية ثم اضغط Enter لتحميل بياناتها.' }, + 'ord.billing.pn': { en: 'Permit number', ar: 'رقم الارسالية' }, + 'ord.billing.notLoaded': { en: 'Load a permit first.', ar: 'الرجاء تحميل الارسالية أولاً.' }, + 'ord.billing.saveConfirm': { en: 'Save this billing claim?', ar: 'حفظ هذه المطالبة؟' }, + + // ---- invoices + 'ord.invoices.title': { en: 'Supply invoices', ar: 'شاشة فواتير التموين' }, + 'ord.invoices.subtitle': { en: 'Invoices grouped by company and invoice number', ar: 'الفواتير حسب الشركة ورقم الفاتورة' }, + 'ord.invoices.archived': { en: 'Archived', ar: 'مؤرشف' }, + + // ---- weights + 'ord.weights.title': { en: 'Loading weights', ar: 'تثبيت أوزان التحميل' }, + 'ord.weights.hint': { en: 'Type the permit number and press Enter to load the truck data.', ar: 'أدخل رقم الارسالية ثم اضغط Enter لتحميل بيانات الشاحنة.' }, + 'ord.weights.saveConfirm': { en: 'Save the loading weights?', ar: 'حفظ أوزان التحميل؟' }, + 'ord.weights.digits': { en: 'Exactly 5 digits', ar: 'يجب ان يكون الوزن من 5 خانات' }, + + // ---- company destinations + 'ord.compDest.title': { en: 'Company destinations', ar: 'وجهات الشركات' }, + 'ord.compDest.subtitle': { en: 'Packed-cargo destinations each company may receive', ar: 'وجهات المشوّل المسموحة لكل شركة' }, + 'ord.compDest.packed': { en: 'Packed destinations', ar: 'مشوّل' }, + 'ord.compDest.all': { en: 'Select all', ar: 'تحديد الكل' }, + 'ord.compDest.none': { en: 'Clear all', ar: 'إلغاء التحديد' }, + 'ord.compDest.saveConfirm': { en: 'Save the destinations of this company?', ar: 'حفظ وجهات هذه الشركة؟' }, + 'ord.compDest.pick': { en: 'Select a company to view and edit its destinations.', ar: 'اختر شركة لعرض وجهاتها وتعديلها.' }, + 'ord.compDest.empty': { en: 'No packed destinations are defined.', ar: 'لا توجد وجهات مشوّل معرّفة.' }, + + // ---- financial report + 'ord.fin.title': { en: 'Financial billing report', ar: 'تقارير عطاء التموين المالية' }, + 'ord.fin.subtitle': { en: 'Transport wages by company and invoice number', ar: 'أجور النقل حسب الشركة ورقم المطالبة' }, + 'ord.fin.invoice': { en: 'Invoice number', ar: 'رقم المطالبة' }, + 'ord.fin.totals': { en: 'Totals', ar: 'المجموع' }, +}); diff --git a/web/src/features/grains-orders/types.ts b/web/src/features/grains-orders/types.ts new file mode 100644 index 0000000..40f0c28 --- /dev/null +++ b/web/src/features/grains-orders/types.ts @@ -0,0 +1,157 @@ +/** Shapes returned by api/v1/grains/orders/* (camelCase of the .NET DTOs). */ + +export interface OrdersResult { + message: string; + id?: number | null; +} + +export interface LookupOption { + id: number; + name: string | null; +} + +export interface CompanyOption { + scac: number; + label: string | null; +} + +export interface TenderOrder { + id: number; + orderDate: string; + mobileShift: number | null; + quantity: number; + usedQuota: number; + cargoType: string | null; + location: string | null; + destination: string | null; + type: 'COMP' | 'AHALE' | null; + ct: string | null; + isTipper: boolean; + mobileShow: boolean | null; + canDelete: boolean; +} + +export interface Quota { + destinationId: number; + name: string | null; + quotaDate: string; + quota: number | null; + doneQuota: number; + createdBy: string | null; + creationDate: string | null; +} + +export interface BillingPermit { + pn: number; + scac: number; + companyName: string | null; + cargoType: number | null; + tn: string | null; + destination: number | null; + loadDate: string | null; + dischargeDate: string | null; + lnw: number; + dnw: number | null; + lastInvoice: number | null; + price: number | null; + finePrice: number | null; +} + +export interface BillingRow { + id: number; + cargoType: string | null; + scac: string | null; + pn: number; + tn: string | null; + loadDate: string | null; + destination: string | null; + dischargeDate: string | null; + lnw: number | null; + dnw: number | null; + price: number | null; + finePrice: number | null; +} + +export interface InvoiceRow { + id: number; + invoiceNumber: number; + statusCode: string | null; + count: number; + companyName: string | null; + scac: number; + invoiceDate: string | null; +} + +export interface PermitWeights { + pn: number; + tn: string | null; + trn: string | null; + driver: string | null; + emptyWeight: string | null; + grossWeight: string | null; + documentNumber: string | null; +} + +export interface CompanyDestinations { + scac: number; + locationIds: number[]; +} + +export interface TenderTypeSummary { type: string | null; quantity: number; percent: number } +export interface TenderDestinationSummary { + destination: string | null; + individuals: number; + individualsPercent: number; + companies: number; + companiesPercent: number; + total: number; +} +export interface TenderOrderReport { + orderDate: string; + byType: TenderTypeSummary[]; + typeTotal: number; + byDestination: TenderDestinationSummary[]; + totalIndividuals: number; + totalCompanies: number; +} + +export interface FinancialBillingRow { + id: number; + cargoType: string | null; + companyName: string | null; + pn: number; + tn: string | null; + loadDate: string | null; + destination: string | null; + dischargeDate: string | null; + lnw: number; + dnw: number; + difference: number; + price: number; + finePrice: number; + serialNo: string | null; + origin: string | null; + loseFine: number; + demurrageFine: number; + otherFine: number; + finalCost: number; + invoiceNumber: number; + scac: number; +} + +export interface FinancialBillingTotals { + lnw: number; + dnw: number; + loseFine: number; + demurrageFine: number; + otherFine: number; + finalCost: number; +} + +export interface FinancialBillingPage { + items: FinancialBillingRow[]; + page: number; + pageSize: number; + totalCount: number; + totals: FinancialBillingTotals; +} diff --git a/web/src/features/grains-permits/api.ts b/web/src/features/grains-permits/api.ts new file mode 100644 index 0000000..4f19de9 --- /dev/null +++ b/web/src/features/grains-permits/api.ts @@ -0,0 +1,209 @@ +import { useQuery } from '@tanstack/react-query'; +import { api } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; +import type { OptionItem, OptionsLoader } from '@/components/meta/types'; +import { useLanguage } from '@/providers/LanguageProvider'; +import { useToast } from '@/providers/ToastProvider'; +import type { + AcceptPrint, AllowedDestination, CompanyOption, DestinationSearchResult, DistributionPivotRow, DistributionSummaryRow, DriverInfo, + LocationGroups, LocationTruckCount, LookupItem, OrderActivationRow, OrderChoice, PermitDetail, PermitOperationResult, PrintIn, PrintOut, + TruckDistribution, TruckInfo, WeighbridgeResult, +} from './types'; + +export const PERMITS = '/grains/permits'; +export const QUEUE = '/grains/permit-queue'; +export const DEST = '/grains/permit-destinations'; +export const DIST = '/grains/permit-distribution'; +export const WB = '/grains/permit-weighbridge'; + +export const permitGridKey = 'grains.permits'; +export const queueGridKey = 'grains.permits.queue'; +const detailKey = (id: number) => ['grains.permits.detail', id]; + +// ---------------------------------------------------------------- option loaders +const lookup = (key: string, path: string): OptionsLoader => ({ + key: `grains.permits.${key}`, + load: async () => (await api.get(`${DEST}/lookups/${path}`, undefined, { silent: true })) + .map((o) => ({ value: o.id, label: o.name ?? String(o.id) })), +}); +export const locationOptions = lookup('locations', 'locations'); +// GNPermits.cfm: destination filter = LOCATIONS domain GN, type EX, ordered by name (the lookup above serves other screens). +export const exitLocationOptions = lookup('filterDestinations', 'filter-destinations'); +// GNPermits.cfm: company filter = getCompanies() (NTP_TENDERS_COMPANIES, "SCAC-name"), value = SCAC. +export const companyFilterOptions: OptionsLoader = { + key: 'grains.permits.companyFilter', + load: async () => (await api.get(`${DEST}/lookups/companies`, undefined, { silent: true })) + .map((c) => ({ value: c.scac, label: c.companyCode ?? String(c.scac) })), +}; +// GNPermits.cfm: "حسب الطلبية" offers the last 7 days, today and tomorrow (recomputed every minute). +const p2 = (n: number) => String(n).padStart(2, '0'); +export const tenderOrderDateOptions: OptionsLoader = { + key: 'grains.permits.tenderOrderDates', + staleTime: 60_000, + load: async () => { + const out: OptionItem[] = []; + for (let d = -7; d <= 1; d++) { + const x = new Date(); + x.setDate(x.getDate() + d); + out.push({ value: `${x.getFullYear()}-${p2(x.getMonth() + 1)}-${p2(x.getDate())}`, label: `${p2(x.getDate())}/${p2(x.getMonth() + 1)}/${x.getFullYear()}` }); + } + return out; + }, +}; +export const cargoOptions = lookup('cargo', 'cargo-types'); + +// ---------------------------------------------------------------- queries +export function usePermitDetail(id: number) { + const { langReady } = useLanguage(); + return useQuery({ queryKey: detailKey(id), queryFn: () => api.get(`${PERMITS}/${id}`), enabled: langReady && id > 0 }); +} + +export const fetchTruck = (tn: string, validate = false) => + api.get(`${PERMITS}/lookups/truck/${encodeURIComponent(tn)}`, { validate }, { silent: true }); +export const fetchTrailer = (trn: string) => + api.get(`${PERMITS}/lookups/trailer/${encodeURIComponent(trn)}`, undefined, { silent: true }); +export const fetchDriver = (nnpn: string) => + api.get(`${PERMITS}/lookups/driver/${encodeURIComponent(nnpn)}`, undefined, { silent: true }); + +export function useAbsenceFeature() { + return useQuery({ queryKey: ['grains.permits.absence'], queryFn: () => api.get<{ enabled: boolean }>(`${PERMITS}/absence-feature`) }); +} + +export function useCompanies() { + const { lang, langReady } = useLanguage(); + return useQuery({ + queryKey: ['grains.permits.companies', lang], enabled: langReady, staleTime: 5 * 60_000, + queryFn: () => api.get(`${DEST}/lookups/companies`, undefined, { silent: true }), + }); +} + +export function useLocationGroups() { + return useQuery({ queryKey: ['grains.permits.locationGroups'], staleTime: 5 * 60_000, queryFn: () => api.get(`${DEST}/lookups/location-groups`, undefined, { silent: true }) }); +} + +export function useOrderDates() { + return useQuery({ queryKey: ['grains.permits.orderDates'], queryFn: () => api.get(`${DEST}/order-dates`, undefined, { silent: true }) }); +} + +export const fetchAllowedDestinations = (pn: string, orderDate: string) => + api.get(`${DEST}/allowed-destinations`, { pn, orderDate }, { silent: true }); +export const fetchOrdersForPermit = (pn: string, orderDate: string) => + api.get(`${DEST}/orders-for-permit`, { pn, orderDate }, { silent: true }); +export const searchDestination = (tn: string) => api.get(`${DEST}/search/${encodeURIComponent(tn)}`); + +export function useActivation() { + return useQuery({ queryKey: ['grains.permits.activation'], queryFn: () => api.get(`${DEST}/activation`) }); +} + +export function useDistributionSummary() { + return useQuery({ queryKey: ['grains.permits.distSummary'], queryFn: () => api.get(`${DIST}/summary`) }); +} +export function useDistributionPivot() { + return useQuery({ queryKey: ['grains.permits.distPivot'], queryFn: () => api.get(`${DIST}/pivot`) }); +} +export const searchTruckDistribution = (tn: string) => api.get(`${DIST}/search-truck`, { tn }); + +export function useLocationCounts() { + return useQuery({ queryKey: ['grains.permits.locCounts'], queryFn: () => api.get(`${WB}/location-truck-counts`), refetchInterval: 60_000 }); +} + +export function usePrintAccept(id: number) { + return useQuery({ queryKey: ['grains.permits.printAccept', id], queryFn: () => api.get(`${WB}/${id}/print/accept`), enabled: id > 0, staleTime: Infinity, retry: false }); +} +export function usePrintIn(id: number) { + return useQuery({ queryKey: ['grains.permits.printIn', id], queryFn: () => api.get(`${WB}/${id}/print/in`), enabled: id > 0, staleTime: Infinity, retry: false }); +} +export function usePrintOut(id: number) { + return useQuery({ queryKey: ['grains.permits.printOut', id], queryFn: () => api.get(`${WB}/${id}/print/out`), enabled: id > 0, staleTime: Infinity, retry: false }); +} + +// ---------------------------------------------------------------- writes +/** + * Business outcomes the legacy returned as normal responses (`success:false`, HTTP 200) are shown as warnings, not as "saved". + * useWrite toasts the backend message for successes; failures with success=false are toasted here. + */ +function useOperation(fn: (v: TVars) => Promise, invalidate: unknown[][]) { + const toast = useToast(); + return useWrite( + async (v) => { + const r = await fn(v); + if (r.success) toast.success(r.message); + else toast.warning(r.message); + return r; + }, + { invalidate, toastSuccess: false }, + ); +} + +const all: unknown[][] = [[...gridKey(permitGridKey)], [...gridKey(queueGridKey)]]; +const permitAction = (path: string) => (v: { id: number; body?: unknown }) => + api.post(`${PERMITS}/${v.id}/${path}`, v.body ?? {}); + +export function usePermitAction(path: string) { + return useOperation(permitAction(path), [...all, ['grains.permits.detail']]); +} + +export function useSubmitOrder() { + return useOperation((v: { id: number; body: Record }) => api.post(`${PERMITS}/${v.id}/submit`, v.body), + [...all, ['grains.permits.detail']]); +} +export function useUpdateOrder() { + return useOperation((v: { id: number; body: Record }) => api.put(`${PERMITS}/${v.id}`, v.body), + [...all, ['grains.permits.detail']]); +} +export function useClosePermit() { + return useOperation((pn: string) => api.post(`${PERMITS}/close`, { pn }), all); +} +export function useToggleAbsence() { + return useOperation(() => api.post(`${PERMITS}/absence-feature/toggle`), [['grains.permits.absence']]); +} +export function useAddToQueue() { + return useOperation((v: { tn: string; tt: string; checkStatuses: boolean }) => api.post(QUEUE, v), all); +} +export function useAssignByPn() { + return useOperation((v: { pn: string; destId: number; shipmentMode: number }) => api.post(`${DEST}/assign-by-pn`, v), all); +} +export function useManualInput() { + return useOperation((v: { pn: string; orderId: number; orderDate: string; ltw: number; lgw: number }) => + api.post(`${DEST}/manual-input`, v), all); +} +export function useActivateOrders() { + return useOperation((selected: string[]) => api.post(`${DEST}/activation`, { selected }), [['grains.permits.activation']]); +} +export function useDistribute() { + return useOperation((category: string) => api.post(`${DIST}/distribute`, { category }), + [['grains.permits.distSummary'], ['grains.permits.distPivot'], ...all]); +} +export function useProcessOpen() { + return useOperation((v: { tn: string; cargoType: string | null; saveScrn: boolean }) => api.post(`${DIST}/process-open`, v), all); +} +export function useProcessOpenWithDestination() { + return useOperation((v: { pn: string; locations: number; orderDate: string; reservedQueue: boolean }) => + api.post(`${DIST}/process-open-with-destination`, v), all); +} +export function useSingleTruck() { + return useOperation((tn: string) => api.post(`${DIST}/single-truck?tn=${encodeURIComponent(tn)}`), all); +} +export function useRevokeAllRequested() { + return useOperation((scrnBelow: number) => api.post(`${DIST}/revoke-all-requested?scrnBelow=${scrnBelow}`), all); +} +export function useWeighbridgeManual() { + return useOperation((v: { tn: string; locationId: number; weightIn: number; weightOut: number }) => + api.post(`${WB}/manual`, v), []); +} +export function useWeights(kind: 'loading-weights' | 'discharge-weights') { + return useOperation((v: { tn: string; grossWeight: number; tareWeight: number }) => + api.post(`${WB}/${kind}`, v), []); +} +export function useWeighbridgeReading(kind: 'enter' | 'exit') { + const toast = useToast(); + return useWrite<{ tn: string; weight: number }, WeighbridgeResult>( + async (v) => { + const r = await api.post(`${WB}/${kind}`, v); + if (!r.success) toast.warning(r.message); + return r; + }, + { toastSuccess: false, invalidate: [['grains.permits.locCounts']] }, + ); +} diff --git a/web/src/features/grains-permits/meta/permits.tsx b/web/src/features/grains-permits/meta/permits.tsx new file mode 100644 index 0000000..894fb9f --- /dev/null +++ b/web/src/features/grains-permits/meta/permits.tsx @@ -0,0 +1,130 @@ +import type { FilterMeta, GridMeta, L10n, OptionItem, StatusMeta } from '@/components/meta/types'; +import { cargoOptions, companyFilterOptions, exitLocationOptions, tenderOrderDateOptions } from '../api'; +import type { PermitListItem, QueueItem } from '../types'; + +/** Declarative tables for the permit list (legacy GNPermits.cfm / getGNPermits) and the queue grid (queueGrid.cfm). */ + +/** PERMITS.SHIPMENTSTATUSCODE values of the Grains domain with the legacy captions. */ +export const permitStatuses: StatusMeta[] = [ + // Arabic captions are STATUS.DESCRIPTION (DOMAIN='GN') exactly as the legacy filter and grid show them. + { value: 'REQST', label: { en: 'Order distributed', ar: 'توزيع طلبية' }, color: 'info' }, + { value: 'PLND', label: { en: 'Confirmed', ar: 'تم التثبيت' }, color: 'primary' }, + { value: 'OPEN', label: { en: 'On the turn', ar: 'على الدور' }, color: 'default' }, + { value: 'ACCPT', label: { en: 'Ready for release', ar: 'جاهز للتسريب' }, color: 'secondary' }, + { value: 'RESD', label: { en: 'Released', ar: 'تم التسريب' }, color: 'warning' }, + { value: 'ACTRL', label: { en: 'On the road', ar: 'على الطريق' }, color: 'warning' }, + { value: 'CLRPR', label: { en: 'Exit allowed', ar: 'مسموح الخروج' }, color: 'info' }, + { value: 'ABSNC', label: { en: 'Absent', ar: 'عدم الحضور' }, color: 'default' }, + { value: 'INCOMP', label: { en: 'Incomplete', ar: 'غير مكتمل' }, color: 'default' }, + { value: 'CLOSE', label: { en: 'Completed', ar: 'مكتمل' }, color: 'success' }, + { value: 'RVKD', label: { en: 'Cancelled', ar: 'ملغي' }, color: 'error' }, +]; + +/** + * Status chips of the list = the legacy dropdown: every GN status except REGREQST, CLOSE and RVKD, ordered by caption; + * "ملغي" (RVKD) is offered only to the user GTOM1 (GNPermits.cfm). + */ +export const permitFilterStatuses = (showRevoked: boolean): StatusMeta[] => { + const hidden = new Set(['CLOSE', 'RVKD']); + const list = permitStatuses.filter((x) => !hidden.has(x.value)).sort((a, b) => a.label.ar.localeCompare(b.label.ar, 'ar')); + return showRevoked ? [...list, permitStatuses.find((x) => x.value === 'RVKD')!] : list; +}; + +export const shipmentModeOptions: OptionItem[] = [ + { value: 'PCKD', label: { en: 'Packed', ar: 'مشول' } }, + { value: 'BULK', label: { en: 'Bulk', ar: 'سائب' } }, +]; + +export interface PermitGridHandlers { + onAction: (action: string, row: PermitListItem) => void; +} + +const actionLabels: Record = { + view: { en: 'View', ar: 'مشاهدة' }, + submit: { en: 'Submit order', ar: 'تقديم الطلب' }, + edit: { en: 'Edit order', ar: 'تعديل الطلب' }, + accept: { en: 'Confirm turn', ar: 'تثبيت الدور' }, + reject: { en: 'Revoke confirmation', ar: 'الغاء التثبيت' }, + revokeAccepted: { en: 'Cancel confirmation', ar: 'الغاء التثبيت (جاهز للتسريب)' }, + convertToResd: { en: 'Convert to released', ar: 'تحويل الى تم التسريب' }, + phoneAccept: { en: 'Confirm by phone', ar: 'تأكيد هاتفي' }, + phoneReject: { en: 'Reject by phone', ar: 'رفض هاتفي' }, + cancelOrder: { en: 'Cancel the permit', ar: 'الغاء الإرسالية' }, + revokePermit: { en: 'Revoke the permit', ar: 'الغاء الإرسالية' }, + reactivate: { en: 'Re-activate', ar: 'تفعيل الارسالية' }, + print: { en: 'Print', ar: 'طباعة' }, +}; +export const actionLabel = (a: string): L10n => actionLabels[a] ?? { en: a, ar: a }; + +const danger = new Set(['cancelOrder', 'revokePermit', 'reject']); + +/** + * Same filters, labels and order as GNPermits.cfm: truck, permit, turn date, cargo class, [status chips], destination, + * company (not offered to company users), by order. Like getGNPermits, all conditions are AND. + */ +export const permitFilters = (companyUser: boolean): FilterMeta[] => [ + { name: 'tn', type: 'text', label: { en: 'Truck no.', ar: 'رقم القاطرة' }, inputKind: 'plate' }, + { name: 'pn', type: 'text', label: { en: 'Permit no.', ar: 'رقم الأرسالية' }, inputKind: 'code' }, + { name: 'creationDate', type: 'date', label: { en: 'Turn date', ar: 'تاريخ الدور' } }, + { name: 'shipmentMode', type: 'select', label: { en: 'Cargo class', ar: 'نوع المادة' }, options: shipmentModeOptions }, + { name: 'destAddressId', type: 'select', label: { en: 'Destination', ar: 'الوجهة' }, options: exitLocationOptions }, + ...(companyUser ? [] : [{ name: 'companyCode', type: 'select', label: { en: 'Company', ar: 'اسم الشركة' }, options: companyFilterOptions } as FilterMeta]), + { name: 'tenderOrder', type: 'select', label: { en: 'By order', ar: 'حسب الطلبية' }, options: tenderOrderDateOptions }, +]; + +export interface PermitGridOptions { + /** session.stkid = 62: sees only its own permits, no company filter, status defaults to REQST. */ + companyUser?: boolean; + /** Legacy offers the "ملغي" status only to the user GTOM1. */ + showRevoked?: boolean; +} + +export const permitGrid = (h: PermitGridHandlers, o: PermitGridOptions = {}): GridMeta => ({ + key: 'grains.permits', + endpoint: '/grains/permits', + rowKey: (r) => r.id, + // legacy: "يجب البحث اولا لتظهر لك الأرساليات" - the server returns nothing until a filter is given + requireFilter: true, + filters: permitFilters(!!o.companyUser), + status: { param: 'status', options: permitFilterStatuses(!!o.showRevoked), showAll: true }, + defaultFilters: o.companyUser ? { status: 'REQST' } : undefined, + onRowClick: (r) => h.onAction('view', r), + // Legacy GNPermits.cfm grid, read left to right: action column, status, destination, truck, driver, company, queue no., permit no. + visualLtr: true, + columns: [ + { key: 'shipmentStatusCode', header: { en: 'Status', ar: 'الحالة' }, format: 'status', statuses: permitStatuses }, + { key: 'destinationName', header: { en: 'Destination', ar: 'الوجهة' }, hideBelow: 'sm' }, + { key: 'tn', header: { en: 'Truck no.', ar: 'رقم القاطرة' }, ltr: true }, + { key: 'drvr', header: { en: 'Driver', ar: 'اسم السائق' }, hideBelow: 'md' }, + { key: 'compName', header: { en: 'Company', ar: 'اسم الشركة' }, hideBelow: 'sm' }, + { key: 'queueNo', header: { en: 'Queue', ar: 'الدور' }, ltr: true, hideBelow: 'lg' }, + { key: 'pn', header: { en: 'Permit', ar: 'الأرسالية' }, ltr: true }, + ], +}); + +/** Row actions are computed by the server (`actions`): only the allowed buttons are shown. */ +export const permitRowActions = (h: PermitGridHandlers): NonNullable['rowActions']> => + Object.keys(actionLabels).map((a) => ({ + key: a, + label: actionLabels[a]!, + danger: danger.has(a), + hidden: (r: PermitListItem) => !r.actions.includes(a), + onClick: (r: PermitListItem) => h.onAction(a, r), + })); + +export const queueGrid = (): GridMeta => ({ + key: 'grains.permits.queue', + endpoint: '/grains/permit-queue', + rowKey: (r) => r.id, + filters: [ + { name: 'tn', type: 'text', label: { en: 'Truck no.', ar: 'رقم القاطرة' }, inputKind: 'plate' }, + { name: 'pn', type: 'text', label: { en: 'Permit no.', ar: 'رقم الارسالية' }, inputKind: 'code' }, + ], + columns: [ + { key: 'pn', header: { en: 'Permit no.', ar: 'رقم الارسالية' }, ltr: true }, + { key: 'tn', header: { en: 'Truck', ar: 'القاطرة' }, ltr: true }, + { key: 'creationDate', header: { en: 'Created', ar: 'تاريخ الانشاء' }, format: 'datetime', ltr: true }, + ], +}); + +export { cargoOptions }; diff --git a/web/src/features/grains-permits/pages.tsx b/web/src/features/grains-permits/pages.tsx new file mode 100644 index 0000000..425bbdb --- /dev/null +++ b/web/src/features/grains-permits/pages.tsx @@ -0,0 +1,937 @@ +import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { + Alert, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, GlobalStyles, MenuItem, + Stack, Tab, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tabs, TextField, Typography, +} from '@mui/material'; +import AddIcon from '@mui/icons-material/Add'; +import PrintIcon from '@mui/icons-material/Print'; +import SearchIcon from '@mui/icons-material/Search'; +import { DataGrid } from '@/components/DataGrid'; +// the shared framed section look (see components/SectionPaper): every Paper on the permit screens uses it +import { SectionPaper as Paper } from '@/components/SectionPaper'; +import { ViewItem } from '@/components/ViewItem'; +import { EmptyState } from '@/components/EmptyState'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { PageHeader } from '@/components/PageHeader'; +import { StatusChip } from '@/components/StatusChip'; +import { formatNumber } from '@/components/meta/format'; +import { elementToPdfUrl, type PdfOrientation } from '@/lib/pdf'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { + fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, fetchTruck, searchDestination, searchTruckDistribution, + useAbsenceFeature, useActivateOrders, useActivation, useAddToQueue, useAssignByPn, useClosePermit, useDistribute, + useDistributionPivot, useDistributionSummary, useLocationCounts, useLocationGroups, useManualInput, useOrderDates, + usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination, + useRevokeAllRequested, useSingleTruck, useSubmitOrder, useToggleAbsence, useUpdateOrder, useWeighbridgeManual, + useWeighbridgeReading, useWeights, +} from './api'; +import { actionLabel, permitGrid, permitRowActions, permitStatuses, queueGrid, shipmentModeOptions } from './meta/permits'; +import strings from './strings'; +import { AcceptSlip, InSlip, OutSlip } from './slips'; +import type { PermitListItem, TruckDistribution } from './types'; + +/** Legacy role gates (src/NTP.Application/Grains/Permits/PermitSupport.cs GrainsRoles). */ +export const OPERATORS = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO']; +export const SUPERVISORS = ['SU', 'GPO', 'GNSU', 'GTO']; +export const WEIGHBRIDGE_ROLES = ['SU', 'GPO', 'GNSU', 'GNCO', 'GTO', 'GATEIN', 'GATEOUT', 'THRU']; + +const PHONE_REASONS: { value: string; en: string; ar: string }[] = [ + { value: 'لايمكن الاتصال به', en: 'Cannot be reached', ar: 'لايمكن الاتصال به' }, + { value: 'رقم الهاتف غير صحيح', en: 'Wrong phone number', ar: 'رقم الهاتف غير صحيح' }, + { value: 'الهاتف مغلق', en: 'Phone switched off', ar: 'الهاتف مغلق' }, + { value: 'قائمة الانتظار', en: 'Waiting list', ar: 'قائمة الانتظار' }, + { value: 'لايرد', en: 'No answer', ar: 'لايرد' }, + { value: 'غير موافق', en: 'Does not agree', ar: 'غير موافق' }, + { value: 'عدم الحضور بعد التسريب', en: 'Absent after release', ar: 'عدم الحضور بعد التسريب' }, + { value: 'عدم الحضور بعد التوزيع', en: 'Absent after distribution', ar: 'عدم الحضور بعد التوزيع' }, + { value: 'تجاوز عدد الإستنكافات المسموح بها', en: 'Exceeded the allowed absences', ar: 'تجاوز عدد الإستنكافات المسموح بها' }, +]; +const EXPIRY_DAYS = [1, 2, 3, 4, 5, 14, 30]; +const FIELD_SX = { width: '100%' } as const; + +function useRoles() { + // Backend-driven (GET /auth/permissions): the role code decides on the server, not here. + const { hasRole, can } = useAuth(); + return { + canQueueAdd: can('grains.permits.queue'), + canAbsence: can('grains.permits.absence'), + canClose: can('grains.permits.close'), + canTruckOrder: can('grains.permits.truckOrder'), + canTruckStatus: can('grains.permits.truckStatus'), + isSu: hasRole(['SU']), + }; +} + +/** Locale-aware number formatting in the current UI language. */ +function useFmt() { + const { lang } = useFeatureUi(strings); + return (n: unknown) => formatNumber(n, lang); +} + +const digits = (v: string) => v.replace(/[^0-9]/g, ''); +const ltr = { htmlInput: { dir: 'ltr' as const } }; + +/** Small "type a number, press Enter" field used all over the legacy forms. */ +function NumberField(props: { label: string; value: string; onChange: (v: string) => void; onEnter?: () => void; autoFocus?: boolean }) { + return ( + props.onChange(digits(e.target.value))} + onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); props.onEnter?.(); } }} + slotProps={{ htmlInput: { inputMode: 'numeric', dir: 'ltr' } }} + /> + ); +} + +// ================================================================= reason dialog (cancel / revoke / phone reject) +interface ReasonDialogProps { + open: boolean; + title: string; + withExpiry?: boolean; + free?: boolean; + onClose: () => void; + onSubmit: (reason: string, days: number) => void; +} + +function ReasonDialog({ open, title, withExpiry, free, onClose, onSubmit }: ReasonDialogProps) { + const { t, lang } = useFeatureUi(strings); + const [reason, setReason] = useState(''); + const [days, setDays] = useState(1); + return ( + + {title} + + + {free ? ( + setReason(e.target.value)} /> + ) : ( + setReason(e.target.value)}> + {PHONE_REASONS.map((r) => {lang === 'ar' ? r.ar : r.en})} + + )} + {withExpiry && ( + setDays(Number(e.target.value))}> + {EXPIRY_DAYS.map((d) => {d})} + + )} + + + + + + + + ); +} + +/** Shared state machine of the row/detail actions of a permit. */ +function usePermitActions() { + const { t, tr } = useFeatureUi(strings); + const navigate = useNavigate(); + const confirm = useConfirm(); + const accept = usePermitAction('accept'); + const revoke = usePermitAction('revoke'); + const revokeAccepted = usePermitAction('revoke-accepted'); + const convert = usePermitAction('convert-to-resd'); + const reactivate = usePermitAction('reactivate'); + const cancelOrder = usePermitAction('cancel-order'); + const revokePermit = usePermitAction('revoke-permit'); + const phoneAccept = usePermitAction('phone-accept'); + const phoneReject = usePermitAction('phone-reject'); + const [dialog, setDialog] = useState<{ kind: 'cancelOrder' | 'revokePermit' | 'phoneReject'; id: number } | null>(null); + + async function run(action: string, id: number, status: string | null) { + const ask = async (key: Parameters[0], danger = false) => confirm({ message: t(key), danger }); + switch (action) { + case 'view': navigate(`/grains/permits/${id}`); break; + case 'submit': case 'edit': navigate(`/grains/permits/${id}`); break; + case 'accept': if (await ask('pm.confirm.accept')) accept.mutate({ id }); break; + case 'reject': if (await ask('pm.confirm.revoke', true)) revoke.mutate({ id }); break; + case 'revokeAccepted': if (await ask('pm.confirm.revokeAccepted', true)) revokeAccepted.mutate({ id }); break; + case 'convertToResd': if (await ask('pm.confirm.convert')) convert.mutate({ id }); break; + case 'reactivate': if (await ask('pm.confirm.reactivate')) reactivate.mutate({ id }); break; + case 'phoneAccept': if (await ask('pm.confirm.phoneAccept')) phoneAccept.mutate({ id, body: {} }); break; + case 'phoneReject': case 'cancelOrder': case 'revokePermit': setDialog({ kind: action, id }); break; + case 'print': { + // legacy: openWindow(printIn / printOut / acceptPrint .cfm) = a PDF in a new window. Must run synchronously inside the click. + const kind = status === 'CLOSE' || status === 'ACTRL' || status === 'CLRPR' ? 'in' : 'accept'; + window.open(`/grains/permits/${id}/print/${kind}?pdf=1`, '_blank'); + break; + } + default: break; + } + } + + const element = dialog && ( + setDialog(null)} + onSubmit={(reason, days) => { + const { id, kind } = dialog; + setDialog(null); + if (kind === 'cancelOrder') cancelOrder.mutate({ id, body: { reason } }); + else if (kind === 'revokePermit') revokePermit.mutate({ id, body: { reason } }); + else phoneReject.mutate({ id, body: { reason, expiryDays: days } }); + }} + /> + ); + return { run, element }; +} + +// ================================================================= permit list (GNPermits.cfm) +export function PermitsPage() { + const { t } = useFeatureUi(strings); + const { user } = useAuth(); + const { run, element } = usePermitActions(); + const companyUser = Number(user?.stkId) === 62; // legacy session.stkid = 62 + const showRevoked = String(user?.userId ?? '').toUpperCase() === 'GTOM1'; // legacy: only this login sees "ملغي" + const meta = useMemo(() => { + const h = { onAction: (a: string, r: PermitListItem) => void run(a, r.id, r.shipmentStatusCode) }; + return { ...permitGrid(h, { companyUser, showRevoked }), rowActions: permitRowActions(h) }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [companyUser, showRevoked]); + return ( + <> + + + {element} + + ); +} + +// ================================================================= permit details + order form (createGnOrder.cfm, viewPermitDetails.cfm) +interface OrderValues { tn: string; trn: string; nnpn: string; name: string; dln: string; dled: string; opType: string } +const emptyOrder: OrderValues = { tn: '', trn: '', nnpn: '', name: '', dln: '', dled: '', opType: 'IMPT' }; + +export function PermitDetailPage() { + const fmt = useFmt(); + const { t, tr, lang } = useFeatureUi(strings); + const { id: idParam } = useParams(); + const id = Number(idParam); + const detail = usePermitDetail(id); + const { run, element } = usePermitActions(); + const submit = useSubmitOrder(); + const update = useUpdateOrder(); + const confirm = useConfirm(); + const toast = useToast(); + const [v, setV] = useState(emptyOrder); + const [info, setInfo] = useState<{ truck?: string; trailer?: string }>({}); + const [loaded, setLoaded] = useState(false); + + const d = detail.data; + if (d && !loaded) { + setLoaded(true); + setV({ + tn: d.truck?.tn ?? '', trn: d.trailer?.tn ?? '', nnpn: d.driver?.nnpn ?? '', name: d.driver?.name ?? '', dln: d.driver?.dln ?? '', + dled: d.driver?.dled ?? '', opType: d.operationTypeCode ?? 'IMPT', + }); + } + if (detail.isLoading) return ; + if (!d) return ; + + const canSubmit = d.actions.includes('submit'); + const canEdit = d.actions.includes('edit'); + const editable = canSubmit || canEdit; + const set = (k: keyof OrderValues) => (e: { target: { value: string } }) => setV((p) => ({ ...p, [k]: e.target.value })); + + async function lookupTruck() { + if (!v.tn) return; + try { + const r = await fetchTruck(v.tn.trim()); + setInfo((p) => ({ ...p, truck: r ? `${r.chasesNumber ?? ''} ${r.axials ?? ''}`.trim() : t('pm.order.notRegistered') })); + } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } + } + async function lookupTrailer() { + if (!v.trn) return; + try { + const r = await fetchTrailer(v.trn.trim()); + setInfo((p) => ({ ...p, trailer: r ? `${r.chasesNumber ?? ''} ${r.axials ?? ''}`.trim() : t('pm.order.notRegistered') })); + } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } + } + async function lookupDriver() { + if (!v.nnpn) return; + try { + const r = await fetchDriver(v.nnpn.trim()); + if (r) setV((p) => ({ ...p, name: r.name ?? '', dln: r.dln ?? '', dled: r.dled ?? '' })); + else toast.warning(t('pm.order.driverMissing')); + } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } + } + + const complete = !!(v.tn && v.trn && v.nnpn && v.name && v.dln && (canEdit && !canSubmit ? true : v.opType)); + async function save() { + if (!complete || !(await confirm({ message: t(canSubmit ? 'pm.confirm.submit' : 'pm.confirm.update') }))) return; + const body = { tn: v.tn.trim(), trn: v.trn.trim(), nnpn: v.nnpn.trim(), dln: v.dln.trim(), dled: v.dled || null, name: v.name.trim() }; + if (canSubmit) submit.mutate({ id, body: { ...body, opType: v.opType } }); + else update.mutate({ id, body }); + } + + const others = d.actions.filter((a) => !['view', 'submit', 'edit'].includes(a)); + return ( + <> + + + + + + {d.queueNo} + {d.cargoType} + {d.shift} + {d.operationType} + {[d.truck?.tn, d.truck?.chasesNumber, d.truck?.axials].filter(Boolean).join(' / ')} + {[d.trailer?.tn, d.trailer?.chasesNumber, d.trailer?.axials].filter(Boolean).join(' / ')} + {[d.driver?.name, d.driver?.dln].filter(Boolean).join(' / ')} + + {others.length > 0 && ( + + {others.map((a) => ( + + ))} + + )} + + + {editable && ( + + {t(canSubmit ? 'pm.order.submitTitle' : 'pm.order.editTitle')} + + void lookupTruck()} + helperText={info.truck} slotProps={ltr} /> + void lookupTrailer()} + helperText={info.trailer} slotProps={ltr} /> + void lookupDriver()} slotProps={ltr} /> + + + + {canSubmit && ( + + {lang === 'ar' ? 'محمل' : 'Loaded'} + {lang === 'ar' ? 'فارغ' : 'Empty'} + + )} + + + + + + )} + + + {t('pm.events.title')} + + + + + {t('pm.events.date')} + {t('pm.events.type')} + {t('pm.events.by')} + {t('pm.events.status')} + {t('pm.events.weight')} + {t('pm.events.remarks')} + + + + {d.events.map((e, i) => ( + + {e.eventDate ? new Date(e.eventDate).toLocaleString('en-GB') : ''} + {e.eventCaption ?? e.eventType} + {e.doneBy} + {e.currentStatus} + {e.weight === null ? '' : fmt(e.weight)} + {e.remarks} + + ))} + {d.events.length === 0 && {tr({ en: 'No events', ar: 'لا توجد احداث' })}} + +
+
+
+
+ {element} + + ); +} + +function Info({ label, children, ltr: isLtr }: { label: string; children?: ReactNode; ltr?: boolean }) { + return ( + + {children ? (isLtr ? {children} : children) : null} + + ); +} + +// ================================================================= queue (CreateQueue.cfm / queueGrid.cfm) +export function QueuePage() { + const { t, lang } = useFeatureUi(strings); + const { canQueueAdd } = useRoles(); + const add = useAddToQueue(); + const confirm = useConfirm(); + const meta = useMemo(() => queueGrid(), []); + const [open, setOpen] = useState(false); + const [tn, setTn] = useState(''); + const [tt, setTt] = useState('BULK'); + + async function save() { + if (!tn.trim() || !(await confirm({ message: t('pm.queue.confirm') }))) return; + add.mutate({ tn: tn.trim(), tt, checkStatuses: false }, { onSuccess: (r) => { if (r.success) { setOpen(false); setTn(''); } } }); + } + return ( + <> + } onClick={() => setOpen(true)}>{t('pm.queue.add')}} + /> + + setOpen(false)} fullWidth maxWidth="xs"> + {t('pm.queue.add')} + + + void save()} /> + setTt(e.target.value)}> + {shipmentModeOptions.map((o) => {typeof o.label === 'string' ? o.label : o.label[lang]})} + + + + + + + + + + ); +} + +// ================================================================= destinations (assginggdest / ManualInput / activateOrders) +function AssignByPn() { + const { t, lang } = useFeatureUi(strings); + const groups = useLocationGroups(); + const assign = useAssignByPn(); + const confirm = useConfirm(); + const [pn, setPn] = useState(''); + const [dest, setDest] = useState(''); + const [mode, setMode] = useState(''); + const cargo = [{ id: 38, ar: 'قمح سائب', en: 'Wheat bulk' }, { id: 39, ar: 'شعير سائب', en: 'Barley bulk' }, { id: 40, ar: 'قمح مشول', en: 'Wheat packed' }, { id: 41, ar: 'شعير مشول', en: 'Barley packed' }]; + const locations = [...(groups.data?.packed ?? []), ...(groups.data?.bulk ?? []), ...(groups.data?.bulkGallab ?? [])]; + async function save() { + if (!pn || !dest || !mode || !(await confirm({ message: t('pm.dest.confirm') }))) return; + assign.mutate({ pn, destId: Number(dest), shipmentMode: Number(mode) }); + } + return ( + + + setDest(e.target.value)}> + {locations.map((l) => {l.name})} + + setMode(e.target.value)}> + {cargo.map((c) => {lang === 'ar' ? c.ar : c.en})} + + + + ); +} + +function ManualInput() { + const { t } = useFeatureUi(strings); + const dates = useOrderDates(); + const manual = useManualInput(); + const confirm = useConfirm(); + const toast = useToast(); + const [pn, setPn] = useState(''); + const [date, setDate] = useState(''); + const [orders, setOrders] = useState<{ orderId: number; name: string | null }[]>([]); + const [orderId, setOrderId] = useState(''); + const [ltw, setLtw] = useState(''); + const [lgw, setLgw] = useState(''); + + async function loadOrders(d: string) { + setDate(d); setOrderId(''); + if (!pn || !d) return; + try { + const rows = await fetchAllowedDestinations(pn, d); + setOrders(rows.filter((r) => r.orderId > 0)); + } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } + } + async function loadAlt() { + if (!pn || !date) return; + try { setOrders((await fetchOrdersForPermit(pn, date)).map((o) => ({ orderId: o.id, name: o.destName }))); } catch { /* shown by the client */ } + } + const valid = pn && date && orderId && ltw && lgw; + async function save() { + if (!valid || !(await confirm({ message: t('pm.manual.confirm') }))) return; + manual.mutate({ pn, orderId: Number(orderId), orderDate: date, ltw: Number(ltw), lgw: Number(lgw) }); + } + return ( + + + void loadOrders(e.target.value)}> + {(dates.data ?? []).map((d) => {d.split('-').reverse().join('/')})} + + setOrderId(e.target.value)} + helperText={orders.length === 0 && date ? t('pm.manual.noOrders') : undefined}> + {orders.map((o) => {o.name})} + + + + + + + + + ); +} + +function Activation() { + const fmt = useFmt(); + const { t } = useFeatureUi(strings); + const q = useActivation(); + const activate = useActivateOrders(); + const confirm = useConfirm(); + const [checked, setChecked] = useState | null>(null); + if (q.isLoading) return ; + const rows = q.data ?? []; + const sel = checked ?? new Set(rows.filter((r) => r.statusCode === 'ACTIVE').map((r) => `${r.locId}-${r.ctId}`)); + const toggle = (k: string) => { const n = new Set(sel); if (n.has(k)) n.delete(k); else n.add(k); setChecked(n); }; + async function save() { if (await confirm({ message: t('pm.activate.confirm') })) activate.mutate([...sel], { onSuccess: () => setChecked(null) }); } + return ( + + + + {t('pm.activate.loc')}{t('pm.activate.cargo')} + {t('pm.activate.total')}{t('pm.activate.used')} + + {rows.map((r) => { + const k = `${r.locId}-${r.ctId}`; + return ( + + toggle(k)} /> + {r.loc}{r.ct} + {fmt(r.total)}{fmt(r.used)} + + ); + })} + +
+
+ +
+ ); +} + +// Three separate screens (each with its own menu entry and permission key), previously tabs of one page. +export function DestinationsPage() { + const { t } = useFeatureUi(strings); + return ( + <> + + + + ); +} + +export function ManualInputPage() { + const { t } = useFeatureUi(strings); + return ( + <> + + + + ); +} + +export function ActivationPage() { + const { t } = useFeatureUi(strings); + return ( + <> + + + + ); +} + +// ================================================================= distribution +function DistributeTab() { + const fmt = useFmt(); + const { t, lang } = useFeatureUi(strings); + const distribute = useDistribute(); + const confirm = useConfirm(); + const cats = [ + { v: 'PCKD', en: 'Packed', ar: 'مشول' }, { v: 'BULK_AHALE', en: 'Bulk - individuals', ar: 'سائب - أفراد' }, + { v: 'BULK_COMP', en: 'Bulk - companies', ar: 'سائب - شركات' }, { v: 'BULK_GALLAB_AHALE', en: 'Tipper bulk - individuals', ar: 'قلاب - أفراد' }, + { v: 'BULK_GALLAB_COMP', en: 'Tipper bulk - companies', ar: 'قلاب - شركات' }, + ]; + const [cat, setCat] = useState('PCKD'); + const summary = useDistributionSummary(); + const pivot = useDistributionPivot(); + async function go() { if (await confirm({ message: t('pm.dist.confirm') })) distribute.mutate(cat); } + return ( + + + setCat(e.target.value)}> + {cats.map((c) => {lang === 'ar' ? c.ar : c.en})} + + + + + + {t('pm.dist.summary')} + + {t('pm.dist.company')}{t('pm.dist.count')} + {(summary.data ?? []).map((r) => {r.comp}{fmt(r.cnt)})} +
+
+ + {t('pm.dist.pivot')} + + {t('pm.dist.company')}{t('pm.dist.silos')} + {t('pm.dist.direct')}{t('pm.dist.packed')} + {(pivot.data ?? []).map((r) => ( + {r.company}{r.silos} + {r.direct}{r.packed} + ))} +
+
+
+
+ ); +} + +function ProcessTab() { + const { t } = useFeatureUi(strings); + const open = useProcessOpen(); + const single = useSingleTruck(); + const withDest = useProcessOpenWithDestination(); + const revokeAll = useRevokeAllRequested(); + const { isSu } = useRoles(); + const confirm = useConfirm(); + const [tn, setTn] = useState(''); + const [pn, setPn] = useState(''); + const [orderId, setOrderId] = useState(''); + const [date, setDate] = useState(''); + const [limit, setLimit] = useState(''); + return ( + + + + {t('pm.proc.byTruck')} + + + + + + + + + + {t('pm.proc.withDest')} + + + setDate(e.target.value)} slotProps={{ inputLabel: { shrink: true } }} /> + + + + {isSu && ( + + + {t('pm.proc.revokeAll')} + + + + + )} + + ); +} + +function SearchTruckTab() { + const { t } = useFeatureUi(strings); + const toast = useToast(); + const [tn, setTn] = useState(''); + const [r, setR] = useState(null); + async function go() { + if (!tn) return; + try { setR(await searchTruckDistribution(tn)); } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } + } + return ( + + + void go()} /> + + + {r && ( + + + {r.status} + {r.companyLocations} + {r.order} + {`${r.trucksTotalQuantity} / ${r.tenderTotalQuantity}`} + {r.errorMsg && {r.errorMsg}} + + + )} + + ); +} + +export function DistributionPage() { + const { t } = useFeatureUi(strings); + const [tab, setTab] = useState<'distribute' | 'process' | 'search'>('distribute'); + const absence = useAbsenceFeature(); + const toggle = useToggleAbsence(); + const confirm = useConfirm(); + const { canAbsence, canTruckOrder, canTruckStatus } = useRoles(); + return ( + <> + { if (await confirm({ message: t('pm.absence.confirm') })) toggle.mutate(undefined as never); }}> + {absence.data?.enabled ? t('pm.absence.disable') : t('pm.absence.enable')} + + )} + /> + setTab(v)} variant="scrollable" sx={{ mb: 2 }}> + + {canTruckOrder && } + {canTruckStatus && } + + {tab === 'distribute' && } + {tab === 'process' && canTruckOrder && } + {tab === 'search' && canTruckStatus && } + + ); +} + +// ================================================================= weighbridges +function ReadingTab({ kind }: { kind: 'enter' | 'exit' }) { + const { t } = useFeatureUi(strings); + const call = useWeighbridgeReading(kind); + const toast = useToast(); + const [tn, setTn] = useState(''); + const [w, setW] = useState(''); + async function go() { + if (!tn || !w) return; + call.mutate({ tn, weight: Number(w) }, { onSuccess: (r) => { if (r.success) { toast.success(r.message); setW(''); } } }); + } + return ( + + + void go()} /> + + + ); +} + +function WeightsTab({ kind }: { kind: 'loading-weights' | 'discharge-weights' }) { + const { t } = useFeatureUi(strings); + const save = useWeights(kind); + const [tn, setTn] = useState(''); + const [tare, setTare] = useState(''); + const [gross, setGross] = useState(''); + return ( + + + + + + + ); +} + +function ManualTab() { + const { t } = useFeatureUi(strings); + const save = useWeighbridgeManual(); + const toast = useToast(); + const { user } = useAuth(); + const [tn, setTn] = useState(''); + const [loc, setLoc] = useState(user?.locationId ? String(user.locationId) : ''); + const [wi, setWi] = useState(''); + const [wo, setWo] = useState(''); + const [dest, setDest] = useState(''); + async function find() { + if (!tn) return; + try { const r = await searchDestination(tn); setDest(r.destination ? `${r.destination}${r.message ? ` - ${r.message}` : ''}` : r.message ?? ''); } + catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } + } + return ( + + void find()} /> + {dest && {dest}} + + + + + + + + + ); +} + +function CountsTab() { + const fmt = useFmt(); + const { t } = useFeatureUi(strings); + const q = useLocationCounts(); + if (q.isLoading) return ; + return ( + + + {t('pm.wb.loc')}{t('pm.wb.trucks')} + {(q.data ?? []).map((r, i) => {r.loc}{fmt(r.cnt)})} +
+
+ ); +} + +export function WeighbridgePage() { + const { t } = useFeatureUi(strings); + const { canClose } = useRoles(); + const [tab, setTab] = useState(0); + const closeP = useClosePermit(); + const confirm = useConfirm(); + const [pn, setPn] = useState(''); + return ( + <> + + setTab(v)} variant="scrollable" sx={{ mb: 2 }}> + + {canClose && } + + {tab === 0 && } + {tab === 1 && } + {tab === 2 && } + {tab === 3 && } + {tab === 4 && } + {tab === 5 && } + {tab === 6 && canClose && ( + + + + + )} + + ); +} + +// ================================================================= print pages (acceptPrint / printIn / printOut) +const printStyles = ( + +); + +/** + * Print sheet. With `?pdf=1` (opened by the Print action in a new tab) it renders the sheet to an A5 PDF (portrait for the + * acceptance slip, landscape for the in/out slips, like legacy cfdocument) and replaces this tab with the PDF. + * Without it the sheet is shown with a Print button (browser print dialog). + */ +function PrintShell({ title, children, loading, error, orientation, bare, width = 640 }: { + title: string; children: ReactNode; loading: boolean; error: boolean; orientation: PdfOrientation; bare?: boolean; width?: number; +}) { + const { t } = useFeatureUi(strings); + const [sp] = useSearchParams(); + const wantsPdf = sp.get('pdf') === '1'; + const sheet = useRef(null); + const [pdfFailed, setPdfFailed] = useState(false); + const [pdfUrl, setPdfUrl] = useState(null); + + useEffect(() => { + if (!wantsPdf || loading || error || pdfFailed || pdfUrl || !sheet.current) return; + let cancelled = false; + // short timer (not requestAnimationFrame, which does not run in a background tab) so the sheet is laid out first + const id = window.setTimeout(() => { + elementToPdfUrl(sheet.current!, orientation).then( + (url) => { + if (cancelled) return; + setPdfUrl(url); // full-screen frame below: works even where top-level blob navigation is blocked + window.location.replace(url); // normal browsers: this tab becomes the PDF itself + }, + () => { if (!cancelled) setPdfFailed(true); }, + ); + }, 80); + return () => { cancelled = true; window.clearTimeout(id); }; + }, [wantsPdf, loading, error, pdfFailed, pdfUrl, orientation]); + + if (loading) return ; + if (error) return {t('pm.print.failed')}; + return ( + <> + {printStyles} + {pdfUrl && ( + + )} + {wantsPdf && !pdfFailed && !pdfUrl && {t('pm.print.generating')}} + {pdfFailed && {t('pm.print.pdfFailed')}} + + + + {bare ? ( + // data-pdf-literal: designed black on white, captured exactly as laid out (no theme neutralising) + {children} + ) : ( + + {title} + {children} + + )} + + ); +} + +export function PrintAcceptPage() { + const { t } = useFeatureUi(strings); + const id = Number(useParams().id); + const q = usePrintAccept(id); + const d = q.data; + return ( + + {d && } + + ); +} + +export function PrintInPage() { + const { t } = useFeatureUi(strings); + const id = Number(useParams().id); + const q = usePrintIn(id); + const d = q.data; + return ( + + {d && } + + ); +} + +export function PrintOutPage() { + const { t } = useFeatureUi(strings); + const id = Number(useParams().id); + const q = usePrintOut(id); + const d = q.data; + return ( + + {d && } + + ); +} + diff --git a/web/src/features/grains-permits/routes.tsx b/web/src/features/grains-permits/routes.tsx new file mode 100644 index 0000000..a7cd966 --- /dev/null +++ b/web/src/features/grains-permits/routes.tsx @@ -0,0 +1,46 @@ +import type { RouteObject } from 'react-router-dom'; +import AltRouteIcon from '@mui/icons-material/AltRoute'; +import EditNoteIcon from '@mui/icons-material/EditNote'; +import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck'; +import AssignmentIcon from '@mui/icons-material/Assignment'; +import LocalShippingIcon from '@mui/icons-material/LocalShipping'; +import ScaleIcon from '@mui/icons-material/Scale'; +import SortIcon from '@mui/icons-material/Sort'; +import TuneIcon from '@mui/icons-material/Tune'; +import type { MenuItem } from '@/shell/types'; +import { + ActivationPage, DestinationsPage, DistributionPage, ManualInputPage, PermitDetailPage, PermitsPage, PrintAcceptPage, PrintInPage, PrintOutPage, QueuePage, WeighbridgePage, +} from './pages'; +import strings from './strings'; + +/** Grains "permits" slice: permit list / order form / queue / destinations / distribution / weighbridges / print pages. */ +export const routes: RouteObject[] = [ + { path: '/grains/permits', element: }, + { path: '/grains/permits/queue', element: }, + { path: '/grains/permits/destinations', element: }, + { path: '/grains/permits/manual-input', element: }, + { path: '/grains/permits/activation', element: }, + { path: '/grains/permits/distribution', element: }, + { path: '/grains/permits/weighbridge', element: }, + { path: '/grains/permits/:id', element: , handle: { crumb: strings['pm.crumb.view'] } }, + { path: '/grains/permits/:id/print/accept', element: , handle: { crumb: strings['pm.crumb.print'] } }, + { path: '/grains/permits/:id/print/in', element: , handle: { crumb: strings['pm.crumb.print'] } }, + { path: '/grains/permits/:id/print/out', element: , handle: { crumb: strings['pm.crumb.print'] } }, +]; + +export const menu: MenuItem[] = [ + { + key: 'grains.permits', + title: strings['pm.menu.group'], + icon: AssignmentIcon, + children: [ + { key: 'grains.permits.list', title: strings['pm.menu.permits'], icon: LocalShippingIcon, path: '/grains/permits' }, + { key: 'grains.permits.queue', title: strings['pm.menu.queue'], icon: SortIcon, path: '/grains/permits/queue' }, + { key: 'grains.permits.destinations', title: strings['pm.menu.destinations'], icon: AltRouteIcon, path: '/grains/permits/destinations' }, + { key: 'grains.permits.manualEntry', title: strings['pm.menu.manualInput'], icon: EditNoteIcon, path: '/grains/permits/manual-input' }, + { key: 'grains.permits.activation', title: strings['pm.menu.activation'], icon: PlaylistAddCheckIcon, path: '/grains/permits/activation' }, + { key: 'grains.permits.distribution', title: strings['pm.menu.distribution'], icon: TuneIcon, path: '/grains/permits/distribution' }, + { key: 'grains.permits.weighbridge', title: strings['pm.menu.weighbridge'], icon: ScaleIcon, path: '/grains/permits/weighbridge' }, + ], + }, +]; diff --git a/web/src/features/grains-permits/slips.tsx b/web/src/features/grains-permits/slips.tsx new file mode 100644 index 0000000..68da7bf --- /dev/null +++ b/web/src/features/grains-permits/slips.tsx @@ -0,0 +1,205 @@ +import type { ReactNode } from 'react'; +import { Box } from '@mui/material'; +import { Barcode } from '@/components/Barcode'; +import { Logo } from '@/components/Logo'; +import { useFeatureUi } from '@/i18n/useUi'; +import strings from './strings'; +import type { AcceptPrint, PrintIn, PrintOut } from './types'; + +/** + * The three printed slips of a permit, laid out like the legacy cfdocument PDFs (acceptPrint.cfm, printIn.cfm, printOut.cfm): + * logo, title over a rule, data block, [weights table], stamps / signatures. Always black on white; they are captured to an + * A5 PDF as designed (the sheet carries data-pdf-literal, see lib/pdf.ts). + */ +const SLIP_FONT = 'Arial, Tahoma, "Segoe UI", sans-serif'; +const p2 = (n: number) => String(n).padStart(2, '0'); +const today = () => { const d = new Date(); return `${d.getFullYear()}/${p2(d.getMonth() + 1)}/${p2(d.getDate())}`; }; + +function BlankLine({ width = 190 }: { width?: number }) { + return ; +} + +/** Logo (start side), title centred over a thick rule, then the slip body. */ +function SlipSheet({ title, children, compact }: { title: string; children: ReactNode; compact?: boolean }) { + const { lang } = useFeatureUi(strings); + return ( + + + + {title} + + {children} + + ); +} + +/** Label / value rows. `pairs` = how many label+value pairs per line. */ +function SlipInfo({ rows, pairs = 1, mt = 3 }: { rows: [string, ReactNode][]; pairs?: 1 | 2; mt?: number }) { + return ( + + {rows.map(([label, value], i) => ( + + {label} + {label ? (value || '-') : ''} + + ))} + + ); +} + +/** Bordered weights table. Legacy tables are left-to-right even on Arabic pages. */ +function SlipTable({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +/** Note, officer, acknowledgement and signature lines, then the "not official without the company stamp" footer. */ +function SlipNotes({ doneBy }: { doneBy?: string | null }) { + const { t } = useFeatureUi(strings); + return ( + <> + + {t('pm.slip.note')} + + {t('pm.slip.officer')} {doneBy ?? ''} + {t('pm.slip.ack')} + {t('pm.slip.officerSign')} + {t('pm.slip.driverSign')} + + + {t('pm.slip.footer')} + + ); +} + +// ------------------------------------------------------------------------------------------------ accept (acceptPrint.cfm) +export function AcceptSlip({ d }: { d: AcceptPrint }) { + const { t } = useFeatureUi(strings); + const now = new Date(); + const printedAt = `${p2(now.getHours())}:${p2(now.getMinutes())}:${p2(now.getSeconds())} ${today()}`; + const rows: [string, ReactNode][] = [ + [t('pm.slip.permit'), ], + [t('pm.slip.company'), d.compName], + [t('pm.slip.truck'), d.tn], + [t('pm.slip.trailer'), d.trn], + ...(d.operationType ? ([[t('pm.slip.operation'), d.operationType]] as [string, ReactNode][]) : []), + [t('pm.slip.driver'), d.drvr], + [t('pm.slip.cargoShift'), d.cargoType ? `${d.cargoType}/${d.shift ?? ''}` : ], + [t('pm.slip.loading'), d.hasOrder ? d.location : ], + [t('pm.slip.destination'), d.hasOrder ? d.destination : ], + [t('pm.slip.moit'), ], + [t('pm.slip.nextPn'), d.nextPn], + [t('pm.slip.printedAt'), printedAt], + ]; + return ( + + + {/* legacy table is left-to-right: loading stamp on the left, unloading on the right, in both languages */} + + {[t('pm.slip.stampLoading'), t('pm.slip.stampUnloading')].map((label) => ( + + {label} + + + ))} + + + ); +} + +// ------------------------------------------------------------------------------------------------ entry (printIn.cfm) +export function InSlip({ d }: { d: PrintIn }) { + const { t } = useFeatureUi(strings); + const h = d.header; + return ( + + + + + + {t('pm.slip.weightByCenter')} + {t('pm.slip.weightReceived')} + {t('pm.slip.cargoType')} + {t('pm.slip.receivingCenter')} + + + {t('pm.slip.ton')}{t('pm.slip.kilo')} + {t('pm.slip.ton')}{t('pm.slip.kilo')} + + + + + + + + {d.loading.ton}{d.loading.kilo}{t('pm.slip.netSent')} + {d.discharge.ton}{d.discharge.kilo}{t('pm.slip.netReceived')} + {d.tonDifference}{d.kiloDifference}{t('pm.slip.difference')} {d.sign} + + + + {d.discharge.ton} + {d.discharge.kilo} + {h.shipmentMode ?? ''} + {h.destination ?? ''} + + + + + + ); +} + +// ------------------------------------------------------------------------------------------------ loading / exit (printOut.cfm) +export function OutSlip({ d }: { d: PrintOut }) { + const { t } = useFeatureUi(strings); + const h = d.header; + return ( + + + + + + {t('pm.slip.netWeight')} + {t('pm.slip.sendingCenter')} + {t('pm.slip.cargoType')} + + {t('pm.slip.ton')}{t('pm.slip.kilo')} + + + {d.ton}{d.kilo}{d.location ?? ''}{h.shipmentMode ?? ''} + + + + + ); +} diff --git a/web/src/features/grains-permits/strings.ts b/web/src/features/grains-permits/strings.ts new file mode 100644 index 0000000..4605af9 --- /dev/null +++ b/web/src/features/grains-permits/strings.ts @@ -0,0 +1,217 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** Feature strings of the Grains "permits" slice (permit list, order form, queue, destinations, distribution, weighbridges, print). */ +export default defineStrings({ + // ---- menu + 'pm.menu.group': { en: 'Permits and distribution', ar: 'الارساليات والتوزيع' }, + 'pm.menu.permits': { en: 'Grain permits', ar: 'ارساليات التموين' }, + 'pm.menu.queue': { en: 'Turns (queue)', ar: 'الأدوار' }, + 'pm.menu.destinations': { en: 'Destinations', ar: 'تحديد الوجهات' }, + 'pm.menu.distribution': { en: 'Distribution', ar: 'توزيع الطلبيات' }, + 'pm.menu.weighbridge': { en: 'Weighbridges', ar: 'القبّان' }, + 'pm.crumb.print': { en: 'Print', ar: 'طباعة' }, + 'pm.crumb.view': { en: 'Permit', ar: 'الارسالية' }, + + // ---- shared + 'pm.forbidden': { en: 'You are not allowed to use this page.', ar: 'غير مصرح لك باستخدام هذه الصفحة.' }, + 'pm.loading': { en: 'Loading...', ar: 'جاري التحميل...' }, + 'pm.notFound': { en: 'Permit not found', ar: 'الارسالية غير موجودة' }, + 'pm.back': { en: 'Back to the list', ar: 'العودة للقائمة' }, + 'pm.reason': { en: 'Reason', ar: 'السبب' }, + 'pm.delayDays': { en: 'Postpone for (days)', ar: 'التأجيل (أيام)' }, + + // ---- list + 'pm.list.title': { en: 'Grain permits', ar: 'ارساليات التموين' }, + 'pm.list.subtitle': { en: 'Search first (truck, permit number, status, order date ...) to list the permits.', ar: 'يجب البحث اولا لتظهر لك الأرساليات' }, + + // ---- confirmations + 'pm.confirm.accept': { en: 'Confirm the turn of this permit?', ar: 'هل تريد تثبيت دور هذه الارسالية؟' }, + 'pm.confirm.revoke': { en: 'Revoke the confirmation (back to "order distributed")?', ar: 'هل تريد الغاء التثبيت؟' }, + 'pm.confirm.revokeAccepted': { en: 'Cancel the confirmation of this permit (back to "turn confirmed")?', ar: 'هل تريد الغاء تثبيت هذه الارسالية؟' }, + 'pm.confirm.convert': { en: 'Convert this permit to "released"?', ar: 'هل تريد تحويل الارسالية الى تم التسريب؟' }, + 'pm.confirm.reactivate': { en: 'Put this permit back on the turn?', ar: 'هل تريد اعادة الارسالية الى الدور؟' }, + 'pm.confirm.phoneAccept': { en: 'Confirm this order by phone?', ar: 'هل تريد تأكيد الطلبية هاتفيا؟' }, + 'pm.confirm.submit': { en: 'Submit the order with these details?', ar: 'هل تريد تقديم الطلب؟' }, + 'pm.confirm.update': { en: 'Save the changes of this order?', ar: 'هل تريد حفظ التعديلات؟' }, + + // ---- detail / order form + 'pm.detail.title': { en: 'Permit {pn}', ar: 'الارسالية {pn}' }, + 'pm.detail.status': { en: 'Status', ar: 'الحالة' }, + 'pm.detail.queueNo': { en: 'Queue no.', ar: 'رقم الدور' }, + 'pm.detail.cargo': { en: 'Cargo', ar: 'الحمولة' }, + 'pm.detail.shift': { en: 'Shift', ar: 'الفترة' }, + 'pm.detail.operation': { en: 'Operation', ar: 'نوع العملية' }, + 'pm.detail.truck': { en: 'Truck', ar: 'القاطرة' }, + 'pm.detail.trailer': { en: 'Trailer', ar: 'المقطورة' }, + 'pm.detail.driver': { en: 'Driver', ar: 'السائق' }, + 'pm.order.submitTitle': { en: 'Submit the order', ar: 'تقديم الطلب' }, + 'pm.order.editTitle': { en: 'Edit the order', ar: 'تعديل الطلب' }, + 'pm.order.pn': { en: 'Permit no.', ar: 'رقم الارسالية' }, + 'pm.order.tn': { en: 'Truck no.', ar: 'رقم القاطرة' }, + 'pm.order.trn': { en: 'Trailer no.', ar: 'رقم المقطورة' }, + 'pm.order.nnpn': { en: 'Driver national no.', ar: 'الرقم الوطني للسائق' }, + 'pm.order.name': { en: 'Driver name', ar: 'اسم السائق' }, + 'pm.order.dln': { en: 'Licence no.', ar: 'رقم الرخصة' }, + 'pm.order.dled': { en: 'Licence expiry', ar: 'تاريخ انتهاء الرخصة' }, + 'pm.order.opType': { en: 'Operation type', ar: 'نوع العملية' }, + 'pm.order.submit': { en: 'Submit', ar: 'تقديم' }, + 'pm.order.update': { en: 'Save changes', ar: 'حفظ التعديلات' }, + 'pm.order.notRegistered': { en: 'Not registered', ar: 'غير مسجلة' }, + 'pm.order.driverMissing': { en: 'The driver must be registered in the drivers screen', ar: 'السائق يجب ان يكون مسجل في شاشة السائقين' }, + 'pm.events.title': { en: 'Permit events', ar: 'احداث الارسالية' }, + 'pm.events.date': { en: 'Date', ar: 'التاريخ' }, + 'pm.events.type': { en: 'Event', ar: 'الحدث' }, + 'pm.events.by': { en: 'Done by', ar: 'بواسطة' }, + 'pm.events.status': { en: 'Status', ar: 'الحالة' }, + 'pm.events.weight': { en: 'Weight', ar: 'الوزن' }, + 'pm.events.remarks': { en: 'Remarks', ar: 'ملاحظات' }, + + // ---- queue + 'pm.queue.title': { en: 'Turns (queue)', ar: 'الأدوار' }, + 'pm.queue.subtitle': { en: 'Permit records waiting for a turn', ar: 'الارساليات بانتظار الدور' }, + 'pm.queue.add': { en: 'Add truck to the turn', ar: 'تسجيل دور' }, + 'pm.queue.cargo': { en: 'Cargo class', ar: 'نوع الحمولة' }, + 'pm.queue.confirm': { en: 'Register a turn for this truck?', ar: 'هل تريد تسجيل دور لهذه القاطرة؟' }, + + // ---- destinations + 'pm.dest.title': { en: 'Destinations', ar: 'تحديد الوجهات' }, + 'pm.dest.subtitle': { en: 'Assign a destination to a supply permit', ar: 'تحديد وجهة ارسالية تموين' }, + 'pm.menu.manualInput': { en: 'Manual input', ar: 'الادخال اليدوي' }, + 'pm.menu.activation': { en: 'Activate orders', ar: 'تفعيل الطلبيات' }, + 'pm.manual.title': { en: 'Manual input', ar: 'الادخال اليدوي' }, + 'pm.manual.subtitle': { en: 'Enter a truck by hand against an order date and destination', ar: 'ادخال شاحنة يدوياً على طلبية ووجهة' }, + 'pm.activation.title': { en: 'Activate orders', ar: 'تفعيل الطلبيات' }, + 'pm.activation.subtitle': { en: 'Activate or deactivate the orders of the day', ar: 'تفعيل وإلغاء تفعيل طلبيات اليوم' }, + 'pm.dest.destination': { en: 'Destination', ar: 'الوجهة' }, + 'pm.dest.cargo': { en: 'Cargo', ar: 'الحمولة' }, + 'pm.dest.confirm': { en: 'Assign this destination to the permit?', ar: 'هل تريد تحديد هذه الوجهة للارسالية؟' }, + 'pm.manual.orderDate': { en: 'Order date', ar: 'تاريخ الطلبية' }, + 'pm.manual.order': { en: 'Order', ar: 'الطلبية' }, + 'pm.manual.noOrders': { en: 'No orders available', ar: 'لا توجد طلبيات متاحة' }, + 'pm.manual.ltw': { en: 'First weight (tare)', ar: 'الوزن الأول' }, + 'pm.manual.lgw': { en: 'Second weight (gross)', ar: 'الوزن الثاني' }, + 'pm.manual.altList': { en: 'List orders of the permit type', ar: 'طلبيات حسب نوع الارسالية' }, + 'pm.manual.confirm': { en: 'Assign the destination manually and record the weights?', ar: 'هل تريد تحديد الوجهة يدويا وتسجيل الأوزان؟' }, + 'pm.activate.loc': { en: 'Loading site', ar: 'الموقع' }, + 'pm.activate.cargo': { en: 'Cargo', ar: 'الحمولة' }, + 'pm.activate.total': { en: 'Trucks', ar: 'العدد' }, + 'pm.activate.used': { en: 'Distributed', ar: 'الموزع' }, + 'pm.activate.confirm': { en: 'Save the activation of today\'s orders?', ar: 'هل تريد حفظ تفعيل طلبيات اليوم؟' }, + + // ---- distribution + 'pm.dist.title': { en: 'Distribution', ar: 'توزيع الطلبيات' }, + 'pm.dist.subtitle': { en: 'Distribute turns to orders, process single trucks and look up a truck', ar: 'توزيع الأدوار على الطلبيات ومعالجة السيارات والاستعلام' }, + 'pm.dist.tabDistribute': { en: 'Distribute', ar: 'توزيع' }, + 'pm.dist.tabProcess': { en: 'Single truck / manual', ar: 'سيارة / يدوي' }, + 'pm.dist.tabSearch': { en: 'Truck inquiry', ar: 'استعلام عن سيارة' }, + 'pm.dist.category': { en: 'Category', ar: 'الفئة' }, + 'pm.dist.run': { en: 'Distribute', ar: 'توزيع' }, + 'pm.dist.confirm': { en: 'Distribute the open turns of this category to the orders?', ar: 'هل تريد توزيع الأدوار المفتوحة على الطلبيات؟' }, + 'pm.dist.summary': { en: 'Distributed permits per company', ar: 'الارساليات الموزعة حسب الشركة' }, + 'pm.dist.pivot': { en: 'Distributed permits per destination type', ar: 'الارساليات الموزعة حسب نوع الوجهة' }, + 'pm.dist.company': { en: 'Company', ar: 'الشركة' }, + 'pm.dist.count': { en: 'Count', ar: 'العدد' }, + 'pm.dist.silos': { en: 'Silos', ar: 'صوامع' }, + 'pm.dist.direct': { en: 'Direct', ar: 'مباشر' }, + 'pm.dist.packed': { en: 'Packed', ar: 'مشول' }, + 'pm.proc.byTruck': { en: 'Distribute a truck on the turn', ar: 'توزيع سيارة على الدور' }, + 'pm.proc.autoOrder': { en: 'Pick an order automatically', ar: 'اختيار طلبية تلقائيا' }, + 'pm.proc.single': { en: 'Move to "order distributed" only', ar: 'تحويل الحالة فقط' }, + 'pm.proc.withDest': { en: 'Distribute a permit to a chosen order', ar: 'توزيع ارسالية على طلبية محددة' }, + 'pm.proc.confirm': { en: 'Distribute now?', ar: 'هل تريد التوزيع؟' }, + 'pm.proc.revokeAll': { en: 'Send old requested permits back to the turn', ar: 'ارجاع الارساليات القديمة الى الدور' }, + 'pm.proc.limit': { en: 'Orders below number', ar: 'الطلبيات الأقل من الرقم' }, + 'pm.proc.revokeAllRun': { en: 'Run', ar: 'تنفيذ' }, + 'pm.proc.revokeAllConfirm': { en: 'Send every requested / planned company permit of the older orders back to the turn?', ar: 'هل تريد ارجاع جميع الارساليات الى الدور؟' }, + 'pm.search.status': { en: 'Latest status', ar: 'آخر حالة' }, + 'pm.search.locations': { en: 'Company destinations', ar: 'وجهات الشركة' }, + 'pm.search.orders': { en: 'Current orders', ar: 'الطلبيات الحالية' }, + 'pm.search.quantities': { en: 'Distributed / ordered trucks', ar: 'الموزع / المطلوب' }, + 'pm.absence.enable': { en: 'Enable absence feature', ar: 'تفعيل الاستنكاف' }, + 'pm.absence.disable': { en: 'Disable absence feature', ar: 'ايقاف الاستنكاف' }, + 'pm.absence.confirm': { en: 'Switch the absence feature?', ar: 'هل تريد تغيير حالة خاصية الاستنكاف؟' }, + + // ---- weighbridges + 'pm.wb.title': { en: 'Weighbridges', ar: 'القبّان' }, + 'pm.wb.subtitle': { en: 'Entry / exit weighings, manual weighing and manual closing', ar: 'الوزن عند الدخول والخروج والوزن اليدوي واغلاق التصريح' }, + 'pm.wb.tabEnter': { en: 'Entry weighing', ar: 'وزن الدخول' }, + 'pm.wb.tabExit': { en: 'Exit weighing', ar: 'وزن الخروج' }, + 'pm.wb.tabManual': { en: 'Manual weighing', ar: 'وزن يدوي' }, + 'pm.wb.tabLoading': { en: 'Loading weights', ar: 'أوزان التحميل' }, + 'pm.wb.tabDischarge': { en: 'Discharge weights', ar: 'أوزان التفريغ' }, + 'pm.wb.tabCounts': { en: 'Trucks per site', ar: 'السيارات حسب الموقع' }, + 'pm.wb.tabClose': { en: 'Close a permit', ar: 'اغلاق تصريح' }, + 'pm.wb.weight': { en: 'Weight (kg)', ar: 'الوزن (كغم)' }, + 'pm.wb.tare': { en: 'Tare weight', ar: 'الوزن الفارغ' }, + 'pm.wb.gross': { en: 'Gross weight', ar: 'الوزن القائم' }, + 'pm.wb.first': { en: 'First weight (tare)', ar: 'الوزن الأول' }, + 'pm.wb.second': { en: 'Second weight (gross)', ar: 'الوزن الثاني' }, + 'pm.wb.location': { en: 'Weighbridge location no.', ar: 'رقم موقع القبان' }, + 'pm.wb.findDest': { en: 'Find destination', ar: 'البحث عن الوجهة' }, + 'pm.wb.loc': { en: 'Site', ar: 'الموقع' }, + 'pm.wb.trucks': { en: 'Trucks', ar: 'عدد السيارات' }, + 'pm.wb.close': { en: 'Close the permit', ar: 'اغلاق التصريح' }, + 'pm.wb.closeConfirm': { en: 'Close this permit manually?', ar: 'هل تريد اغلاق التصريح يدويا؟' }, + + // ---- print + 'pm.print.print': { en: 'Print', ar: 'طباعة' }, + 'pm.slip.title': { en: 'Permit form no. {pn}', ar: 'نموذج ارسالية رقم {pn}' }, + 'pm.slip.permit': { en: 'Permit no.', ar: 'رقم الإرسالية' }, + 'pm.slip.company': { en: 'Company', ar: 'اسم الشركة' }, + 'pm.slip.truck': { en: 'Truck no.', ar: 'رقم القاطرة' }, + 'pm.slip.trailer': { en: 'Trailer no.', ar: 'رقم المقطورة' }, + 'pm.slip.operation': { en: 'Operation type', ar: 'نوع العملية' }, + 'pm.slip.driver': { en: 'Driver', ar: 'اسم السائق' }, + 'pm.slip.cargoShift': { en: 'Cargo / shift', ar: 'المادة/الشفت' }, + 'pm.slip.loading': { en: 'Loading location', ar: 'موقع التحميل' }, + 'pm.slip.destination': { en: 'Destination', ar: 'الوجهة' }, + 'pm.slip.moit': { en: 'Ministry of Industry and Trade permit no.', ar: 'رقم إرسالية وزارة الصناعة والتجارة' }, + 'pm.slip.nextPn': { en: 'Next permit no.', ar: 'رقم الإرسالية القادمة' }, + 'pm.slip.printedAt': { en: 'Printed on', ar: 'تاريخ طباعة الارسالية' }, + 'pm.slip.stampLoading': { en: 'Loading site stamp', ar: 'ختم موقع التحميل' }, + 'pm.slip.stampUnloading': { en: 'Unloading site stamp', ar: 'ختم موقع التفريغ' }, + 'pm.slip.titleIn': { en: 'Entry form', ar: 'نموذج ادخال' }, + 'pm.slip.titleOut': { en: 'Loading and exit form', ar: 'نموذج شحن وإخراج' }, + 'pm.slip.number': { en: 'No.:', ar: 'رقم:' }, + 'pm.slip.date': { en: 'Date:', ar: 'التاريخ:' }, + 'pm.slip.receivedFrom': { en: 'Received from:', ar: 'استلمت من:' }, + 'pm.slip.vehicle': { en: 'Vehicle no.:', ar: 'واسطة نقل رقم:' }, + 'pm.slip.vehicleNo': { en: 'Vehicle no.:', ar: 'رقم واسطة النقل:' }, + 'pm.slip.receivingCenterName': { en: 'Receiving center:', ar: 'اسم المركز المستلم:' }, + 'pm.slip.driverName': { en: 'Driver:', ar: 'اسم السائق:' }, + 'pm.slip.driverNnpn': { en: 'Driver national no.:', ar: 'الرقم الوطني للسائق:' }, + 'pm.slip.transporter': { en: 'Transport company:', ar: 'اسم شركة النقل:' }, + 'pm.slip.weightByCenter': { en: 'Weight per the center', ar: 'الوزن حسب المركز' }, + 'pm.slip.weightReceived': { en: 'Weight received', ar: 'الوزن المستلم' }, + 'pm.slip.cargoType': { en: 'Cargo type', ar: 'نوع المادة' }, + 'pm.slip.receivingCenter': { en: 'Receiving center and number', ar: 'المركز المستلم ورقمه' }, + 'pm.slip.sendingCenter': { en: 'Sending center', ar: 'المركز المرسل' }, + 'pm.slip.netWeight': { en: 'Net weight', ar: 'الوزن الصافي' }, + 'pm.slip.ton': { en: 'Ton', ar: 'طن' }, + 'pm.slip.kilo': { en: 'Kilo', ar: 'كيلو' }, + 'pm.slip.netSent': { en: 'Net sent', ar: 'الصافي المرسل' }, + 'pm.slip.netReceived': { en: 'Net received', ar: 'الصافي المستلم' }, + 'pm.slip.difference': { en: 'Difference', ar: 'الفرق' }, + 'pm.slip.note': { en: 'Note:', ar: 'ملاحظة :' }, + 'pm.slip.officer': { en: 'Officer name:', ar: 'اسم الموظف المختص:' }, + 'pm.slip.ack': { en: 'I confirm I received the cargo above in full', ar: 'أقر انني استلمت الحمولة المبينة اعلاه كاملة' }, + 'pm.slip.officerSign': { en: 'Officer signature:', ar: 'توقيع الموظف المختص:' }, + 'pm.slip.driverSign': { en: 'Driver signature:', ar: 'توقيع السائق:' }, + 'pm.slip.footer': { en: 'This document is not official unless it carries the company stamp', ar: 'لا يعتبر هذا الطلب وثيقة رسمية مالم يحمل ختم الشركة' }, + 'pm.print.generating': { en: 'Creating the PDF…', ar: 'جاري إنشاء ملف PDF…' }, + 'pm.print.pdfFailed': { en: 'The PDF could not be created. Use the Print button instead.', ar: 'تعذر إنشاء ملف PDF. استخدم زر الطباعة.' }, + 'pm.print.failed': { en: 'The print data is not available for this permit.', ar: 'بيانات الطباعة غير متوفرة لهذه الارسالية.' }, + 'pm.print.acceptTitle': { en: 'Grain permit', ar: 'ارسالية تموين' }, + 'pm.print.inTitle': { en: 'Weight statement (loading and discharge)', ar: 'كشف الأوزان (تحميل وتفريغ)' }, + 'pm.print.outTitle': { en: 'Loading weight statement', ar: 'كشف وزن التحميل' }, + 'pm.print.nextPn': { en: 'Next permit no.', ar: 'رقم الارسالية التالية' }, + 'pm.print.printedAt': { en: 'Printed at', ar: 'وقت الطباعة' }, + 'pm.print.trackingNo': { en: 'Tracking no.', ar: 'رقم التتبع' }, + 'pm.print.origin': { en: 'Loading site', ar: 'موقع التحميل' }, + 'pm.print.net': { en: 'Net', ar: 'الصافي' }, + 'pm.print.tonKilo': { en: 'Ton / kg', ar: 'طن / كغم' }, + 'pm.print.loading': { en: 'Loading', ar: 'التحميل' }, + 'pm.print.discharge': { en: 'Discharge', ar: 'التفريغ' }, + 'pm.print.difference': { en: 'Difference (discharge - loading)', ar: 'الفرق (تفريغ - تحميل)' }, + 'pm.print.doneBy': { en: 'Weighed by', ar: 'تم الوزن بواسطة' }, +}); diff --git a/web/src/features/grains-permits/types.ts b/web/src/features/grains-permits/types.ts new file mode 100644 index 0000000..cc0d595 --- /dev/null +++ b/web/src/features/grains-permits/types.ts @@ -0,0 +1,100 @@ +/** Wire types of the Grains permits slice (camelCase JSON of src/NTP.Application/Grains/Permits/PermitContracts.cs). */ + +export interface PermitOperationResult { + success: boolean; + message: string; + code?: string | null; + permitId?: number | null; + data?: Record | null; +} + +export interface PermitListItem { + id: number; + pn: string | null; + tn: string | null; + trn: string | null; + trackingNo: string | null; + creationDate: string | null; + destinationName: string | null; + drvr: string | null; + compName: string | null; + statusCaption: string | null; + shipmentStatusCode: string | null; + companyCode: number | null; + queueNo: string | null; + actions: string[]; +} + +export interface PermitEvent { + eventDate: string | null; + eventType: string | null; + eventCaption: string | null; + doneBy: string | null; + currentStatusCode: string | null; + currentStatus: string | null; + weight: number | null; + remarks: string | null; +} + +export interface TruckInfo { tn: string; chasesNumber: string | null; axials: string | null; regDate: string | null } +export interface DriverInfo { nnpn: string; name: string | null; dln: string | null; dled: string | null } + +export interface PermitDetail { + id: number; + pn: string | null; + statusCode: string | null; + statusCaption: string | null; + companyName: string | null; + companyCode: number | null; + queueNo: string | null; + shift: string | null; + cargoType: string | null; + operationType: string | null; + operationTypeCode: string | null; + truck: TruckInfo | null; + trailer: TruckInfo | null; + driver: DriverInfo | null; + actions: string[]; + events: PermitEvent[]; +} + +export interface QueueItem { id: number; tn: string | null; pn: string | null; creationDate: string | null } + +export interface LookupItem { id: number; name: string | null } +export interface CompanyOption { scac: number; companyCode: string | null } +export interface LocationGroups { packed: LookupItem[]; bulk: LookupItem[]; bulkGallab: LookupItem[] } +export interface AllowedDestination { orderId: number; name: string | null; dest: number | null; orderDate: string | null } +export interface OrderChoice { id: number; destName: string | null } +export interface DestinationSearchResult { destination: string | null; origin: number | null; message: string | null } + +export interface OrderActivationRow { + locId: number; ctId: number; loc: string | null; ct: string | null; total: number; used: number; statusCode: string | null; +} + +export interface DistributionSummaryRow { companyCode: number | null; comp: string | null; cnt: number } +export interface DistributionPivotRow { companyCode: number | null; company: string | null; silos: number; direct: number; packed: number } +export interface TruckDistribution { + status: string; companyLocations: string; order: string; errorMsg: string; trucksTotalQuantity: number; tenderTotalQuantity: number; +} +export interface BlacklistedDistribution { blacklistId: number; text: string | null; cargoType: number | null } + +export interface WeighbridgeResult { success: boolean; errorCode: string; message: string; action: string | null; permitId: number | null } +export interface TruckPermitBrief { id: number; drvr: string | null; tn: string | null; pn: string | null; shipmentStatusCode: string | null } +export interface LocationTruckCount { loc: string | null; cnt: number } + +export interface AcceptPrint { + id: number; pn: string | null; shipmentStatusCode: string | null; shift: string | null; tn: string | null; trn: string | null; + drvr: string | null; compName: string | null; operationType: string | null; destination: string | null; cargoType: string | null; + location: string | null; nextPn: string | null; crn: number | null; scrn: number | null; printedAt: string; hasOrder: boolean; +} +export interface PrintHeader { + trackingNo: string | null; compName: string | null; drvr: string | null; nnpn: string | null; tn: string | null; + shipmentMode: string | null; destination: string | null; origin: string | null; +} +export interface WeightFigures { net: number; ton: number; kilo: number } +export interface PrintIn { + header: PrintHeader; loadingTare: number; loadingGross: number; dischargeTare: number; dischargeGross: number; + loading: WeightFigures; discharge: WeightFigures; tonDifference: number; kiloDifference: number; sign: string; + loadingLocation: string | null; dischargeLocation: string | null; doneBy: string | null; +} +export interface PrintOut { header: PrintHeader; netWeight: number; ton: number; kilo: number; location: string | null; doneBy: string | null } diff --git a/web/src/features/grains-registry/api.ts b/web/src/features/grains-registry/api.ts new file mode 100644 index 0000000..bd1aa92 --- /dev/null +++ b/web/src/features/grains-registry/api.ts @@ -0,0 +1,160 @@ +import { useQuery } from '@tanstack/react-query'; +import { api, API_BASE, ApiError, getToken } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { gridKey } from '@/components/DataGrid'; +import type { OptionItem, OptionsLoader } from '@/components/meta/types'; +import { useLanguage } from '@/providers/LanguageProvider'; +import type { + BlacklistAdded, DriverDetail, LocationTruckCount, RegistryDestinationOptions, RegistryLocation, RegistryNationality, + RegistryPermissions, RegistryResult, RegistryTempFile, TenderCompany, TrailerDetail, TrailerRow, TruckDetail, TruckKind, +} from './types'; + +export const BASE = '/grains/registry'; + +export const GRID_TRUCKS = 'grains.registry.trucks'; +export const GRID_TRAILERS = 'grains.registry.trailers'; +export const GRID_DRIVERS = 'grains.registry.drivers'; +export const GRID_BLACKLIST = 'grains.registry.blacklist'; + +// ---------------------------------------------------------------- option loaders (cached by React Query) +export const companyOptions: OptionsLoader = { + key: 'grains.registry.companies', + load: async () => (await api.get(`${BASE}/lookups/companies`, undefined, { silent: true })) + .map((c) => ({ value: c.scac, label: `${c.scac} - ${c.name ?? ''}` })), +}; + +export const nationalityOptions: OptionsLoader = { + key: 'grains.registry.nationalities', + load: async () => (await api.get(`${BASE}/lookups/driver-nationalities`, undefined, { silent: true })) + .map((n) => ({ value: n.code, label: n.name ?? n.code })), +}; + +export const weighbridgeLocationOptions: OptionsLoader = { + key: 'grains.registry.weighbridgeLocations', + load: async () => (await api.get(`${BASE}/lookups/weighbridge-locations`, undefined, { silent: true })) + .map((l) => ({ value: l.id, label: l.name ?? String(l.id) })), +}; + +/** Axial loads of the vehicle kinds returned by `kinds(parent)` (S/T for trucks, TR/HTR for trailers). */ +export const axialsOptions = (cacheKey: string, kinds: (parent: unknown) => string): OptionsLoader => ({ + key: `grains.registry.axials.${cacheKey}`, + load: async ({ parent }) => { + const k = kinds(parent); + if (!k) return []; + return (await api.get(`${BASE}/lookups/truck-kinds`, { kinds: k }, { silent: true })) + .map((x) => ({ value: x.id, label: x.name ?? String(x.id) })); + }, +}); + +// ---------------------------------------------------------------- queries +export function usePermissions() { + const { langReady } = useLanguage(); + return useQuery({ + queryKey: ['grains.registry.permissions'], + queryFn: () => api.get(`${BASE}/permissions`, undefined, { silent: true }), + enabled: langReady, + staleTime: 5 * 60_000, + }); +} + +export function useDestinationOptions(enabled: boolean) { + const { lang, langReady } = useLanguage(); + return useQuery({ + queryKey: ['grains.registry.destinations', lang], + queryFn: () => api.get(`${BASE}/lookups/destinations`, undefined, { silent: true }), + enabled: enabled && langReady, + staleTime: 5 * 60_000, + }); +} + +export const useTruck = (id: number | null) => + useQuery({ queryKey: ['grains.registry.truck', id], queryFn: () => api.get(`${BASE}/trucks/${id}`), enabled: id !== null }); + +export const useTruckTrailers = (id: number | null) => + useQuery({ queryKey: ['grains.registry.truckTrailers', id], queryFn: () => api.get(`${BASE}/trucks/${id}/trailers`), enabled: id !== null }); + +export const useTrailer = (id: number | null) => + useQuery({ queryKey: ['grains.registry.trailer', id], queryFn: () => api.get(`${BASE}/trailers/${id}`), enabled: id !== null }); + +export const useDriver = (id: number | null) => + useQuery({ queryKey: ['grains.registry.driver', id], queryFn: () => api.get(`${BASE}/drivers/${id}`), enabled: id !== null }); + +export const useLocationTruckCounts = () => + useQuery({ queryKey: ['grains.registry.locationCounts'], queryFn: () => api.get(`${BASE}/location-truck-counts`) }); + +// ---------------------------------------------------------------- MOT checks (advisory, on demand) +export const motTruck = (tn: string, scac: number, truckType?: string) => + api.get<{ result: string }>(`${BASE}/mot/truck`, { tn, scac, truckType }, { silent: true }); +export const motTrailer = (trn: string, scac: number) => + api.get<{ result: string }>(`${BASE}/mot/trailer`, { trn, scac }, { silent: true }); +export const motOwner = (tn: string, scac: number) => + api.get<{ message: string }>(`${BASE}/mot/owner`, { tn, scac }, { silent: true }); + +// ---------------------------------------------------------------- writes +const truckKeys = () => [gridKey(GRID_TRUCKS), ['grains.registry.truck'], ['grains.registry.truckTrailers']]; +const trailerKeys = () => [gridKey(GRID_TRAILERS), ['grains.registry.trailer'], ['grains.registry.truckTrailers'], ['grains.registry.truck']]; +const driverKeys = () => [gridKey(GRID_DRIVERS), ['grains.registry.driver']]; + +export const useCreateTruck = () => + useWrite((p: Record) => api.post(`${BASE}/trucks`, p), { invalidate: truckKeys() }); +export const useUpdateTruck = (id: number) => + useWrite((p: Record) => api.put(`${BASE}/trucks/${id}`, p), { invalidate: truckKeys() }); +export const useTruckAction = () => + useWrite((v: { id: number; action: 'accept' | 'revoke' }) => api.post(`${BASE}/trucks/${v.id}/${v.action}`), { + invalidate: [...truckKeys(), gridKey(GRID_TRAILERS)], + }); + +export const useCreateTrailer = () => + useWrite((p: Record) => api.post(`${BASE}/trailers`, p), { invalidate: trailerKeys() }); +export const useUpdateTrailer = (id: number) => + useWrite((p: Record) => api.put(`${BASE}/trailers/${id}`, p), { invalidate: trailerKeys() }); +export const useTrailerAction = () => + useWrite((v: { id: number; action: 'accept' | 'revoke' }) => api.post(`${BASE}/trailers/${v.id}/${v.action}`), { + invalidate: trailerKeys(), + }); + +export const useCreateDriver = () => + useWrite((p: Record) => api.post(`${BASE}/drivers`, p), { invalidate: driverKeys() }); +export const useDriverAction = () => + useWrite((v: { id: number; action: 'accept' | 'revoke' }) => api.post(`${BASE}/drivers/${v.id}/${v.action}`), { + invalidate: driverKeys(), + }); + +export const useAddBlacklist = () => + useWrite((p: Record) => api.post(`${BASE}/blacklist`, p), { invalidate: [gridKey(GRID_BLACKLIST)] }); +export const useCancelBlacklist = () => + useWrite((v: { id: number; remarks: string }) => api.post(`${BASE}/blacklist/${v.id}/cancel`, { remarks: v.remarks }), { + invalidate: [gridKey(GRID_BLACKLIST)], + }); + +export const useSaveWeighbridge = () => + useWrite((p: Record) => api.post(`${BASE}/weighbridge-control`, p)); + +// ---------------------------------------------------------------- attachments +export function uploadTemp(file: File): Promise { + const form = new FormData(); + form.append('file', file); + return api.upload(`${BASE}/files/temp`, form, { silent: true }); +} + +/** Attachments need the bearer token, so they are fetched and opened as a blob (not a plain link). */ +export async function openAttachment(kind: string, fileName: string, fallbackError: string): Promise { + const token = getToken(); + const res = await fetch(`${API_BASE}${BASE}/files/${encodeURIComponent(kind)}/${encodeURIComponent(fileName)}`, { + headers: token ? { Authorization: `Bearer ${token}` } : {}, + }); + if (!res.ok) throw new ApiError(res.status, fallbackError); + const url = URL.createObjectURL(await res.blob()); + window.open(url, '_blank', 'noopener'); + window.setTimeout(() => URL.revokeObjectURL(url), 60_000); +} + +export function useCompanies() { + const { langReady } = useLanguage(); + return useQuery({ + queryKey: ['grains.registry.companies.list'], + queryFn: () => api.get(`${BASE}/lookups/companies`, undefined, { silent: true }), + enabled: langReady, + staleTime: 5 * 60_000, + }); +} diff --git a/web/src/features/grains-registry/components.tsx b/web/src/features/grains-registry/components.tsx new file mode 100644 index 0000000..7aac24d --- /dev/null +++ b/web/src/features/grains-registry/components.tsx @@ -0,0 +1,262 @@ +import { useEffect, useRef, useState } from 'react'; +import { + alpha, Alert, Box, Button, Checkbox, Chip, FormControlLabel, FormGroup, MenuItem, Stack, TextField, Typography, +} from '@mui/material'; +import AttachFileIcon from '@mui/icons-material/AttachFile'; +import GrainIcon from '@mui/icons-material/Grain'; +import Inventory2Icon from '@mui/icons-material/Inventory2'; +import LocalShippingIcon from '@mui/icons-material/LocalShipping'; +import UploadFileIcon from '@mui/icons-material/UploadFile'; +import VerifiedIcon from '@mui/icons-material/Verified'; +import { api, ApiError } from '@/api/client'; +import { SectionPaper } from '@/components/SectionPaper'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useToast } from '@/providers/ToastProvider'; +import { motOwner, motTrailer, motTruck, openAttachment, useCompanies } from './api'; +import { attachmentAccept } from './meta/common'; +import strings from './strings'; +import type { DestinationSelection, RegistryAttachment, RegistryDestinationOptions } from './types'; + +/** Section card used by the detail pages (same look as the MetaForm sections). */ +export function Card({ title, children, compactTitle }: { title?: string; children: React.ReactNode; compactTitle?: boolean }) { + return ( + + {title && ( + {title} + )} + {children} + + ); +} + +/** A file uploaded to the temp area that is attached to the record when the form is saved. */ +export interface PendingDoc { id: string; name: string } + +/** + * THE documents section of trucks, trailers and drivers: one list of links (stored documents open through the authenticated + * download endpoint; files just uploaded wait for Save) and ONE upload action. Several files can be picked at once. + */ +export function DocumentsSection(props: { + items: RegistryAttachment[]; + pending: PendingDoc[]; + onAdd: (docs: PendingDoc[]) => void; + onRemove: (id: string) => void; + canUpload: boolean; + /** How many documents (stored + new) a save needs; the message turns red when a save was refused for lack of them. */ + need?: number; +}) { + const { t } = useFeatureUi(strings); + const toast = useToast(); + const input = useRef(null); + const alive = useRef(true); + const [busy, setBusy] = useState(false); + useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); + + async function pick(files: FileList | null) { + const list = files ? Array.from(files) : []; + if (list.length === 0) return; + setBusy(true); + const added: PendingDoc[] = []; + try { + for (const file of list) { + const form = new FormData(); + form.append('file', file); + const r = await api.upload<{ id?: string; name?: string }>('/grains/registry/files/temp', form, { silent: true }); + if (!r?.id) throw new ApiError(0, t('common.uploadFailed')); + added.push({ id: String(r.id), name: r.name || file.name }); + } + } catch (e) { + toast.error(e instanceof ApiError ? e.message : t('common.uploadFailed')); + } finally { + if (input.current) input.current.value = ''; + if (alive.current) setBusy(false); + } + if (added.length > 0 && alive.current) props.onAdd(added); + } + + const total = props.items.length + props.pending.length; + const missing = props.need !== undefined && props.need > 0 && total < props.need; + return ( + + + {total === 0 ? ( + {t('reg.docs.none')} + ) : ( + + {props.items.map((a) => ( + } + label={a.originalName || a.fileName} + variant="outlined" + clickable + onClick={() => openAttachment(a.kind, a.fileName, t('reg.docs.openFailed')).catch((e) => + toast.error(e instanceof ApiError ? e.message : t('reg.docs.openFailed')))} + dir="auto" + /> + ))} + {props.pending.map((p) => ( + } + label={p.name} + color="primary" + variant="outlined" + onDelete={props.canUpload ? () => props.onRemove(p.id) : undefined} + dir="auto" + /> + ))} + + )} + {props.pending.length > 0 && {t('reg.docs.pendingHint')}} + {missing && {t('reg.docs.required', { n: props.need ?? 0 })}} + {props.canUpload && ( + + { void pick(e.target.files); }} /> + + + )} + + + ); +} + +/** Destination check boxes (legacy register.getDistination / getCenters): packed, bulk and bulk-tipper locations of company 327 trucks. */ +export function DestinationsPanel(props: { + options: RegistryDestinationOptions | undefined; + value: DestinationSelection; + onChange: (v: DestinationSelection) => void; + pending?: { user: string | null; time: string | null } | null; + disabled?: boolean; +}) { + const { t } = useFeatureUi(strings); + const { options, value, onChange, disabled } = props; + const groups: { key: keyof DestinationSelection; title: string; icon: React.ReactNode }[] = [ + { key: 'bulk', title: t('reg.trucks.destBulk'), icon: }, + { key: 'packed', title: t('reg.trucks.destPacked'), icon: }, + { key: 'bulkGallab', title: t('reg.trucks.destBulkGallab'), icon: }, + ]; + const toggle = (g: keyof DestinationSelection, id: number, on: boolean) => + onChange({ ...value, [g]: on ? [...value[g], id] : value[g].filter((x) => x !== id) }); + const setGroup = (g: keyof DestinationSelection, ids: number[]) => onChange({ ...value, [g]: ids }); + + return ( + + + {t('reg.trucks.destinationsHint')} + {props.pending && ( + {t('reg.trucks.destPending', { user: props.pending.user ?? '', time: props.pending.time ?? '' })} + )} + {groups.map((g) => { + const list = options?.[g.key] ?? []; + if (list.length === 0) return null; + const selected = list.filter((l) => value[g.key].includes(l.id)).length; + return ( + + ({ alignItems: 'center', px: 1.5, py: 0.75, bgcolor: alpha(th.palette.primary.main, 0.08), borderBottom: 1, borderColor: 'divider' })} + > + {g.icon} + {g.title} + {`${selected} / ${list.length}`}} sx={{ height: 20, fontSize: 11.5 }} /> + + {!disabled && ( + <> + + + + )} + + + {list.map((l) => ( + toggle(g.key, l.id, e.target.checked)} />} + /> + ))} + + + ); + })} + + + ); +} + +type MotOutcome = { severity: 'success' | 'warning' | 'error'; text: string }; + +/** + * Advisory Ministry of Transport check (legacy register.validateTNMOT / validateTRNMOT / validateOwnerTN). + * The permit screens run the same checks; here the registry user can verify a number before saving. + */ +export function MotCheckCard(props: { kind: 'truck' | 'trailer'; initialNumber?: string; initialScac?: number | null; scacLocked?: boolean }) { + const { t } = useFeatureUi(strings); + const companies = useCompanies(); + const [number, setNumber] = useState(props.initialNumber ?? ''); + const [scac, setScac] = useState(props.initialScac ? String(props.initialScac) : ''); + const [busy, setBusy] = useState(false); + const [outcomes, setOutcomes] = useState([]); + + const motText = (code: string): MotOutcome => + code === '' ? { severity: 'success', text: t('reg.mot.ok') } + : code === 'wrongCT' ? { severity: 'warning', text: t('reg.mot.wrongType') } + : { severity: 'error', text: t('reg.mot.notRegistered') }; + + async function run() { + const sc = Number(scac); + if (!number.trim() || !sc) return; + setBusy(true); + try { + if (props.kind === 'truck') { + const [truck, owner] = await Promise.all([motTruck(number.trim(), sc), motOwner(number.trim(), sc)]); + setOutcomes([ + motText(truck.result), + owner.message ? { severity: 'error', text: owner.message } : { severity: 'success', text: t('reg.mot.ownerOk') }, + ]); + } else { + setOutcomes([motText((await motTrailer(number.trim(), sc)).result)]); + } + } catch (e) { + setOutcomes([{ severity: 'error', text: e instanceof ApiError ? e.message : t('reg.mot.failed') }]); + } finally { + setBusy(false); + } + } + + return ( + + + {t('reg.mot.hint')} + + setNumber(e.target.value)} + slotProps={{ htmlInput: { dir: 'ltr', maxLength: 12, inputMode: 'numeric' } }} + /> + setScac(e.target.value)} + disabled={props.scacLocked} + > + {(companies.data ?? []).map((c) => {c.scac} - {c.name ?? ''})} + + + + {outcomes.map((o, i) => {o.text})} + + + ); +} + +/** The temp ids of the files uploaded in the documents section become the `attachmentIds` list of a save request. */ +export function withDocumentIds(payload: Record, docs: PendingDoc[]): Record { + return { ...payload, attachmentIds: docs.map((d) => d.id) }; +} + +/** Number or null for select values that may come back as text. */ +export const num = (v: unknown): number | null => (v === null || v === undefined || v === '' ? null : Number(v)); diff --git a/web/src/features/grains-registry/meta/blacklist.ts b/web/src/features/grains-registry/meta/blacklist.ts new file mode 100644 index 0000000..cce6a13 --- /dev/null +++ b/web/src/features/grains-registry/meta/blacklist.ts @@ -0,0 +1,77 @@ +import type { FormMeta, GridMeta, OptionItem } from '@/components/meta/types'; +import { GRID_BLACKLIST, weighbridgeLocationOptions } from '../api'; +import type { BlacklistRow } from '../types'; +import { blacklistStatuses, lbl } from './common'; + +const categories: OptionItem[] = [ + { value: 'PHONEDECLINE', label: lbl('Block', 'منع') }, + { value: 'WAITINGLIST', label: lbl('Waiting', 'انتظار') }, +]; +/** Legacy dropdown of blocking days. */ +const days: OptionItem[] = [1, 2, 3, 4, 5, 10, 14, 30].map((d) => ({ value: d, label: String(d) })); + +/** Legacy blackListGrid.cfm / getBlackListGrid; the cancel icon was only shown to GNSU/GNCO/GTO on OPEN entries. */ +export function blacklistGrid(h: { canCancel: boolean; onCancel: (r: BlacklistRow) => void }): GridMeta { + return { + key: GRID_BLACKLIST, + endpoint: '/grains/registry/blacklist', + rowKey: (r) => r.id, + // registration lists are large: nothing is loaded until the user picks a filter (status chip or any search field) + requireFilter: true, + status: { param: 'statusCode', options: blacklistStatuses }, + filters: [ + { name: 'entityId', type: 'text', label: lbl('Permit number', 'رقم الارسالية'), inputKind: 'plate' }, + { name: 'category', type: 'select', label: lbl('Type', 'النوع'), options: categories }, + ], + columns: [ + { key: 'entityNumber', header: lbl('Permit', 'الارسالية'), ltr: true }, + { key: 'entityTypeCaption', header: lbl('Entity', 'الجهة'), hideBelow: 'md' }, + { key: 'categoryCaption', header: lbl('Type', 'النوع') }, + { key: 'creationDate', header: lbl('Created on', 'تاريخ الإنشاء'), format: 'datetime', ltr: true, hideBelow: 'md' }, + { key: 'createdBy', header: lbl('Created by', 'أنشئ بواسطة'), hideBelow: 'lg' }, + { key: 'expiryDate', header: lbl('Expires on', 'تاريخ الانتهاء'), format: 'datetime', ltr: true }, + { key: 'remarks', header: lbl('Remarks', 'ملاحظات'), hideBelow: 'lg' }, + { key: 'statusCode', header: lbl('Status', 'الحالة'), format: 'status', statuses: blacklistStatuses }, + ], + rowActions: h.canCancel + ? [{ key: 'cancel', label: lbl('Cancel entry', 'إلغاء الحظر'), danger: true, hidden: (r) => r.statusCode !== 'OPEN', onClick: h.onCancel }] + : [], + }; +} + +/** createBlacklist.cfm (permit number, type, days, remarks). */ +export const blacklistForm = (): FormMeta => ({ + key: 'grains.registry.blacklistForm', + sections: [ + { + key: 'entry', + columns: 2, + fields: [ + { + name: 'entityNum', type: 'text', label: lbl('Permit number', 'رقم الارسالية'), required: true, inputKind: 'plate', maxLength: 18, + pattern: { regex: /^\d{1,18}$/, message: lbl('Digits only', 'أرقام فقط') }, + }, + { name: 'category', type: 'select', label: lbl('Type', 'النوع'), required: true, options: categories, defaultValue: 'PHONEDECLINE' }, + { name: 'expiryDays', type: 'select', label: lbl('Blocking days', 'عدد ايام المنع'), required: true, options: days, defaultValue: 1 }, + { name: 'remarks', type: 'textarea', label: lbl('Remarks', 'ملاحظات'), required: true, rows: 3, maxLength: 400, span: 'full' }, + ], + }, + ], +}); + +/** WeighbridgesControl.cfm. */ +export const weighbridgeForm = (): FormMeta => ({ + key: 'grains.registry.weighbridgeForm', + sections: [ + { + key: 'wb', + columns: 2, + fields: [ + { name: 'tn', type: 'text', label: lbl('Truck number', 'رقم القاطرة'), required: true, inputKind: 'plate', maxLength: 20 }, + { name: 'locationId', type: 'select', label: lbl('Weighbridge location', 'موقع الميزان'), required: true, options: weighbridgeLocationOptions }, + { name: 'expiryDate', type: 'date', label: lbl('Exception valid until', 'صالح حتى'), required: true }, + { name: 'notes', type: 'textarea', label: lbl('Notes', 'ملاحظات'), required: true, rows: 3, maxLength: 400, span: 'full' }, + ], + }, + ], +}); diff --git a/web/src/features/grains-registry/meta/common.ts b/web/src/features/grains-registry/meta/common.ts new file mode 100644 index 0000000..582a653 --- /dev/null +++ b/web/src/features/grains-registry/meta/common.ts @@ -0,0 +1,97 @@ +import type { FieldMeta, L10n, OptionItem, Rule, StatusMeta } from '@/components/meta/types'; + +/** Company 327 (Al Badiya) must supply the full data set; every other company only the vehicle number (legacy GN_BadiyaSCAC). */ +export const BADIYA_SCAC = 327; +export const isBadiya: Rule = { field: 'tcscac', op: 'eq', value: BADIYA_SCAC }; + +export const REGISTRY_ROOT = '/grains/registry'; + +/** Status chips of trucks / trailers / drivers (legacy STATUS rows of domain GN). */ +export const registryStatuses: StatusMeta[] = [ + { value: 'OPEN', label: { en: 'New', ar: 'جديد' }, color: 'info' }, + { value: 'REGREQST', label: { en: 'Awaiting registration', ar: 'بانتظار التسجيل' }, color: 'warning' }, + { value: 'ACCPT', label: { en: 'Licensed', ar: 'مرخص' }, color: 'success' }, + { value: 'INCOMP', label: { en: 'Incomplete', ar: 'غير مكتمل' }, color: 'warning' }, + { value: 'RVKD', label: { en: 'Revoked', ar: 'ملغي' }, color: 'error' }, +]; + +export const blacklistStatuses: StatusMeta[] = [ + { value: 'OPEN', label: { en: 'Active', ar: 'فعال' }, color: 'error' }, + { value: 'DELETED', label: { en: 'Cancelled', ar: 'ملغي' }, color: 'default' }, + { value: 'EXPIRED', label: { en: 'Expired', ar: 'منتهي' }, color: 'default' }, +]; + +/** Mirrors RegistryRules: accept unless ACCPT/RVKD, revoke and edit unless RVKD. */ +export const canAcceptStatus = (s: string | null | undefined) => (s ?? '').toUpperCase() !== 'ACCPT' && (s ?? '').toUpperCase() !== 'RVKD'; +export const canRevokeStatus = (s: string | null | undefined) => (s ?? '').toUpperCase() !== 'RVKD'; +export const canEditStatus = canRevokeStatus; + +/** The legacy validateSpecialChars class: these characters are refused in names, numbers and owner data. */ +export const NO_SPECIAL: NonNullable = { + regex: /^[^!,@#$%+\-*^&<>{}:";'\\/_)(=|~.`[\]?]*$/, + message: { en: 'Special characters are not allowed', ar: 'لا يجوز ادخال حروف خاصة' }, +}; + +export const DIGITS_ONLY = (max: number): NonNullable => ({ + regex: new RegExp(`^\\d{1,${max}}$`), + message: { en: `Digits only, up to ${max}`, ar: `أرقام فقط، حتى ${max} خانة` }, +}); + +/** Manufacture year 1960 .. next year (legacy range check), as a regex because the value travels as text. */ +export function manufactureYearPattern(now = new Date()): NonNullable { + const last = now.getFullYear() + 1; + const years: number[] = []; + for (let y = 1960; y <= last; y++) years.push(y); + return { + regex: new RegExp(`^(${years.join('|')})$`), + message: { en: `Year must be between 1960 and ${last}`, ar: `سنة الصنع يجب ان تكون بين 1960 - ${last}` }, + }; +} + +export const attachmentAccept = '.pdf,.png,.jpg,.jpeg,.gif,.tif,.tiff,.bmp,.doc,.docx'; + +export const colorOptions: OptionItem[] = [ + { value: 'WHITE', label: { en: 'White', ar: 'أبيض' } }, + { value: 'YELLOW', label: { en: 'Yellow', ar: 'أصفر' } }, + { value: 'RED', label: { en: 'Red', ar: 'أحمر' } }, + { value: 'GREEN', label: { en: 'Green', ar: 'أخضر' } }, + { value: 'BLACK', label: { en: 'Black', ar: 'أسود' } }, + { value: 'SILVER', label: { en: 'Silver', ar: 'فضي' } }, + { value: 'BLUE', label: { en: 'Blue', ar: 'أزرق' } }, + { value: 'BEIGE', label: { en: 'Beige', ar: 'بيج' } }, + { value: 'ORANGE', label: { en: 'Orange', ar: 'برتقالي' } }, +]; + +export const modelOptions: OptionItem[] = [ + { value: 'MERCEDES', label: { en: 'Mercedes', ar: 'مرسيدس' } }, + { value: 'MAN', label: 'MAN' }, + { value: 'Renault', label: { en: 'Renault', ar: 'رينو' } }, + { value: 'SCANIA', label: { en: 'Scania', ar: 'سكانيا' } }, + { value: 'VOLVO', label: { en: 'Volvo', ar: 'فولفو' } }, + { value: 'FIAT', label: { en: 'Fiat', ar: 'فيات' } }, +]; + +export const headTypeOptions: OptionItem[] = [ + { value: 'Trella', label: { en: 'Trailer head', ar: 'تريلا' } }, + { value: 'Tripper', label: { en: 'Tipper', ar: 'قلاب' } }, + { value: 'Single', label: { en: 'Single', ar: 'سنجل' } }, +]; + +export const truckKindOptions: OptionItem[] = [ + { value: 'S', label: { en: 'Single (up to 6 axial loads)', ar: 'سنجل' } }, + { value: 'T', label: { en: 'Tractor with trailer', ar: 'رأس تريلا' } }, +]; + +export const trailerKindOptions: OptionItem[] = [ + { value: 'TR', label: { en: 'Trailer', ar: 'مقطورة' } }, + { value: 'HTR', label: { en: 'Heavy trailer', ar: 'مقطورة ثقيلة' } }, +]; + +/** Axial loads belong to a vehicle kind; legacy derives the kind from the axial count (trucks < 7 = S, trailers < 12 = TR). */ +export const truckKindOfAxials = (a: number | null | undefined) => (a === null || a === undefined ? '' : a < 7 ? 'S' : 'T'); +export const trailerKindOfAxials = (a: number | null | undefined) => (a === null || a === undefined ? '' : a < 12 ? 'TR' : 'HTR'); + +export const lbl = (en: string, ar: string): L10n => ({ en, ar }); + +/** yyyy-mm-dd of an ISO date/time string ('' when missing) - what and the form payload use. */ +export const isoDay = (v: string | null | undefined) => (v ? v.slice(0, 10) : ''); diff --git a/web/src/features/grains-registry/meta/drivers.ts b/web/src/features/grains-registry/meta/drivers.ts new file mode 100644 index 0000000..e1ee682 --- /dev/null +++ b/web/src/features/grains-registry/meta/drivers.ts @@ -0,0 +1,67 @@ +import type { FormMeta, GridMeta, OptionItem } from '@/components/meta/types'; +import { GRID_DRIVERS, nationalityOptions } from '../api'; +import type { DriverRow } from '../types'; +import { DIGITS_ONLY, lbl, NO_SPECIAL, registryStatuses } from './common'; + +/** Legacy driverGrid.cfm / getDriverGrid. */ +export function driverGrid(h: { onOpen: (r: DriverRow) => void }): GridMeta { + return { + key: GRID_DRIVERS, + endpoint: '/grains/registry/drivers', + rowKey: (r) => r.id, + // registration lists are large: nothing is loaded until the user picks a filter (status chip or any search field) + requireFilter: true, + onRowClick: h.onOpen, + status: { param: 'statusCode', options: registryStatuses }, + filters: [ + { name: 'nnpn', type: 'text', label: lbl('National no. / passport', 'الرقم الوطني / الجواز'), ltr: true }, + { name: 'name', type: 'text', label: lbl('Name', 'الاسم') }, + ], + columns: [ + { key: 'nnpn', header: lbl('National no. / passport', 'الرقم الوطني / الجواز'), ltr: true }, + { key: 'name', header: lbl('Name', 'الاسم') }, + { key: 'dln', header: lbl('License no.', 'رقم الرخصة'), ltr: true, hideBelow: 'sm' }, + { key: 'dled', header: lbl('License expiry', 'انتهاء الرخصة'), format: 'date', ltr: true, hideBelow: 'md' }, + { key: 'compName', header: lbl('Company', 'الشركة'), hideBelow: 'md' }, + { key: 'createTimestamp', header: lbl('Created on', 'تاريخ الإنشاء'), format: 'datetime', ltr: true, hideBelow: 'lg' }, + { key: 'createUserId', header: lbl('Created by', 'أنشئ بواسطة'), hideBelow: 'lg' }, + { key: 'statusCode', header: lbl('Status', 'الحالة'), format: 'status', statuses: registryStatuses }, + ], + }; +} + +/** Driving licence categories 1..6 (the backend accepts a single digit 1-6). */ +const categoryOptions: OptionItem[] = ['1', '2', '3', '4', '5', '6'].map((v) => ({ value: v, label: v })); + +/** regesterDriver.cfm saveDriverDetails: every field but the second mobile is required; two documents are mandatory on create. */ +export function driverForm(o: { isCreate: boolean }): FormMeta { + return { + key: 'grains.registry.driverForm', + sections: [ + { + key: 'driver', + title: lbl('Driver information', 'معلومات السائق'), + columns: 2, + fields: [ + { + name: 'nnpn', type: 'text', label: lbl('National no. / passport', 'الرقم الوطني / الجواز'), required: true, maxLength: 20, + ltr: true, pattern: NO_SPECIAL, readOnly: !o.isCreate, + }, + { name: 'name', type: 'text', label: lbl('Driver name', 'اسم السائق'), required: true, maxLength: 50, pattern: NO_SPECIAL }, + { name: 'nat', type: 'select', label: lbl('Nationality', 'الجنسية'), required: true, options: nationalityOptions }, + { + name: 'dln', type: 'text', label: lbl('Driving licence no.', 'رقم رخصة القيادة'), required: true, inputKind: 'code', + maxLength: 9, pattern: DIGITS_ONLY(9), + }, + { name: 'dled', type: 'date', label: lbl('Licence expiry', 'تاريخ انتهاء الرخصة'), required: true }, + { name: 'cat', type: 'select', label: lbl('Licence category', 'فئة الرخصة'), required: true, options: categoryOptions }, + { + name: 'mobile1', type: 'text', label: lbl('Mobile', 'رقم الهاتف'), required: true, inputKind: 'phone', maxLength: 10, + pattern: DIGITS_ONLY(10), + }, + { name: 'mobile2', type: 'text', label: lbl('Second mobile', 'رقم هاتف آخر'), inputKind: 'phone', maxLength: 10, pattern: DIGITS_ONLY(10) }, + ], + }, + ], + }; +} diff --git a/web/src/features/grains-registry/meta/trailers.ts b/web/src/features/grains-registry/meta/trailers.ts new file mode 100644 index 0000000..9045a34 --- /dev/null +++ b/web/src/features/grains-registry/meta/trailers.ts @@ -0,0 +1,85 @@ +import type { FormMeta, GridMeta, Rule } from '@/components/meta/types'; +import { axialsOptions, companyOptions, GRID_TRAILERS } from '../api'; +import type { TrailerRow } from '../types'; +import { DIGITS_ONLY, isBadiya, lbl, NO_SPECIAL, registryStatuses, trailerKindOptions } from './common'; + +/** Legacy trailerGrid.cfm / getTrailerGrid. */ +export function trailerGrid(h: { isCompanyUser: boolean; onOpen: (r: TrailerRow) => void }): GridMeta { + return { + key: GRID_TRAILERS, + endpoint: '/grains/registry/trailers', + rowKey: (r) => r.id, + // registration lists are large: nothing is loaded until the user picks a filter (status chip or any search field) + requireFilter: true, + onRowClick: h.onOpen, + status: { param: 'statusCode', options: registryStatuses }, + filters: [ + { name: 'tn', type: 'text', label: lbl('Trailer number', 'رقم المقطورة'), inputKind: 'plate' }, + { name: 'chasesNumber', type: 'text', label: lbl('Chassis number', 'رقم الشصي'), ltr: true }, + ...(h.isCompanyUser ? [] : [{ name: 'tcscac', type: 'select' as const, label: lbl('Company', 'الشركة'), options: companyOptions }]), + ], + columns: [ + { key: 'tn', header: lbl('Number', 'الرقم'), ltr: true }, + { key: 'chasesNumber', header: lbl('Chassis number', 'رقم الشصي'), ltr: true, hideBelow: 'sm' }, + { key: 'compName', header: lbl('Company', 'الشركة'), hideBelow: 'md' }, + { key: 'ownerName', header: lbl('Owner', 'المالك'), hideBelow: 'lg' }, + { key: 'regDate', header: lbl('License expiry', 'انتهاء الترخيص'), format: 'date', ltr: true, hideBelow: 'lg' }, + { key: 'createTimestamp', header: lbl('Created on', 'تاريخ الإنشاء'), format: 'datetime', ltr: true, hideBelow: 'lg' }, + { key: 'statusCode', header: lbl('Status', 'الحالة'), format: 'status', statuses: registryStatuses }, + ], + }; +} + +export interface TrailerFormOptions { + isEdit: boolean; + companyLocked: boolean; +} + +/** + * registerGrainsTrailer.cfm: company 327 on create and every company on edit require the full data set; + * two documents are required in the same cases (counting the stored ones on edit). + */ +export function trailerForm(o: TrailerFormOptions): FormMeta { + const full: Rule = o.isEdit ? { field: 'tcscac', op: 'notEmpty' } : isBadiya; + return { + key: 'grains.registry.trailerForm', + sections: [ + { + key: 'trailer', + title: lbl('Trailer information', 'معلومات المقطورة'), + columns: 2, + fields: [ + { + name: 'tn', type: 'text', label: lbl('Trailer number', 'رقم المقطورة'), required: true, inputKind: 'plate', maxLength: 12, + pattern: DIGITS_ONLY(12), readOnly: o.isEdit, + }, + { + name: 'tcscac', type: 'select', label: lbl('Company', 'الشركة'), required: true, options: companyOptions, + disabledWhen: o.isEdit || o.companyLocked ? { field: 'tcscac', op: 'notEmpty' } : undefined, + }, + { name: 'chasesNumber', type: 'text', label: lbl('Chassis number', 'رقم الشصي'), requiredWhen: full, maxLength: 20, ltr: true, pattern: NO_SPECIAL }, + { name: 'regDate', type: 'date', label: lbl('License expiry', 'تاريخ انتهاء الترخيص'), requiredWhen: full }, + { name: 'axialsKind', type: 'select', label: lbl('Axial load kind', 'نوع الأحمال المحورية'), options: trailerKindOptions }, + { + name: 'axials', type: 'select', label: lbl('Axial loads', 'الأحمال المحورية'), dependsOn: 'axialsKind', + options: axialsOptions('trailer', (p) => (p ? String(p) : '')), requiredWhen: full, + helper: lbl('Choose the kind first.', 'اختر النوع أولاً.'), + }, + ], + }, + { + key: 'owner', + title: lbl('Owner', 'المالك'), + columns: 2, + fields: [ + { name: 'ownerName', type: 'text', label: lbl('Owner name', 'اسم المالك'), requiredWhen: full, maxLength: 50, pattern: NO_SPECIAL }, + { + name: 'ownerNnpn', type: 'text', label: lbl('Owner national no. / passport', 'الرقم الوطني / الجواز للمالك'), + requiredWhen: full, maxLength: 20, ltr: true, pattern: NO_SPECIAL, + }, + { name: 'phoneNumber', type: 'text', label: lbl('Owner phone', 'رقم هاتف المالك'), inputKind: 'phone', maxLength: 10, pattern: DIGITS_ONLY(10) }, + ], + }, + ], + }; +} diff --git a/web/src/features/grains-registry/meta/trucks.ts b/web/src/features/grains-registry/meta/trucks.ts new file mode 100644 index 0000000..5c56104 --- /dev/null +++ b/web/src/features/grains-registry/meta/trucks.ts @@ -0,0 +1,118 @@ +import type { FormMeta, GridMeta } from '@/components/meta/types'; +import { axialsOptions, companyOptions, GRID_TRUCKS } from '../api'; +import type { TrailerRow, TruckRow } from '../types'; +import { + colorOptions, DIGITS_ONLY, headTypeOptions, isBadiya, lbl, manufactureYearPattern, modelOptions, NO_SPECIAL, + registryStatuses, truckKindOptions, +} from './common'; + +/** Legacy truckGrid.cfm / getTruckGrid (searchType TN = trucks, TRN = trailers table, rows carry tnId). */ +export function truckGrid(h: { isCompanyUser: boolean; onOpen: (r: TruckRow) => void }): GridMeta { + return { + key: GRID_TRUCKS, + endpoint: '/grains/registry/trucks', + rowKey: (r) => `${r.entityType}-${r.id}`, + // registration lists are large: nothing is loaded until the user picks a filter (status chip or any search field) + requireFilter: true, + onRowClick: h.onOpen, + status: { param: 'statusCode', options: registryStatuses }, + filters: [ + { name: 'tn', type: 'text', label: lbl('Number', 'الرقم'), inputKind: 'plate' }, + { name: 'chasesNumber', type: 'text', label: lbl('Chassis number', 'رقم الشصي'), ltr: true }, + { name: 'headType', type: 'select', label: lbl('Truck type', 'نوع الشاحنة'), options: [ + { value: 'Trella', label: lbl('Trailer head', 'تريلا') }, + { value: 'Tripper', label: lbl('Tipper', 'قلاب') }, + { value: 'Single', label: lbl('Single', 'سنجل') }, + ] }, + ...(h.isCompanyUser ? [] : [{ name: 'tcscac', type: 'select' as const, label: lbl('Company', 'الشركة'), options: companyOptions }]), + ], + columns: [ + { key: 'tn', header: lbl('Number', 'الرقم'), ltr: true }, + { key: 'chasesNumber', header: lbl('Chassis number', 'رقم الشصي'), ltr: true, hideBelow: 'sm' }, + { key: 'compName', header: lbl('Company', 'الشركة'), hideBelow: 'md' }, + { key: 'regDate', header: lbl('License expiry', 'انتهاء الترخيص'), format: 'date', ltr: true, hideBelow: 'lg' }, + { key: 'createTimestamp', header: lbl('Created on', 'تاريخ الإنشاء'), format: 'datetime', ltr: true, hideBelow: 'lg' }, + { key: 'createUserId', header: lbl('Created by', 'أنشئ بواسطة'), hideBelow: 'lg' }, + { key: 'statusCode', header: lbl('Status', 'الحالة'), format: 'status', statuses: registryStatuses }, + ], + }; +} + +/** Small read-only grid of the trailers connected to a truck (legacy getTrailerGrid of the truck page). */ +export const connectedTrailerColumns = (): GridMeta['columns'] => [ + { key: 'tn', header: lbl('Trailer', 'المقطورة'), ltr: true }, + { key: 'chasesNumber', header: lbl('Chassis number', 'رقم الشصي'), ltr: true, hideBelow: 'sm' }, + { key: 'regDate', header: lbl('License expiry', 'انتهاء الترخيص'), format: 'date', ltr: true, hideBelow: 'md' }, + { key: 'statusCode', header: lbl('Status', 'الحالة'), format: 'status', statuses: registryStatuses }, +]; + +export interface TruckFormOptions { + /** Edit of an existing truck: number and company are fixed, axials/year become required for every company. */ + isEdit: boolean; + /** Company users register for their own company (the select is locked). */ + companyLocked: boolean; +} + +/** + * registerGrainsTruck.cfm: company 327 requires the full data set; the other companies only number + company + * (on edit also axial loads and a valid manufacture year). The phone box is only editable for company 327 on edit. + */ +export function truckForm(o: TruckFormOptions): FormMeta { + const full = o.isEdit ? undefined : isBadiya; + const editReq = o.isEdit ? { field: 'tcscac', op: 'notEmpty' as const } : undefined; + return { + key: 'grains.registry.truckForm', + sections: [ + { + key: 'truck', + title: lbl('Truck information', 'معلومات القاطرة'), + columns: 2, + fields: [ + { + name: 'tn', type: 'text', label: lbl('Truck number', 'رقم القاطرة'), required: true, inputKind: 'plate', maxLength: 12, + pattern: DIGITS_ONLY(12), readOnly: o.isEdit, + }, + { + name: 'tcscac', type: 'select', label: lbl('Company', 'الشركة'), required: true, options: companyOptions, + disabledWhen: o.isEdit || o.companyLocked ? { field: 'tcscac', op: 'notEmpty' } : undefined, + }, + { name: 'chasesNumber', type: 'text', label: lbl('Chassis number', 'رقم الشصي'), requiredWhen: isBadiya, maxLength: 20, ltr: true, pattern: NO_SPECIAL }, + { name: 'regDate', type: 'date', label: lbl('License expiry', 'تاريخ انتهاء الترخيص'), requiredWhen: isBadiya }, + { name: 'color', type: 'select', label: lbl('Colour', 'اللون'), requiredWhen: isBadiya, options: colorOptions }, + { name: 'model', type: 'select', label: lbl('Model', 'الموديل'), requiredWhen: isBadiya, options: modelOptions }, + { + name: 'axialsKind', type: 'select', label: lbl('Axial load kind', 'نوع الأحمال المحورية'), options: truckKindOptions, + requiredWhen: editReq ?? full, + }, + { + name: 'axials', type: 'select', label: lbl('Axial loads', 'الأحمال المحورية'), dependsOn: 'axialsKind', + options: axialsOptions('truck', (p) => (p ? String(p) : '')), + requiredWhen: o.isEdit ? { field: 'tcscac', op: 'notEmpty' } : isBadiya, + helper: lbl('Choose the kind first.', 'اختر النوع أولاً.'), + }, + { + name: 'manifactureYear', type: 'text', label: lbl('Manufacture year', 'سنة الصنع'), inputKind: 'code', maxLength: 4, + pattern: manufactureYearPattern(), requiredWhen: o.isEdit ? { field: 'tcscac', op: 'notEmpty' } : isBadiya, + }, + { name: 'headType', type: 'select', label: lbl('Truck type', 'نوع الشاحنة'), requiredWhen: isBadiya, options: headTypeOptions }, + ], + }, + { + key: 'owner', + title: lbl('Owner', 'المالك'), + columns: 2, + fields: [ + { name: 'ownerName', type: 'text', label: lbl('Owner name', 'اسم المالك'), requiredWhen: isBadiya, maxLength: 50, pattern: NO_SPECIAL }, + { + name: 'ownerNnpn', type: 'text', label: lbl('Owner national no. / passport', 'الرقم الوطني / الجواز للمالك'), + requiredWhen: isBadiya, maxLength: 20, ltr: true, pattern: NO_SPECIAL, + }, + { + name: 'phoneNumber', type: 'text', label: lbl('Owner phone', 'رقم هاتف المالك'), inputKind: 'phone', maxLength: 10, pattern: DIGITS_ONLY(10), + disabledWhen: o.isEdit ? { not: isBadiya } : undefined, + }, + ], + }, + ], + }; +} diff --git a/web/src/features/grains-registry/pages.tsx b/web/src/features/grains-registry/pages.tsx new file mode 100644 index 0000000..e686549 --- /dev/null +++ b/web/src/features/grains-registry/pages.tsx @@ -0,0 +1,628 @@ +import { useEffect, useMemo, useState } from 'react'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { + Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, Paper, Stack, Table, TableBody, TableCell, TableContainer, + TableHead, TableRow, TextField, Typography, +} from '@mui/material'; +import AddIcon from '@mui/icons-material/Add'; +import BlockIcon from '@mui/icons-material/Block'; +import CheckCircleIcon from '@mui/icons-material/CheckCircle'; +import type { ApiError } from '@/api/client'; +import { DataGrid, gridReturnUrl } from '@/components/DataGrid'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { MetaForm } from '@/components/MetaForm'; +import { PageHeader } from '@/components/PageHeader'; +import { StatusChip } from '@/components/StatusChip'; +import { formatDate, formatNumber } from '@/components/meta/format'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { + useAddBlacklist, useCancelBlacklist, useCreateDriver, useCreateTrailer, useCreateTruck, useDestinationOptions, useDriver, + useDriverAction, useLocationTruckCounts, usePermissions, useSaveWeighbridge, useTrailer, useTrailerAction, useTruck, + useTruckAction, useTruckTrailers, useUpdateTrailer, useUpdateTruck, +} from './api'; +import { Card, DestinationsPanel, DocumentsSection, num, withDocumentIds, type PendingDoc } from './components'; +import { blacklistForm, blacklistGrid, weighbridgeForm } from './meta/blacklist'; +import { + BADIYA_SCAC, canAcceptStatus, canEditStatus, canRevokeStatus, isoDay, registryStatuses, trailerKindOfAxials, truckKindOfAxials, +} from './meta/common'; +import { driverForm, driverGrid } from './meta/drivers'; +import { trailerForm, trailerGrid } from './meta/trailers'; +import { connectedTrailerColumns, truckForm, truckGrid } from './meta/trucks'; +import strings from './strings'; +import type { BlacklistRow, DestinationSelection, RegistryDestinationOptions, TrailerRow } from './types'; + +const ROOT = '/grains/registry'; + +/** Wait for the permissions of the caller (legacy isActAuthorized buttons) before drawing a page. */ +function usePerms() { + const q = usePermissions(); + return { perms: q.data, loading: q.isLoading }; +} + +/** Accept / revoke buttons of a record, each behind a confirm dialog (legacy confirm + ajax call). */ +function RecordActions(props: { + status: string; canAccept: boolean; canRevoke: boolean; busy?: boolean; + onAccept: () => void; onRevoke: () => void; extra?: React.ReactNode; +}) { + const { t } = useFeatureUi(strings); + const confirm = useConfirm(); + return ( + <> + {props.extra} + {props.canAccept && canAcceptStatus(props.status) && ( + + )} + {props.canRevoke && canRevokeStatus(props.status) && ( + + )} + + ); +} + +function StatusLine({ status }: { status: string }) { + return ; +} + +const fieldErrorsOf = (e: ApiError) => ({ ...e.fieldErrors }) as Record; + +/** Files uploaded in the documents section of a record page, waiting for Save, and the "documents needed" message state. */ +function usePendingDocs() { + const [docs, setDocs] = useState([]); + const [need, setNeed] = useState(undefined); + return { + docs, need, setNeed, + add: (more: PendingDoc[]) => setDocs((p) => [...p, ...more]), + remove: (id: string) => setDocs((p) => p.filter((d) => d.id !== id)), + clear: () => { setDocs([]); setNeed(undefined); }, + }; +} + +/** Splits the stored destination ids into the three check-box groups by the location lists. */ +function splitDestinations(ids: number[] | null | undefined, o: RegistryDestinationOptions | undefined): DestinationSelection { + const out: DestinationSelection = { packed: [], bulk: [], bulkGallab: [] }; + for (const id of ids ?? []) { + if (o?.packed.some((l) => l.id === id)) out.packed.push(id); + else if (o?.bulkGallab.some((l) => l.id === id)) out.bulkGallab.push(id); + else out.bulk.push(id); + } + return out; +} + +// ================================================================= trucks +export function TrucksPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const { perms, loading } = usePerms(); + const meta = useMemo( + () => truckGrid({ + isCompanyUser: perms?.isCompanyUser ?? false, + // a TRN search lists trailers: those rows open the trailer (or their truck when the backend gives its id) + onOpen: (r) => navigate(r.entityType === 'TRN' ? (r.tnId ? `${ROOT}/trucks/${r.tnId}` : `${ROOT}/trailers/${r.id}`) : `${ROOT}/trucks/${r.id}`), + }), + [perms?.isCompanyUser, navigate], + ); + if (loading) return ; + return ( + <> + } onClick={() => navigate(`${ROOT}/trucks/new`)}>{t('reg.trucks.new')} + )} + /> + + + ); +} + +export function TruckPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const params = useParams(); + const id = params.id ? Number(params.id) : null; + const isNew = id === null; + const { perms, loading } = usePerms(); + const truck = useTruck(id); + const trailers = useTruckTrailers(id); + const create = useCreateTruck(); + const update = useUpdateTruck(id ?? 0); + const action = useTruckAction(); + const [serverErrors, setServerErrors] = useState>({}); + const [dests, setDests] = useState({ packed: [], bulk: [], bulkGallab: [] }); + const pending = usePendingDocs(); + + const t0 = truck.data; + const showDestinations = !!perms?.canManageDestinations && (isNew ? !perms.isCompanyUser || perms.companyCodeNo === BADIYA_SCAC : t0?.tcscac === BADIYA_SCAC); + const destOptions = useDestinationOptions(showDestinations); + useEffect(() => { if (t0) setDests(splitDestinations(t0.destinationIds, destOptions.data)); }, [t0, destOptions.data]); + + const canEdit = isNew || (!!perms?.canEditTruck && !!t0 && canEditStatus(t0.statusCode)); + const meta = useMemo( + () => truckForm({ isEdit: !isNew, companyLocked: !!perms?.isCompanyUser }), + [isNew, perms?.isCompanyUser], + ); + const initial = useMemo(() => { + if (!t0) return perms?.isCompanyUser && perms.companyCodeNo ? { tcscac: perms.companyCodeNo } : {}; + return { + tn: t0.tn, tcscac: t0.tcscac, chasesNumber: t0.chasesNumber, regDate: isoDay(t0.regDate), color: t0.color, model: t0.model, + axialsKind: t0.axialsKind ?? truckKindOfAxials(t0.axials), axials: t0.axials, manifactureYear: t0.manifactureYear, + headType: t0.headType, ownerName: t0.ownerName, ownerNnpn: t0.ownerNnpn, phoneNumber: t0.phoneNumber, + }; + }, [t0, perms?.isCompanyUser, perms?.companyCodeNo]); + + if (loading || (!isNew && truck.isLoading)) return ; + if (!isNew && !t0) return {truck.error?.message ?? t('reg.loadFailed')}; + if (isNew && !perms?.canAddTruck) return {t('reg.forbidden')}; + + const submit = (payload: Record) => + new Promise((resolve) => { + setServerErrors({}); + const { axialsKind: _kind, ...rest } = payload; + void _kind; + const body = withDocumentIds({ + ...rest, tcscac: num(rest.tcscac), axials: num(rest.axials), + ...(showDestinations ? { destinations: dests } : {}), + }, pending.docs); + const mutation = isNew ? create : update; + mutation.mutate(body, { + onSuccess: (res) => { pending.clear(); resolve(); if (isNew && res.id) navigate(`${ROOT}/trucks/${res.id}`, { replace: true }); }, + onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); }, + }); + }); + + return ( + + } + backTo={`${ROOT}/trucks`} + actions={ + <> + {!isNew && t0 && ( + action.mutate({ id: t0.id, action: 'accept' })} + onRevoke={() => action.mutate({ id: t0.id, action: 'revoke' })} + extra={perms?.canAddTrailer && canEditStatus(t0.statusCode) && (trailers.data?.length ?? 0) === 0 && ( + + )} + /> + )} + + } + /> + {!isNew && t0 && !canEdit && ( + {canEditStatus(t0.statusCode) ? t('reg.readOnlyNoRight') : t('reg.revokedLocked')} + )} + {!isNew && t0?.lastUpdateUserId && ( + + {t('reg.trucks.lastUpdate', { user: t0.lastUpdateUserId, time: formatDate(t0.lastUpdateTimestamp) })} + + )} + navigate(gridReturnUrl(`${ROOT}/trucks`))} + onSubmit={submit} + > + + {showDestinations && canEdit && ( + + )} + + {!isNew && t0 && } + + ); +} + +function ConnectedTrailers({ rows, loading }: { rows: TrailerRow[]; loading: boolean }) { + const { t, tr, lang } = useFeatureUi(strings); + const navigate = useNavigate(); + const columns = useMemo(() => connectedTrailerColumns(), []); + return ( + + {loading ? : rows.length === 0 ? ( + {t('reg.trucks.noTrailers')} + ) : ( + + + + {columns.map((c) => {tr(c.header)})} + + + {rows.map((r) => ( + navigate(`${ROOT}/trailers/${r.id}`)}> + {r.tn} + {r.chasesNumber} + {formatDate(r.regDate, lang)} + + + ))} + +
+
+ )} +
+ ); +} + +// ================================================================= trailers +export function TrailersPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const { perms, loading } = usePerms(); + const meta = useMemo( + () => trailerGrid({ isCompanyUser: perms?.isCompanyUser ?? false, onOpen: (r) => navigate(`${ROOT}/trailers/${r.id}`) }), + [perms?.isCompanyUser, navigate], + ); + if (loading) return ; + return ( + <> + } onClick={() => navigate(`${ROOT}/trailers/new`)}>{t('reg.trailers.new')} + )} + /> + + + ); +} + +export function TrailerPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const params = useParams(); + const [sp] = useSearchParams(); + const id = params.id ? Number(params.id) : null; + const truckId = sp.get('truckId') ? Number(sp.get('truckId')) : null; + const isNew = id === null; + const { perms, loading } = usePerms(); + const trailer = useTrailer(id); + const parentTruck = useTruck(isNew ? truckId : null); + const create = useCreateTrailer(); + const update = useUpdateTrailer(id ?? 0); + const action = useTrailerAction(); + const [serverErrors, setServerErrors] = useState>({}); + const toast = useToast(); + const pending = usePendingDocs(); + + const d = trailer.data; + const canEdit = isNew || (!!perms?.canEditTrailer && !!d && canEditStatus(d.statusCode)); + const meta = useMemo( + () => trailerForm({ isEdit: !isNew, companyLocked: !!perms?.isCompanyUser }), + [isNew, perms?.isCompanyUser], + ); + const initial = useMemo(() => { + if (!d) { + const scac = parentTruck.data?.tcscac ?? (perms?.isCompanyUser ? perms.companyCodeNo : null); + return scac ? { tcscac: scac } : {}; + } + return { + tn: d.tn, tcscac: d.tcscac, chasesNumber: d.chasesNumber, regDate: isoDay(d.regDate), + axialsKind: d.axialsKind ?? trailerKindOfAxials(d.axials), axials: d.axials, ownerName: d.ownerName, ownerNnpn: d.ownerNnpn, + phoneNumber: d.phoneNumber, + }; + }, [d, parentTruck.data?.tcscac, perms?.isCompanyUser, perms?.companyCodeNo]); + + if (loading || (!isNew && trailer.isLoading) || (isNew && truckId !== null && parentTruck.isLoading)) return ; + if (!isNew && !d) return {trailer.error?.message ?? t('reg.loadFailed')}; + if (isNew && !perms?.canAddTrailer) return {t('reg.forbidden')}; + + const submit = (payload: Record) => + new Promise((resolve) => { + setServerErrors({}); + const { axialsKind: _kind, ...rest } = payload; + void _kind; + // legacy: two documents are needed when a Badiya trailer is registered, and on every edit at least two must exist afterwards + const needDocs = isNew ? (num(rest.tcscac) === BADIYA_SCAC ? 2 : 0) : 2; + if ((d?.attachments.length ?? 0) + pending.docs.length < needDocs) { + pending.setNeed(needDocs); + toast.warning(t('reg.docs.required', { n: needDocs })); + resolve(); + return; + } + const body = withDocumentIds({ + ...rest, tcscac: num(rest.tcscac), axials: num(rest.axials), ...(isNew && truckId ? { truckId } : {}), + }, pending.docs); + const mutation = isNew ? create : update; + mutation.mutate(body, { + onSuccess: (res) => { + pending.clear(); + resolve(); + if (isNew) navigate(truckId ? `${ROOT}/trucks/${truckId}` : res.id ? `${ROOT}/trailers/${res.id}` : `${ROOT}/trailers`, { replace: true }); + }, + onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); }, + }); + }); + + return ( + + } + backTo={truckId ? `${ROOT}/trucks/${truckId}` : `${ROOT}/trailers`} + actions={ + <> + {!isNew && d && ( + action.mutate({ id: d.id, action: 'accept' })} + onRevoke={() => action.mutate({ id: d.id, action: 'revoke' })} + extra={d.truckId && ( + + )} + /> + )} + + } + /> + {isNew && parentTruck.data && {t('reg.trailers.forTruck', { tn: parentTruck.data.tn })}} + {!isNew && d && !canEdit && ( + {canEditStatus(d.statusCode) ? t('reg.readOnlyNoRight') : t('reg.revokedLocked')} + )} + navigate(truckId ? `${ROOT}/trucks/${truckId}` : gridReturnUrl(`${ROOT}/trailers`))} + onSubmit={submit} + > + + + + ); +} + +// ================================================================= drivers +export function DriversPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const { perms, loading } = usePerms(); + const meta = useMemo(() => driverGrid({ onOpen: (r) => navigate(`${ROOT}/drivers/${r.id}`) }), [navigate]); + if (loading) return ; + return ( + <> + } onClick={() => navigate(`${ROOT}/drivers/new`)}>{t('reg.drivers.new')} + )} + /> + + + ); +} + +export function DriverPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const params = useParams(); + const id = params.id ? Number(params.id) : null; + const isNew = id === null; + const { perms, loading } = usePerms(); + const driver = useDriver(id); + const create = useCreateDriver(); + const action = useDriverAction(); + const [serverErrors, setServerErrors] = useState>({}); + const toast = useToast(); + const pending = usePendingDocs(); + const d = driver.data; + const meta = useMemo(() => driverForm({ isCreate: isNew }), [isNew]); + const initial = useMemo( + () => (d ? { nnpn: d.nnpn, name: d.name, nat: d.nat, dln: d.dln, dled: isoDay(d.dled), cat: d.cat, mobile1: d.mobile1, mobile2: d.mobile2 } : {}), + [d], + ); + + if (loading || (!isNew && driver.isLoading)) return ; + if (!isNew && !d) return {driver.error?.message ?? t('reg.loadFailed')}; + if (isNew && !perms?.canAddDriver) return {t('reg.forbidden')}; + + const submit = (payload: Record) => + new Promise((resolve) => { + setServerErrors({}); + // legacy: the driving licence and the ID / passport are both required to register a driver + if (pending.docs.length < 2) { + pending.setNeed(2); + toast.warning(t('reg.docs.required', { n: 2 })); + resolve(); + return; + } + create.mutate(withDocumentIds({ ...payload, nat: payload.nat === null ? null : String(payload.nat), cat: payload.cat === null ? null : String(payload.cat) }, pending.docs), { + onSuccess: (res) => { pending.clear(); resolve(); navigate(res.id ? `${ROOT}/drivers/${res.id}` : `${ROOT}/drivers`, { replace: true }); }, + onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); }, + }); + }); + + return ( + + : undefined} + backTo={`${ROOT}/drivers`} + actions={!isNew && d && ( + action.mutate({ id: d.id, action: 'accept' })} + onRevoke={() => action.mutate({ id: d.id, action: 'revoke' })} + /> + )} + /> + {!isNew && {t('reg.drivers.noEdit')}} + navigate(gridReturnUrl(`${ROOT}/drivers`))} + onSubmit={submit} + > + + + + ); +} + +// ================================================================= blacklist +export function BlacklistPage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const { perms, loading } = usePerms(); + const cancel = useCancelBlacklist(); + const [target, setTarget] = useState(null); + const [remarks, setRemarks] = useState(''); + const confirm = useConfirm(); + const meta = useMemo( + () => blacklistGrid({ canCancel: !!perms?.canCancelBlacklist, onCancel: (r) => { setTarget(r); setRemarks(''); } }), + [perms?.canCancelBlacklist], + ); + if (loading) return ; + + async function save() { + if (!target || !remarks.trim()) return; + if (!(await confirm({ message: t('reg.bl.cancelConfirm'), danger: true }))) return; + cancel.mutate({ id: target.id, remarks: remarks.trim() }, { onSuccess: () => setTarget(null) }); + } + + return ( + <> + } onClick={() => navigate(`${ROOT}/blacklist/new`)}>{t('reg.bl.new')}} + /> + + setTarget(null)} fullWidth maxWidth="xs"> + {t('reg.bl.cancelTitle')} + + + {target?.entityNumber} + setRemarks(e.target.value)} slotProps={{ htmlInput: { maxLength: 400 } }} + error={remarks.length > 0 && !remarks.trim()} required + /> + + + + + + + + + ); +} + +export function BlacklistCreatePage() { + const { t } = useFeatureUi(strings); + const navigate = useNavigate(); + const add = useAddBlacklist(); + const meta = useMemo(() => blacklistForm(), []); + const [serverErrors, setServerErrors] = useState>({}); + return ( + <> + + navigate(gridReturnUrl(`${ROOT}/blacklist`))} + onSubmit={(p) => + new Promise((resolve) => { + setServerErrors({}); + add.mutate( + { ...p, entityType: 'PERMIT', isId: false, expiryDays: Number(p.expiryDays) }, + { onSuccess: () => { resolve(); navigate(`${ROOT}/blacklist`); }, onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); } }, + ); + })} + /> + + ); +} + +// ================================================================= weighbridge control +export function WeighbridgeControlPage() { + const { t } = useFeatureUi(strings); + const save = useSaveWeighbridge(); + const meta = useMemo(() => weighbridgeForm(), []); + const [serverErrors, setServerErrors] = useState>({}); + const [version, setVersion] = useState(0); + return ( + <> + + + new Promise((resolve) => { + setServerErrors({}); + save.mutate( + { ...p, locationId: num(p.locationId) }, + { onSuccess: () => { resolve(); setVersion((v) => v + 1); }, onError: (e) => { setServerErrors(fieldErrorsOf(e)); resolve(); } }, + ); + })} + /> + + ); +} + +// ================================================================= trucks per location (locTruckNumGrid) +export function LocationCountsPage() { + const { t, lang } = useFeatureUi(strings); + const q = useLocationTruckCounts(); + const rows = q.data ?? []; + const total = rows.reduce((s, r) => s + r.cnt, 0); + return ( + <> + + {q.isLoading ? : q.error ? {q.error.message} : ( + + + + + {t('reg.lc.location')} + {t('reg.lc.count')} + + + + {rows.map((r, i) => ( + + {r.loc} + {formatNumber(r.cnt, lang)} + + ))} + + {t('reg.lc.total')} + {formatNumber(total, lang)} + + +
+
+ )} + + ); +} diff --git a/web/src/features/grains-registry/routes.tsx b/web/src/features/grains-registry/routes.tsx new file mode 100644 index 0000000..3bc0ce6 --- /dev/null +++ b/web/src/features/grains-registry/routes.tsx @@ -0,0 +1,59 @@ +import type { RouteObject } from 'react-router-dom'; +import BadgeIcon from '@mui/icons-material/Badge'; +import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings'; +import BlockIcon from '@mui/icons-material/Block'; +import LocalShippingIcon from '@mui/icons-material/LocalShipping'; +import PinDropIcon from '@mui/icons-material/PinDrop'; +import RvHookupIcon from '@mui/icons-material/RvHookup'; +import ScaleIcon from '@mui/icons-material/Scale'; +import type { MenuItem } from '@/shell/types'; +import { + BlacklistCreatePage, BlacklistPage, DriverPage, DriversPage, LocationCountsPage, TrailerPage, TrailersPage, TruckPage, TrucksPage, + WeighbridgeControlPage, +} from './pages'; +import strings from './strings'; + +/** + * Grains "registry" slice: trucks, trailers, drivers, blacklist, weighbridge exceptions, trucks per location. + * Legacy role gating is done by the backend (isActAuthorized action ids); pages hide the buttons the caller may not use. + */ +export const routes: RouteObject[] = [ + { path: '/grains/registry/trucks', element: }, + { path: '/grains/registry/trucks/new', element: , handle: { crumb: strings['reg.crumb.new'] } }, + { path: '/grains/registry/trucks/:id', element: , handle: { crumb: strings['reg.crumb.details'] } }, + { path: '/grains/registry/trailers', element: }, + { path: '/grains/registry/trailers/new', element: , handle: { crumb: strings['reg.crumb.new'] } }, + { path: '/grains/registry/trailers/:id', element: , handle: { crumb: strings['reg.crumb.details'] } }, + { path: '/grains/registry/drivers', element: }, + { path: '/grains/registry/drivers/new', element: , handle: { crumb: strings['reg.crumb.new'] } }, + { path: '/grains/registry/drivers/:id', element: , handle: { crumb: strings['reg.crumb.details'] } }, + { path: '/grains/registry/blacklist', element: }, + { path: '/grains/registry/blacklist/new', element: , handle: { crumb: strings['reg.crumb.new'] } }, + { path: '/grains/registry/weighbridge-control', element: }, + { path: '/grains/registry/location-counts', element: }, +]; + +export const menu: MenuItem[] = [ + { + key: 'grains.registry', + title: strings['reg.menu.group'], + icon: LocalShippingIcon, + children: [ + { key: 'grains.registry.trucks', title: strings['reg.menu.trucks'], icon: LocalShippingIcon, path: '/grains/registry/trucks', createPath: '/grains/registry/trucks/new', createKey: 'grains.registry.trucks.create' }, + { key: 'grains.registry.trailers', title: strings['reg.menu.trailers'], icon: RvHookupIcon, path: '/grains/registry/trailers', createPath: '/grains/registry/trailers/new', createKey: 'grains.registry.trailers.create' }, + { key: 'grains.registry.drivers', title: strings['reg.menu.drivers'], icon: BadgeIcon, path: '/grains/registry/drivers', createPath: '/grains/registry/drivers/new', createKey: 'grains.registry.drivers.create' }, + { key: 'grains.registry.locationCounts', title: strings['reg.menu.locationCounts'], icon: PinDropIcon, path: '/grains/registry/location-counts' }, + ], + }, + // Its own menu (not under the fleet registry). Each entry is available only to the roles that have its key in GRAINS_SCREEN_PERMISSIONS. + { + key: 'grains.control', + title: strings['reg.menu.controlGroup'], + icon: AdminPanelSettingsIcon, + children: [ + { key: 'grains.registry.blacklist', title: strings['reg.menu.blacklist'], icon: BlockIcon, path: '/grains/registry/blacklist', createPath: '/grains/registry/blacklist/new' }, + { key: 'grains.registry.weighbridge', title: strings['reg.menu.weighbridge'], icon: ScaleIcon, path: '/grains/registry/weighbridge-control' }, + ], + }, +]; + diff --git a/web/src/features/grains-registry/strings.ts b/web/src/features/grains-registry/strings.ts new file mode 100644 index 0000000..d6455ff --- /dev/null +++ b/web/src/features/grains-registry/strings.ts @@ -0,0 +1,118 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** Feature strings of the Grains "registry" slice (trucks, trailers, drivers, blacklist, weighbridge control). */ +export default defineStrings({ + // ---- menu + 'reg.menu.group': { en: 'Fleet registry', ar: 'سجل الأسطول' }, + 'reg.menu.controlGroup': { en: 'Restrictions and weighbridge', ar: 'المنع وضبط الميزان' }, + 'reg.menu.trucks': { en: 'Trucks', ar: 'القاطرات' }, + 'reg.menu.trailers': { en: 'Trailers', ar: 'المقطورات' }, + 'reg.menu.drivers': { en: 'Drivers', ar: 'السائقون' }, + 'reg.menu.blacklist': { en: 'Blacklist', ar: 'قائمة المنع' }, + 'reg.menu.weighbridge': { en: 'Weighbridge control', ar: 'ضبط الميزان' }, + 'reg.menu.locationCounts': { en: 'Trucks per location', ar: 'عدد الشاحنات حسب الموقع' }, + 'reg.crumb.new': { en: 'New', ar: 'جديد' }, + 'reg.crumb.details': { en: 'Details', ar: 'التفاصيل' }, + + // ---- shared + 'reg.forbidden': { en: 'You are not allowed to use this page.', ar: 'غير مصرح لك باستخدام هذه الصفحة.' }, + 'reg.status.open': { en: 'New', ar: 'جديد' }, + 'reg.status.accpt': { en: 'Licensed', ar: 'مرخص' }, + 'reg.status.rvkd': { en: 'Revoked', ar: 'ملغي' }, + 'reg.status.regreqst': { en: 'Awaiting registration', ar: 'بانتظار التسجيل' }, + 'reg.status.incomp': { en: 'Incomplete', ar: 'غير مكتمل' }, + 'reg.status': { en: 'Status', ar: 'الحالة' }, + 'reg.accept': { en: 'Activate', ar: 'تفعيل' }, + 'reg.revoke': { en: 'Revoke', ar: 'إلغاء' }, + 'reg.acceptConfirm': { en: 'Do you want to activate this record?', ar: 'هل تريد تفعيل هذا السجل؟' }, + 'reg.revokeConfirm': { en: 'Do you want to revoke this record? This cannot be undone.', ar: 'هل تريد إلغاء هذا السجل؟ لا يمكن التراجع عن ذلك.' }, + 'reg.back': { en: 'Back to the list', ar: 'العودة إلى القائمة' }, + 'reg.loadFailed': { en: 'Could not load the record.', ar: 'تعذر تحميل السجل.' }, + 'reg.revokedLocked': { en: 'This record is revoked and can no longer be edited.', ar: 'هذا السجل ملغي ولا يمكن تعديله.' }, + 'reg.readOnlyNoRight': { en: 'You do not have the right to edit this record; it is shown read-only.', ar: 'لا تملك صلاحية تعديل هذا السجل؛ يظهر للقراءة فقط.' }, + + // ---- documents (attachments) + 'reg.trucks.destSelectAll': { en: 'Select all', ar: 'تحديد الكل' }, + 'reg.trucks.destClear': { en: 'Clear', ar: 'إلغاء' }, + 'reg.docs.title': { en: 'Documents', ar: 'المستندات' }, + 'reg.docs.upload': { en: 'Upload document', ar: 'رفع مستند' }, + 'reg.docs.pendingHint': { en: 'Uploaded files are attached when you save.', ar: 'تُرفق الملفات المرفوعة عند الحفظ.' }, + 'reg.docs.required': { en: 'At least {n} documents are required.', ar: 'يجب إرفاق {n} مستندات على الأقل.' }, + 'reg.docs.none': { en: 'No documents attached yet.', ar: 'لا توجد مستندات مرفقة.' }, + 'reg.docs.openFailed': { en: 'Could not open the file.', ar: 'تعذر فتح الملف.' }, + 'reg.docs.vehicleLicense': { en: 'Vehicle license', ar: 'رخصة المركبة' }, + 'reg.docs.ownerId': { en: 'Owner ID', ar: 'هوية المالك' }, + 'reg.docs.driverLicense': { en: 'Driving license', ar: 'رخصة السائق' }, + 'reg.docs.driverId': { en: 'ID / passport', ar: 'الهوية / الجواز' }, + 'reg.docs.helper': { en: 'PDF or image, one file per box.', ar: 'ملف PDF أو صورة، ملف واحد لكل خانة.' }, + + // ---- trucks + 'reg.trucks.title': { en: 'Trucks', ar: 'القاطرات' }, + 'reg.trucks.subtitle': { en: 'Registered tractor units per company', ar: 'القاطرات المسجلة حسب الشركة' }, + 'reg.trucks.new': { en: 'New truck', ar: 'قاطرة جديدة' }, + 'reg.trucks.createTitle': { en: 'Register a truck', ar: 'تسجيل قاطرة' }, + 'reg.trucks.detailTitle': { en: 'Truck {tn}', ar: 'القاطرة {tn}' }, + 'reg.trucks.addTrailer': { en: 'Add trailer', ar: 'إضافة مقطورة' }, + 'reg.trucks.trailers': { en: 'Connected trailers', ar: 'المقطورات المرتبطة' }, + 'reg.trucks.noTrailers': { en: 'No trailer is connected to this truck.', ar: 'لا توجد مقطورة مرتبطة بهذه القاطرة.' }, + 'reg.trucks.destinations': { en: 'Destinations', ar: 'الوجهات' }, + 'reg.trucks.destinationsHint': { en: 'Saved together with the truck.', ar: 'تُحفظ مع القاطرة.' }, + 'reg.trucks.destPacked': { en: 'Packed', ar: 'مشول' }, + 'reg.trucks.destBulk': { en: 'Bulk', ar: 'سائب' }, + 'reg.trucks.destBulkGallab': { en: 'Bulk (tipper)', ar: 'سائب (قلاب)' }, + 'reg.trucks.destPending': { en: 'A destination change by {user} is pending ({time}).', ar: 'يوجد تعديل وجهات معلق من {user} ({time}).' }, + 'reg.trucks.lastUpdate': { en: 'Last update: {user} - {time}', ar: 'آخر تعديل: {user} - {time}' }, + 'reg.trucks.byTrailer': { en: 'Search the trailers table', ar: 'البحث في جدول المقطورات' }, + + // ---- trailers + 'reg.trailers.title': { en: 'Trailers', ar: 'المقطورات' }, + 'reg.trailers.subtitle': { en: 'Registered trailers per company', ar: 'المقطورات المسجلة حسب الشركة' }, + 'reg.trailers.new': { en: 'New trailer', ar: 'مقطورة جديدة' }, + 'reg.trailers.createTitle': { en: 'Register a trailer', ar: 'تسجيل مقطورة' }, + 'reg.trailers.detailTitle': { en: 'Trailer {tn}', ar: 'المقطورة {tn}' }, + 'reg.trailers.forTruck': { en: 'The trailer will be connected to truck {tn}.', ar: 'ستُربط المقطورة بالقاطرة {tn}.' }, + 'reg.trailers.openTruck': { en: 'Open the truck', ar: 'فتح القاطرة' }, + + // ---- drivers + 'reg.drivers.title': { en: 'Drivers', ar: 'السائقون' }, + 'reg.drivers.subtitle': { en: 'Registered drivers per company', ar: 'السائقون المسجلون حسب الشركة' }, + 'reg.drivers.new': { en: 'New driver', ar: 'سائق جديد' }, + 'reg.drivers.createTitle': { en: 'Register a driver', ar: 'تسجيل سائق' }, + 'reg.drivers.detailTitle': { en: 'Driver {name}', ar: 'السائق {name}' }, + 'reg.drivers.noEdit': { en: 'A registered driver cannot be edited; activate or revoke it instead.', ar: 'لا يمكن تعديل بيانات السائق بعد التسجيل؛ يمكنك تفعيله أو إلغاؤه.' }, + + // ---- MOT validation + 'reg.mot.title': { en: 'Ministry of Transport check', ar: 'التحقق من وزارة النقل' }, + 'reg.mot.hint': { en: 'Checks the number against the Ministry of Transport registry (advisory).', ar: 'يتحقق من الرقم في سجل وزارة النقل (للاسترشاد).' }, + 'reg.mot.number': { en: 'Number', ar: 'الرقم' }, + 'reg.mot.company': { en: 'Company', ar: 'الشركة' }, + 'reg.mot.check': { en: 'Check', ar: 'تحقق' }, + 'reg.mot.ok': { en: 'The vehicle is registered and matches.', ar: 'المركبة مسجلة ومطابقة.' }, + 'reg.mot.notRegistered': { en: 'Vehicle registration error / the vehicle is not linked to the company.', ar: 'خطأ في تسجيل السيارة/ السيارة غير مؤتلفة' }, + 'reg.mot.wrongType': { en: 'The vehicle type is not valid for general cargo.', ar: 'النمط غير صحيح' }, + 'reg.mot.ownerOk': { en: 'Ownership is valid for this company.', ar: 'الملكية صحيحة لهذه الشركة.' }, + 'reg.mot.failed': { en: 'The check could not be completed.', ar: 'تعذر إكمال التحقق.' }, + + // ---- blacklist + 'reg.bl.title': { en: 'Blacklist', ar: 'قائمة المنع' }, + 'reg.bl.subtitle': { en: 'Permits blocked or placed on the waiting list', ar: 'الإرساليات الممنوعة أو في قائمة الانتظار' }, + 'reg.bl.new': { en: 'Add to blacklist', ar: 'إضافة لقائمة المنع' }, + 'reg.bl.createTitle': { en: 'Add to blacklist', ar: 'اضافة لقائمة المنع' }, + 'reg.bl.cancel': { en: 'Cancel entry', ar: 'إلغاء الحظر' }, + 'reg.bl.cancelTitle': { en: 'Cancel blacklist entry', ar: 'إلغاء الحظر' }, + 'reg.bl.cancelRemarks': { en: 'Reason for cancelling', ar: 'سبب الإلغاء' }, + 'reg.bl.cancelConfirm': { en: 'Cancel this blacklist entry?', ar: 'هل تريد إلغاء هذا الحظر؟' }, + 'reg.bl.expires': { en: 'Expires on {date}', ar: 'ينتهي بتاريخ {date}' }, + + // ---- weighbridge control + 'reg.wb.title': { en: 'Weighbridge control', ar: 'ضبط الميزان' }, + 'reg.wb.subtitle': { en: 'Let a truck pass a weighbridge location with an exception', ar: 'السماح لقاطرة بالمرور على موقع ميزان باستثناء' }, + 'reg.wb.confirm': { en: 'Save the weighbridge exception?', ar: 'حفظ استثناء الميزان؟' }, + + // ---- location counts + 'reg.lc.title': { en: 'Trucks per location', ar: 'عدد الشاحنات حسب الموقع' }, + 'reg.lc.subtitle': { en: 'Trucks currently counted at each location', ar: 'الشاحنات المحتسبة حالياً في كل موقع' }, + 'reg.lc.location': { en: 'Location', ar: 'الموقع' }, + 'reg.lc.count': { en: 'Trucks', ar: 'عدد الشاحنات' }, + 'reg.lc.total': { en: 'Total', ar: 'المجموع' }, +}); diff --git a/web/src/features/grains-registry/types.ts b/web/src/features/grains-registry/types.ts new file mode 100644 index 0000000..55b7553 --- /dev/null +++ b/web/src/features/grains-registry/types.ts @@ -0,0 +1,77 @@ +/** Wire types of the Grains registry slice (api/v1/grains/registry); property names are the backend's camelCase JSON. */ + +export interface RegistryResult { message: string; id?: number | null } + +export interface RegistryPermissions { + isBadiyaCompany: boolean; + isCompanyUser: boolean; + companyCodeNo: number | null; + canAddTruck: boolean; + canAddTrailer: boolean; + canAddDriver: boolean; + canEditTruck: boolean; + canEditTrailer: boolean; + canRevokeTruck: boolean; + canRevokeTrailer: boolean; + canRevokeDriver: boolean; + canAcceptTruck: boolean; + canAcceptTrailer: boolean; + canAcceptDriver: boolean; + canManageDestinations: boolean; + canExportTruckReport: boolean; + canExportDriverReport: boolean; + canCancelBlacklist: boolean; +} + +export interface TenderCompany { scac: number; name: string | null } +export interface TruckKind { kind: string; id: number; name: string | null } +export interface RegistryLocation { id: number; name: string | null } +export interface RegistryNationality { code: string; name: string | null } +export interface RegistryDestinationOptions { packed: RegistryLocation[]; bulk: RegistryLocation[]; bulkGallab: RegistryLocation[] } + +export interface RegistryAttachment { fileName: string; originalName: string; kind: 'truck' | 'trailer' | 'driver' } +export interface RegistryTempFile { id: string; name: string; size: number } + +export interface TruckRow { + id: number; tn: string; entityType: string; chasesNumber: string | null; createTimestamp: string | null; regDate: string | null; + createUserId: string | null; statusCode: string; statusCaption: string | null; compName: string | null; tnId: number | null; +} +export interface TrailerRow { + id: number; tn: string; chasesNumber: string | null; createTimestamp: string | null; regDate: string | null; createUserId: string | null; + statusCode: string; statusCaption: string | null; compName: string | null; ownerName: string | null; ownerNnpn: string | null; +} +export interface DriverRow { + id: number; nnpn: string; name: string | null; dln: string | null; dled: string | null; createTimestamp: string | null; + createUserId: string | null; compName: string | null; statusCode: string; statusCaption: string | null; +} +export interface BlacklistRow { + id: number; category: string | null; categoryCaption: string | null; entityType: string | null; entityTypeCaption: string | null; + entityNumber: string | null; creationDate: string | null; createdBy: string | null; lastUpdateDate: string | null; + lastUpdateUser: string | null; expiryDate: string | null; statusCode: string; statusCaption: string | null; remarks: string | null; +} + +export interface PendingDestination { user: string | null; time: string | null } + +export interface TruckDetail { + id: number; tn: string; chasesNumber: string | null; regDate: string | null; axials: number | null; axialsKind: string | null; + statusCode: string; statusCaption: string | null; ownerName: string | null; ownerNnpn: string | null; color: string | null; + model: string | null; manifactureYear: string | null; phoneNumber: string | null; headType: string | null; tcscac: number | null; + compName: string | null; lastUpdateUserId: string | null; lastUpdateTimestamp: string | null; trailerId: number | null; + trailerTn: string | null; destinationIds: number[] | null; pendingDestination: PendingDestination | null; + attachments: RegistryAttachment[]; +} +export interface TrailerDetail { + id: number; tn: string; chasesNumber: string | null; regDate: string | null; axials: number | null; axialsKind: string | null; + statusCode: string; statusCaption: string | null; ownerName: string | null; ownerNnpn: string | null; phoneNumber: string | null; + truckId: number | null; tcscac: number | null; compName: string | null; attachments: RegistryAttachment[]; +} +export interface DriverDetail { + id: number; nnpn: string; name: string | null; dln: string | null; dled: string | null; statusCode: string; statusCaption: string | null; + nat: string | null; cat: string | null; mobile1: string | null; mobile2: string | null; attachments: RegistryAttachment[]; +} + +export interface DestinationSelection { packed: number[]; bulk: number[]; bulkGallab: number[] } + +export interface BlacklistAdded { message: string; blacklistId: number; expiryDate: string } +export interface LocationTruckCount { loc: string | null; cnt: number } +export interface FleetCheckResult { allowed: boolean; message: string | null; totalFleet: number; turn: number } diff --git a/web/src/features/grains-reports/api.ts b/web/src/features/grains-reports/api.ts new file mode 100644 index 0000000..212aa14 --- /dev/null +++ b/web/src/features/grains-reports/api.ts @@ -0,0 +1,141 @@ +import { useQuery } from '@tanstack/react-query'; +import { API_BASE, api, ApiError, getToken } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import type { OptionItem, OptionsLoader } from '@/components/meta/types'; + +const base = '/grains/reports'; + +// ------------------------------------------------------------------ types (mirror the backend DTOs, camelCase) +export interface LookupItem { value: string; label: string } + +export interface TripsPerCompanyRow { + scac: string; companyCode: string; allTripNum: number; numOfTruk: number; companyShare: number; + avgShare: number; totalShare: number; avgTotalTrucks: number; avrgTrips: number; isBadiya: boolean; +} +export interface NumOfTripsReport { + from: string; to: string; companies: TripsPerCompanyRow[]; + companiesTotal: { companyShare: number; avgShare: number; totalShare: number; trucks: number; trips: number; tripsPct: number }; + individuals: TripsPerCompanyRow | null; + grandTotalShare: number; grandTrucks: number; grandTrips: number; grandTripsPct: number; +} +export interface QuotaLine { label: string; trucks: number; truckPct: number; trips: number; tripPct: number } +export interface QuotaReport { from: string; to: string; companies: QuotaLine; individuals: QuotaLine } +export interface TripGroupLine { key: string; fromTrips: number; toTrips: number; trucks: number; trucksPct: number; trips: number; tripsPct: number } +export interface FrequencyReport { + from: string; to: string; trucks: number[]; trips: number[]; tripsPct: number[]; + totalTrucks: number; totalTrips: number; groups: TripGroupLine[]; +} +export interface DetailsRow { scac: string; tn: string; tt: number } +export interface DetailsGroup { company: string; rows: DetailsRow[]; totalTrips: number; truckCount: number } +export interface DetailsReport { from: string; to: string; groups: DetailsGroup[] } + +export interface MotMonthLine { month: string; trucks: number[]; trips: number[]; trucksTotal: number; tripsTotal: number } +export interface MotBlock { regType: string; months: MotMonthLine[]; avgTrucksPerTrips: number[]; avgTrucksTotal: number; tripsSum: number } +export interface MotReport { + bucketCount: number; monthCount: number; individuals: MotBlock; companies: MotBlock; + chartCompanies: number[]; chartIndividuals: number[]; chartCompaniesPct: number[]; chartIndividualsPct: number[]; + companyTrucks: number; individualTrucks: number; companyTrips: number; individualTrips: number; +} + +export type ReportRow = Record & { __k: number }; +export interface ReportPageDto { + items: Record[]; page: number; pageSize: number; totalCount: number; + columns: { key: string; headerAr: string; headerEn: string; kind: string }[]; + extra?: Record | null; +} + +export interface PhoneImportRow { line: number; permitId: number; action: string; ok: boolean; code?: string | null; message: string } +export interface PhoneImportResult { + total: number; accepted: number; rejected: number; skipped: number; failed: number; rows: PhoneImportRow[]; message: string; +} +export interface FileImportResult { fileName: string; parsed: number; inserted: number; updated: number; skipped: number; failed: number; errors: string[] } +export interface ScanResult { files: number; results: FileImportResult[] } +export interface RawSyncResult { candidates: number; matched: number; noPermit: number; failed: number } + +// ------------------------------------------------------------------ option loaders (cached by React Query under lang) +const toOptions = (items: LookupItem[]): OptionItem[] => items.map((i) => ({ value: i.value, label: i.label })); + +export const companiesLoader: OptionsLoader = { + key: 'grains.reports.companies', + load: async () => toOptions(await api.get(`${base}/lookups/companies`, undefined, { silent: true })), +}; +export const cargoTypesLoader: OptionsLoader = { + key: 'grains.reports.cargoTypes', + load: async () => toOptions(await api.get(`${base}/lookups/cargo-types`, undefined, { silent: true })), +}; +/** Destinations depend on the cargo kind (BULK => bulk + tipper locations, otherwise packed). */ +export const destinationsLoader: OptionsLoader = { + key: 'grains.reports.destinations', + load: async ({ parent }) => + toOptions(await api.get(`${base}/lookups/destinations`, { shipmentMode: parent ? String(parent) : undefined }, { silent: true })), +}; +export const allDestinationsLoader: OptionsLoader = { + key: 'grains.reports.destinations.all', + load: async () => toOptions(await api.get(`${base}/lookups/destinations`, { shipmentMode: 'BULK' }, { silent: true })), +}; + +// ------------------------------------------------------------------ typed reports +export interface RangeParams { from: string; to: string; scac?: string; cargoType?: string } + +export const tripsKey = (kind: string, p: RangeParams | null) => ['grains.reports.trips', kind, p] as const; + +export function useTripsReport(kind: 'trips/num-of-trips-and-trucks' | 'trips/quota' | 'trips/frequency' | 'trips/distribution' | 'trips/details' | 'dashboard', p: RangeParams | null) { + return useQuery({ + queryKey: tripsKey(kind, p), + queryFn: () => api.get(`${base}/${kind}`, { from: p!.from, to: p!.to, scac: p!.scac, cargoType: p!.cargoType }), + enabled: !!p, + staleTime: 60_000, + }); +} + +export function useMotReport() { + return useQuery({ queryKey: ['grains.reports.mot'], queryFn: () => api.get(`${base}/mot/multi-trips`), staleTime: 5 * 60_000 }); +} + +// ------------------------------------------------------------------ table reports +export function fetchTable(key: string, params: Record) { + return api.get(`${base}/tables/${key}`, params); +} + +/** Excel export: needs the bearer token, so it is fetched and saved as a blob. */ +export async function downloadExcel(key: string, params: Record): Promise { + const qs = new URLSearchParams(params).toString(); + const token = getToken(); + const res = await fetch(`${API_BASE}${base}/tables/${key}/export${qs ? `?${qs}` : ''}`, { + headers: token ? { Authorization: `Bearer ${token}` } : {}, + }); + if (!res.ok) { + let msg = ''; + try { const p = (await res.json()) as { detail?: string; title?: string }; msg = p.detail || p.title || ''; } catch { /* not JSON */ } + throw new ApiError(res.status, msg || res.statusText); + } + const blob = await res.blob(); + const cd = res.headers.get('Content-Disposition') ?? ''; + const m = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(cd); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = m ? decodeURIComponent(m[1]!) : `${key}.xlsx`; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); +} + +// ------------------------------------------------------------------ imports (multipart) +const form = (file: File) => { const f = new FormData(); f.append('file', file); return f; }; + +export function useImportPhoneApprovals() { + return useWrite((file: File) => api.upload(`${base}/imports/phone-approvals`, form(file))); +} +export function useImportWbFile(kind: 'irbid' | 'rsifeh' | 'original') { + return useWrite((v: { file: File; replaceExisting?: boolean }) => + api.upload( + `${base}/weighbridge-files/${kind}${kind === 'original' && v.replaceExisting ? '?replaceExisting=true' : ''}`, form(v.file))); +} +export function useScanDirectory() { + return useWrite((v: { directory: string; archiveDirectory?: string }) => api.post(`${base}/weighbridge-files/scan`, v)); +} +export function useRawSync() { + return useWrite(() => api.post(`${base}/weighbridge-files/raw-sync`)); +} diff --git a/web/src/features/grains-reports/charts.tsx b/web/src/features/grains-reports/charts.tsx new file mode 100644 index 0000000..82f2737 --- /dev/null +++ b/web/src/features/grains-reports/charts.tsx @@ -0,0 +1,152 @@ +import { useId } from 'react'; +import { Box, Stack, Typography, useTheme } from '@mui/material'; +import { formatNumber } from '@/components/meta/format'; +import { useUi } from '@/i18n/useUi'; + +/** + * Small SVG charts (no chart library). Theme + RTL safe: colours come from the MUI palette (primary / warning are far apart + * in hue and lightness, so the pair stays distinguishable in light and dark), the plot is forced dir="ltr" (numeric axes), + * legends and titles are real HTML text, every mark has a tooltip and every chart has a legend when it has >= 2 series. + */ +export interface Series { name: string; values: number[]; color: string } + +export function useChartColors() { + const t = useTheme(); + return { a: t.palette.primary.main, b: t.palette.warning.main, c: t.palette.success.main, d: t.palette.secondary.main, text: t.palette.text.secondary, grid: t.palette.divider }; +} + +function niceMax(v: number): number { + if (v <= 0) return 1; + const p = Math.pow(10, Math.floor(Math.log10(v))); + const n = v / p; + return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * p; +} + +export function Legend({ items }: { items: { name: string; color: string }[] }) { + return ( + <Stack direction="row" spacing={2} useFlexGap sx={{ flexWrap: 'wrap', justifyContent: 'center', mt: 1 }} role="list"> + {items.map((i) => ( + <Stack key={i.name} direction="row" spacing={0.75} sx={{ alignItems: 'center' }} role="listitem"> + <Box sx={{ width: 12, height: 12, borderRadius: 0.5, bgcolor: i.color }} aria-hidden /> + <Typography variant="caption">{i.name}</Typography> + </Stack> + ))} + </Stack> + ); +} + +export interface BarChartProps { + title: string; + categories: string[]; + series: Series[]; + xTitle?: string; + height?: number; +} + +/** Grouped vertical bars; 4px rounded data end anchored to the baseline; 2px gap between bars of a group. */ +export function BarChart({ title, categories, series, xTitle, height = 260 }: BarChartProps) { + const { lang } = useUi(); + const c = useChartColors(); + const id = useId(); + const W = 640, H = height, L = 44, R = 10, T = 12, B = 34; + const max = niceMax(Math.max(0, ...series.flatMap((s) => s.values))); + const pw = W - L - R, ph = H - T - B; + const gw = pw / Math.max(1, categories.length); + const bw = Math.max(2, Math.min(28, (gw - 6) / series.length - 2)); + const y = (v: number) => T + ph - (v / max) * ph; + const ticks = [0, 0.25, 0.5, 0.75, 1].map((f) => f * max); + const every = categories.length > 16 ? 2 : 1; + + return ( + <Box> + <Typography variant="subtitle2" sx={{ fontWeight: 700, textAlign: 'center', mb: 0.5 }}>{title}</Typography> + <Box dir="ltr" sx={{ width: '100%', overflowX: 'auto' }}> + <svg viewBox={`0 0 ${W} ${H}`} width="100%" role="img" aria-labelledby={`${id}-t`} style={{ maxWidth: W, display: 'block', margin: '0 auto' }}> + <title id={`${id}-t`}>{title} + {ticks.map((tv) => ( + + + {formatNumber(Math.round(tv * 100) / 100, lang)} + + ))} + {categories.map((cat, i) => { + const x0 = L + i * gw + (gw - (bw * series.length + 2 * (series.length - 1))) / 2; + return ( + + {series.map((s, k) => { + const v = s.values[i] ?? 0; + const h = (v / max) * ph; + const x = x0 + k * (bw + 2); + const r = Math.min(4, bw / 2, h); + return ( + + {`${s.name} - ${cat}: ${formatNumber(v, lang)}`} + + ); + })} + {i % every === 0 && ( + {cat} + )} + + ); + })} + + {xTitle && {xTitle}} + +
+ {series.length >= 2 && ({ name: s.name, color: s.color }))} />} +
+ ); +} + +export interface PieSlice { name: string; value: number; color: string } + +/** Pie with a 2px surface gap between slices; labels (name + percent) live in the legend, not on the slices. */ +export function PieChart({ title, slices, size = 200 }: { title: string; slices: PieSlice[]; size?: number }) { + const { lang } = useUi(); + const theme = useTheme(); + const id = useId(); + const total = slices.reduce((s, x) => s + x.value, 0); + const r = size / 2 - 4, cx = size / 2, cy = size / 2; + let angle = -Math.PI / 2; + const arcs = slices.filter((s) => s.value > 0).map((s) => { + const a = (s.value / total) * Math.PI * 2; + const full = a >= Math.PI * 2 - 1e-6; + const x1 = cx + r * Math.cos(angle), y1 = cy + r * Math.sin(angle); + angle += a; + const x2 = cx + r * Math.cos(angle), y2 = cy + r * Math.sin(angle); + const d = full ? `M${cx - r},${cy} A${r},${r} 0 1 1 ${cx + r},${cy} A${r},${r} 0 1 1 ${cx - r},${cy} Z` + : `M${cx},${cy} L${x1},${y1} A${r},${r} 0 ${a > Math.PI ? 1 : 0} 1 ${x2},${y2} Z`; + return { ...s, d, pct: (s.value / total) * 100 }; + }); + return ( + + {title} + + + {title} + {total <= 0 ? : arcs.map((a) => ( + + {`${a.name}: ${formatNumber(a.value, lang)} (${a.pct.toFixed(1)}%)`} + + ))} + + + ({ name: `${s.name}${total > 0 ? ` - ${((s.value / total) * 100).toFixed(1)}%` : ''}`, color: s.color }))} /> + + ); +} + +/** Headline number tile (no plot, so no hover layer). */ +export function KpiTile({ label, value }: { label: string; value: string }) { + return ( + + {label} + {value} + + ); +} diff --git a/web/src/features/grains-reports/meta.tsx b/web/src/features/grains-reports/meta.tsx new file mode 100644 index 0000000..50646cc --- /dev/null +++ b/web/src/features/grains-reports/meta.tsx @@ -0,0 +1,218 @@ +import type { ColumnMeta, FilterMeta, OptionItem, StatusMeta } from '@/components/meta/types'; +import { allDestinationsLoader, cargoTypesLoader, companiesLoader, destinationsLoader } from './api'; +import strings from './strings'; + +/** Declarative tables for every tabular report (grid + filters). Row keys equal the backend ReportColumn keys. */ +type Row = Record; + +export interface TableReportMeta { + key: string; + titleKey: keyof typeof strings; + columns: ColumnMeta[]; + filters: FilterMeta[]; + status?: { param: string; options: StatusMeta[] }; + /** Filter names that must be present before the report can run (legacy pages validated them). */ + required: string[]; + /** Default filter values (e.g. today for date ranges). */ + defaults?: 'today' | 'yesterday' | Record; + /** Column layout reconstructed from the legacy request parameters (the .cfr template is unreadable). */ + inferred?: boolean; + /** Shows the "extra" block returned by the backend. */ + extra?: 'orderDistribution' | 'incapability'; + pageSize?: number; +} + +const L = (k: keyof typeof strings) => strings[k]; +const H = (en: string, ar: string) => ({ en, ar }); + +const lbl = (k: keyof typeof strings): OptionItem['label'] => strings[k]; +const opt = (value: string, k: keyof typeof strings): OptionItem => ({ value, label: lbl(k) }); + +const eventOptions = ['LTW', 'LGW', 'DTW', 'DGW'].map((v) => opt(v, `rpt.ev.${v}` as keyof typeof strings)); +const modeOptions = ['BULK', 'PCKD', 'GALLAB'].map((v) => opt(v, `rpt.mode.${v}` as keyof typeof strings)); +const dtypeOptions = ['COMP', 'AHALI', 'all'].map((v) => opt(v, `rpt.dtype.${v}` as keyof typeof strings)); +const modeBulkPckd = ['BULK', 'PCKD'].map((v) => opt(v, `rpt.mode.${v}` as keyof typeof strings)); + +const permitStatuses: StatusMeta[] = [ + { value: 'REQST', label: L('rpt.st.REQST'), color: 'warning' }, + { value: 'PLND', label: L('rpt.st.PLND'), color: 'info' }, + { value: 'OPEN', label: L('rpt.st.OPEN'), color: 'default' }, + { value: 'ACCPT', label: L('rpt.st.ACCPT'), color: 'primary' }, + { value: 'RESD', label: L('rpt.st.RESD'), color: 'primary' }, + { value: 'ACTRL', label: L('rpt.st.ACTRL'), color: 'secondary' }, + { value: 'CLRPR', label: L('rpt.st.CLRPR'), color: 'secondary' }, + { value: 'CLOSE', label: L('rpt.st.CLOSE'), color: 'success' }, + { value: 'RVKD', label: L('rpt.st.RVKD'), color: 'error' }, +]; +const regStatuses = ['OPEN', 'ACCPT', 'RVKD', 'REGREQST'].map((v) => opt(v, `rpt.st.${v}` as keyof typeof strings)); + +const fFrom: FilterMeta = { name: 'from', type: 'date', label: L('rpt.from') }; +const fTo: FilterMeta = { name: 'to', type: 'date', label: L('rpt.to') }; +const fOrderDate: FilterMeta = { name: 'orderDate', type: 'date', label: L('rpt.f.orderDate') }; +const fTn: FilterMeta = { name: 'tn', type: 'text', label: L('rpt.f.tn'), inputKind: 'plate' }; +const fScac: FilterMeta = { name: 'scac', type: 'autocomplete', label: L('rpt.company'), options: companiesLoader }; + +const num = (key: string, h: { en: string; ar: string }, extra: Partial> = {}): ColumnMeta => ({ key, header: h, format: 'number', align: 'end', ...extra }); +const txt = (key: string, h: { en: string; ar: string }, extra: Partial> = {}): ColumnMeta => ({ key, header: h, ...extra }); +const code = (key: string, h: { en: string; ar: string }): ColumnMeta => ({ key, header: h, ltr: true }); + +const permitCols = { + pn: code('pn', H('Permit no.', 'رقم الإرسالية')), + tn: code('tn', H('Truck no.', 'رقم القاطرة')), + company: txt('company', H('Company', 'الشركة')), + cargoType: txt('cargoType', H('Cargo', 'نوع المادة'), { hideBelow: 'md' }), + origin: txt('origin', H('Loading site', 'موقع التحميل'), { hideBelow: 'md' }), + destination: txt('destination', H('Discharge site', 'موقع التفريغ'), { hideBelow: 'md' }), +}; + +export const tableReports: Record = { + 'weighbridge-events': { + key: 'weighbridge-events', titleKey: 'rpt.t.weighbridge-events', required: ['from', 'to'], defaults: 'today', pageSize: 50, + filters: [fFrom, fTo], + columns: [ + num('serial', H('#', '#'), { width: 60, align: 'start' }), + code('pn', H('Permit no.', 'رقم الإرسالية')), code('tn', H('Truck no.', 'رقم السيارة')), + txt('cargoType', H('Cargo', 'نوع المادة'), { hideBelow: 'lg' }), txt('scac', H('Company', 'الشركة')), txt('loc', H('Discharge site', 'موقع التفريغ'), { hideBelow: 'md' }), + num('ltw', H('Load tare', 'فارغ التحميل'), { hideBelow: 'md' }), num('lgw', H('Load gross', 'قائم التحميل'), { hideBelow: 'md' }), num('lnw', H('Load net', 'صافي التحميل')), + txt('loadDate', H('Loaded on', 'تاريخ التحميل'), { ltr: true, hideBelow: 'lg' }), + num('dtw', H('Discharge tare', 'فارغ التفريغ'), { hideBelow: 'md' }), num('dgw', H('Discharge gross', 'قائم التفريغ'), { hideBelow: 'md' }), num('dnw', H('Discharge net', 'صافي التفريغ')), + txt('dischargeDate', H('Discharged on', 'تاريخ التفريغ'), { ltr: true, hideBelow: 'lg' }), + num('netLoss', H('Net loss', 'صافي النقص')), + txt('drvr', H('Driver', 'اسم السائق'), { hideBelow: 'lg' }), code('nnpn', H('National no.', 'الرقم الوطني')), txt('origin', H('Origin', 'جهة التحميل'), { hideBelow: 'lg' }), + ], + }, + 'waybridge-summary': { + key: 'waybridge-summary', titleKey: 'rpt.t.waybridge-summary', required: ['from', 'to'], defaults: 'today', inferred: true, + filters: [fFrom, fTo, { name: 'eventType', type: 'select', label: L('rpt.f.eventType'), options: eventOptions }], + columns: [txt('company', H('Company', 'الشركة')), txt('cargoType', H('Cargo', 'نوع المادة')), num('trips', H('Movements', 'عدد الحركات')), num('totalWeight', H('Total weight', 'إجمالي الوزن'))], + }, + 'waybridge-details': { + key: 'waybridge-details', titleKey: 'rpt.t.waybridge-details', required: ['from', 'to'], defaults: 'today', inferred: true, + filters: [fFrom, fTo, { name: 'eventType', type: 'select', label: L('rpt.f.eventType'), options: eventOptions }], + columns: [ + permitCols.pn, permitCols.tn, permitCols.company, permitCols.cargoType, + txt('eventType', H('Event', 'الحركة')), txt('location', H('Site', 'الموقع'), { hideBelow: 'md' }), + num('weight', H('Weight', 'الوزن')), { key: 'eventDate', header: H('Event date', 'تاريخ الحركة'), format: 'datetime', ltr: true }, txt('doneBy', H('User', 'المستخدم'), { hideBelow: 'lg' }), + ], + }, + 'loading-weights': { + key: 'loading-weights', titleKey: 'rpt.t.loading-weights', required: ['from', 'to'], defaults: 'today', inferred: true, + filters: [fFrom, fTo], + columns: [ + permitCols.pn, permitCols.tn, permitCols.company, permitCols.cargoType, permitCols.origin, permitCols.destination, + num('tare', H('Tare', 'وزن الفارغ')), num('gross', H('Gross', 'وزن القائم')), num('net', H('Net', 'الصافي')), + { key: 'eventDate', header: H('Loaded on', 'تاريخ التحميل'), format: 'datetime', ltr: true }, + ], + }, + 'closed-permits': { + key: 'closed-permits', titleKey: 'rpt.t.closed-permits', required: ['from', 'to'], defaults: 'today', inferred: true, + filters: [fFrom, fTo], + columns: [ + permitCols.pn, permitCols.tn, permitCols.company, permitCols.cargoType, permitCols.origin, permitCols.destination, + txt('drvr', H('Driver', 'اسم السائق'), { hideBelow: 'lg' }), code('nnpn', H('National no.', 'الرقم الوطني')), + { key: 'closeDate', header: H('Closed on', 'تاريخ الإغلاق'), format: 'datetime', ltr: true }, + ], + }, + incapability: { + key: 'incapability', titleKey: 'rpt.t.incapability', required: ['from', 'to'], defaults: 'yesterday', inferred: true, extra: 'incapability', + filters: [fFrom, fTo], + columns: [ + permitCols.pn, permitCols.tn, permitCols.company, permitCols.cargoType, permitCols.destination, + num('loadNet', H('Loaded net', 'صافي التحميل')), num('dischargeNet', H('Discharged net', 'صافي التفريغ')), num('shortage', H('Shortage', 'العجز')), + { key: 'orderDate', header: H('Order date', 'تاريخ الطلبية'), format: 'date', ltr: true, hideBelow: 'md' }, + ], + }, + 'tender-order': { + key: 'tender-order', titleKey: 'rpt.t.tender-order', required: [], pageSize: 50, + status: { param: 'shipmentStatusCode', options: permitStatuses }, + filters: [ + fOrderDate, { name: 'destAddressId', type: 'autocomplete', label: L('rpt.f.destination'), options: allDestinationsLoader }, fTn, fScac, + { name: 'creationDate', type: 'date', label: L('rpt.f.creationDate') }, + ], + columns: [ + txt('phoneAccpt', H('Phone approval', 'موافقة هاتفية'), { hideBelow: 'lg' }), txt('statusCaption', H('Status', 'الحالة')), txt('destName', H('Destination', 'الوجهة'), { hideBelow: 'md' }), + txt('remarks', H('Loading site', 'موقع التحميل'), { hideBelow: 'lg' }), code('tn', H('Truck no.', 'رقم القاطرة')), txt('type', H('Load type', 'نوع الحمولة'), { hideBelow: 'md' }), + txt('drvr', H('Driver', 'اسم السائق'), { hideBelow: 'lg' }), { key: 'creationDate', header: H('Permit date', 'تاريخ الإرسالية'), format: 'datetime', ltr: true, hideBelow: 'md' }, + code('phoneNumber', H('Company phone', 'هاتف الشركة')), txt('compName', H('Company', 'الشركة')), code('queueNo', H('Queue no.', 'رقم الدور')), code('pn', H('Permit no.', 'رقم الإرسالية')), + ], + }, + 'distribution-summary': { + key: 'distribution-summary', titleKey: 'rpt.t.distribution-summary', required: ['orderDate'], + filters: [fOrderDate, { name: 'shipmentMode', type: 'select', label: L('rpt.f.shipmentMode'), options: modeBulkPckd }], + defaults: { shipmentMode: 'BULK' }, + columns: [txt('name', H('Company', 'الشركة')), num('cnt', H('Count', 'العدد')), txt('shift', H('Shift', 'الشفت')), { key: 'orderDate', header: H('Order date', 'تاريخ الطلبية'), ltr: true }], + }, + 'order-distribution': { + key: 'order-distribution', titleKey: 'rpt.t.order-distribution', required: ['orderDate'], extra: 'orderDistribution', + filters: [fOrderDate], + columns: [ + txt('dest', H('Destination', 'الوجهة')), num('ahale', H('Individuals', 'عدد الافراد')), num('ahalePct', H('Individuals %', 'نسبة الافراد')), + num('company', H('Companies', 'عدد الشركات')), num('companyPct', H('Companies %', 'نسبة الشركات')), num('total', H('Total', 'المجموع')), + ], + }, + 'call-list': { + key: 'call-list', titleKey: 'rpt.t.call-list', required: ['orderDate'], + filters: [fOrderDate, { name: 'destAddressId', type: 'autocomplete', label: L('rpt.f.destination'), options: allDestinationsLoader }, fTn, fScac, { name: 'tt', type: 'text', label: L('rpt.f.tt') }], + columns: [ + code('name', H('Truck (Name)', 'القاطرة')), code('phone', H('Phone', 'الهاتف')), code('code1', H('Code1', 'Code1')), code('code2', H('Code2', 'Code2')), + code('number1', H('Number1', 'Number1')), code('number2', H('Number2', 'Number2')), code('number3', H('Number3', 'Number3')), code('number4', H('Number4', 'Number4')), code('number5', H('Number5', 'Number5')), + code('item', H('Item', 'Item')), code('fromDist', H('From', 'From')), code('origin', H('Origin', 'Origin')), code('week', H('Week', 'Week')), code('day', H('Day', 'Day')), + code('month', H('Month', 'Month')), code('dayNight', H('DayNight', 'DayNight')), code('id', H('ID', 'ID')), + ], + pageSize: 100, + }, + 'companies-turn': { + key: 'companies-turn', titleKey: 'rpt.t.companies-turn', required: ['shipmentMode'], inferred: true, + defaults: { shipmentMode: 'BULK', distributionType: 'COMP' }, + filters: [ + { name: 'shipmentMode', type: 'select', label: L('rpt.f.shipmentMode'), options: modeOptions }, + { name: 'distributionType', type: 'select', label: L('rpt.f.distributionType'), options: dtypeOptions }, + ], + columns: [num('turn', H('Turn', 'الدور'), { align: 'start', width: 80 }), code('scac', H('Company code', 'رقم الشركة')), txt('company', H('Company', 'اسم الشركة')), txt('code', H('Cargo', 'نوع المادة')), txt('type', H('Distribution', 'نوع التوزيع')), num('counter', H('Counter', 'العداد'))], + }, + 'owners-turn': { + key: 'owners-turn', titleKey: 'rpt.t.owners-turn', required: ['destAddressId'], inferred: true, + defaults: { shipmentMode: 'BULK' }, + filters: [ + { name: 'shipmentMode', type: 'select', label: L('rpt.f.shipmentMode'), options: modeBulkPckd }, + { name: 'destAddressId', type: 'autocomplete', label: L('rpt.f.destination'), options: destinationsLoader, dependsOn: 'shipmentMode' }, + ], + columns: [num('turn', H('Turn', 'الدور'), { align: 'start', width: 80 }), code('tn', H('Truck no.', 'رقم القاطرة')), num('trips', H('Trips', 'عدد الرحلات')), { key: 'lastTrip', header: H('Last trip', 'آخر رحلة'), format: 'datetime', ltr: true }], + }, + drivers: { + key: 'drivers', titleKey: 'rpt.t.drivers', required: [], + filters: [ + { name: 'nnpn', type: 'text', label: L('rpt.f.nnpn'), inputKind: 'code' }, { name: 'name', type: 'text', label: L('rpt.f.name') }, + { name: 'statusCode', type: 'select', label: L('rpt.f.status'), options: regStatuses }, + ], + columns: [ + code('nnpn', H('National no.', 'الرقم الوطني')), txt('name', H('Name', 'الاسم')), code('dln', H('Licence no.', 'رقم الرخصة')), txt('dled', H('Licence expiry', 'انتهاء الرخصة'), { ltr: true, hideBelow: 'md' }), + txt('company', H('Company', 'الشركة'), { hideBelow: 'md' }), txt('status', H('Status', 'الحالة')), txt('createDate', H('Registered on', 'تاريخ التسجيل'), { ltr: true, hideBelow: 'lg' }), txt('createUser', H('User', 'المستخدم'), { hideBelow: 'lg' }), + ], + }, + trucks: { + key: 'trucks', titleKey: 'rpt.t.trucks', required: [], + filters: [ + fTn, { name: 'chasesNumber', type: 'text', label: L('rpt.f.chasis'), inputKind: 'code' }, { name: 'headType', type: 'text', label: L('rpt.f.headType') }, + { name: 'statusCode', type: 'select', label: L('rpt.f.status'), options: regStatuses }, fScac, + ], + columns: [ + code('tn', H('Truck no.', 'رقم القاطرة')), code('chasesNumber', H('Chassis no.', 'رقم الشاصي')), txt('company', H('Company', 'الشركة')), txt('status', H('Status', 'الحالة')), + txt('regDate', H('Reg. date', 'تاريخ التسجيل'), { ltr: true, hideBelow: 'md' }), txt('createDate', H('Created on', 'تاريخ الإنشاء'), { ltr: true, hideBelow: 'lg' }), txt('createUser', H('User', 'المستخدم'), { hideBelow: 'lg' }), + ], + }, + 'mot-grain-cube': { + key: 'mot-grain-cube', titleKey: 'rpt.t.mot-grain-cube', required: ['from', 'to'], defaults: 'today', + filters: [fFrom, fTo], + columns: [txt('loc', H('Destination', 'الوجهة')), txt('company', H('Company', 'الشركة')), num('trucks', H('Trucks', 'الشاحنات')), num('cTrucks', H('Company trucks', 'شاحنات الشركات')), num('trails', H('Trailers', 'المقطورات')), num('cTrails', H('Company trailers', 'مقطورات الشركات')), num('trips', H('Trips', 'الرحلات')), num('cTrips', H('Company trips', 'رحلات الشركات'))], + }, + 'mot-grain-frequency': { + key: 'mot-grain-frequency', titleKey: 'rpt.t.mot-grain-frequency', required: ['from', 'to'], defaults: 'today', + filters: [fFrom, fTo], + columns: [num('c', H('Trips', 'عدد الرحلات'), { align: 'start' }), num('contCnt', H('Individuals - count', 'أفراد - عدد')), num('contPerc', H('Individuals %', 'أفراد %')), num('compCnt', H('Companies - count', 'شركات - عدد')), num('compPerc', H('Companies %', 'شركات %'))], + }, +}; + +export const tableReportKeys = Object.keys(tableReports); + +export { cargoTypesLoader }; diff --git a/web/src/features/grains-reports/pages.tsx b/web/src/features/grains-reports/pages.tsx new file mode 100644 index 0000000..1ab04dd --- /dev/null +++ b/web/src/features/grains-reports/pages.tsx @@ -0,0 +1,748 @@ +import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'; +import { useParams, useSearchParams } from 'react-router-dom'; +import { + Alert, Box, Button, Checkbox, FormControlLabel, MenuItem, Paper, Stack, Table, TableBody, TableCell, TableContainer, + TableHead, TableRow, TextField, Typography, +} from '@mui/material'; +import DownloadIcon from '@mui/icons-material/Download'; +import PlayArrowIcon from '@mui/icons-material/PlayArrow'; +import PrintIcon from '@mui/icons-material/Print'; +import UploadFileIcon from '@mui/icons-material/UploadFile'; +import { ApiError, type PagedResult } from '@/api/client'; +import { DataGrid } from '@/components/DataGrid'; +import { EmptyState } from '@/components/EmptyState'; +import { LoadingBanner } from '@/components/LoadingBanner'; +import { PageHeader } from '@/components/PageHeader'; +import { formatNumber } from '@/components/meta/format'; +import type { GridMeta } from '@/components/meta/types'; +import { useOptions } from '@/components/meta/useOptions'; +import { useFeatureUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useConfirm } from '@/providers/ConfirmProvider'; +import { useToast } from '@/providers/ToastProvider'; +import { + cargoTypesLoader, companiesLoader, downloadExcel, fetchTable, useImportPhoneApprovals, useImportWbFile, useMotReport, + useRawSync, useScanDirectory, useTripsReport, + type DetailsReport, type FileImportResult, type FrequencyReport, type MotBlock, type MotReport, type NumOfTripsReport, + type PhoneImportResult, type QuotaReport, type RangeParams, type RawSyncResult, type ScanResult, +} from './api'; +import { BarChart, KpiTile, PieChart, useChartColors } from './charts'; +import { tableReports, type TableReportMeta } from './meta'; +import strings from './strings'; + +type Row = Record; + +const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +const todayIso = () => iso(new Date()); +const yesterdayIso = () => { const d = new Date(); d.setDate(d.getDate() - 1); return iso(d); }; +const errText = (e: unknown, fb: string) => (e instanceof ApiError ? e.message : fb); +const pct = (n: number, lang: 'en' | 'ar') => `${formatNumber(Math.round(n * 100) / 100, lang)}%`; + +// ====================================================================== shared bits + +/** Date range (+ optional company / cargo) bar. The report runs only when the URL carries a valid range. */ +function useRange(opts: { company?: boolean; cargo?: boolean }) { + const { t, tr, lang } = useFeatureUi(strings); + const [sp, setSp] = useSearchParams(); + const [from, setFrom] = useState(sp.get('from') ?? ''); + const [to, setTo] = useState(sp.get('to') ?? ''); + const [scac, setScac] = useState(sp.get('scac') ?? ''); + const [cargo, setCargo] = useState(sp.get('cargoType') ?? ''); + const [err, setErr] = useState(''); + const companies = useOptions(opts.company ? companiesLoader : undefined); + const cargos = useOptions(opts.cargo ? cargoTypesLoader : undefined); + + const params: RangeParams | null = useMemo(() => { + const f = sp.get('from'), tt = sp.get('to'); + if (!f || !tt || tt < f) return null; + return { from: f, to: tt, scac: sp.get('scac') || undefined, cargoType: sp.get('cargoType') || undefined }; + }, [sp]); + + function run() { + if (!from || !to) { setErr(t('common.required')); return; } + if (to < from) { setErr(t('rpt.rangeInvalid')); return; } + setErr(''); + const p = new URLSearchParams({ from, to }); + if (scac) p.set('scac', scac); + if (cargo) p.set('cargoType', cargo); + setSp(p); + } + const onKey = (e: KeyboardEvent) => { if (e.key === 'Enter') { e.preventDefault(); run(); } }; + + const bar = ( + + + setFrom(e.target.value)} required + slotProps={{ inputLabel: { shrink: true } }} sx={{ width: 200 }} error={!!err && !from} /> + setTo(e.target.value)} required + slotProps={{ inputLabel: { shrink: true } }} sx={{ width: 200 }} error={!!err && !to} /> + {opts.company && ( + setScac(e.target.value)} sx={{ width: 260 }}> + {t('rpt.allCompanies')} + {companies.options.map((o) => {tr(o.label)})} + + )} + {opts.cargo && ( + setCargo(e.target.value)} sx={{ width: 260 }}> + {t('rpt.allCargo')} + {cargos.options.map((o) => {tr(o.label)})} + + )} + + + {err && {err}} + + ); + return { bar, params, lang, t }; +} + +const PrintButton = ({ label }: { label: string }) => ( + +); + +function ReportShell({ title, subtitle, bar, params, query, print = true, children }: { + title: string; subtitle?: string; bar: ReactNode; params: RangeParams | null; + query: { isPending: boolean; isError: boolean; error: unknown; isFetching: boolean; data: unknown }; + print?: boolean; children: ReactNode; +}) { + const { t, lang } = useFeatureUi(strings); + const { user } = useAuth(); + return ( + + : undefined} /> + {bar} + {!params && } + {params && query.isPending && } + {params && query.isError && {t('rpt.loadError')}: {errText(query.error, '')}} + {params && !!query.data && ( + + + {t('rpt.period')}: {params.from} - {params.to} + + {children} + {print && ( + + {t('rpt.printedBy')}: {user?.name} - {t('rpt.printedOn')}: {new Date().toLocaleString(lang === 'ar' ? 'ar-JO' : 'en-GB')} + + )} + + )} + + ); +} + +const th = { fontWeight: 700 } as const; +const numCell = { textAlign: 'end', fontVariantNumeric: 'tabular-nums' } as const; +const Cell = ({ children, bold }: { children: ReactNode; bold?: boolean }) => ( + {children} +); + +// ====================================================================== trips reports +export function NumOfTripsPage() { + const { bar, params, lang, t } = useRange({}); + const q = useTripsReport('trips/num-of-trips-and-trucks', params); + const n = (v: number) => formatNumber(v, lang); + const r = q.data; + return ( + + {r && ( + + + + + {(['rpt.num.company', 'rpt.num.approvedTrucks', 'rpt.num.pct', 'rpt.num.totalPct', 'rpt.num.actualTrucks', 'rpt.num.trips', 'rpt.num.tripsPct', 'rpt.num.trucksDiff'] as const).map((k, i) => ( + {t(k)} + ))} + + + + {r.companies.map((c) => ( + + {c.scac} + {n(c.companyShare)}{pct(c.avgShare, lang)}{pct(c.totalShare, lang)} + {n(c.numOfTruk)}{n(c.allTripNum)}{pct(c.avrgTrips, lang)} + {pct(c.avgTotalTrucks - c.avgShare, lang)} + + ))} + + {t('rpt.num.companiesTotal')} + {n(r.companiesTotal.companyShare)}{pct(r.companiesTotal.avgShare, lang)}{pct(r.companiesTotal.totalShare, lang)} + {n(r.companiesTotal.trucks)}{n(r.companiesTotal.trips)}{pct(r.companiesTotal.tripsPct, lang)}{''} + + {r.individuals && ( + + {t('rpt.num.individuals')} + {n(r.individuals.companyShare)}{pct(r.individuals.avgShare, lang)}{pct(r.individuals.totalShare, lang)} + {n(r.individuals.numOfTruk)}{n(r.individuals.allTripNum)}{pct(r.individuals.avrgTrips, lang)}{''} + + )} + + {t('rpt.num.grand')} + {''}{''}{pct(r.grandTotalShare, lang)} + {n(r.grandTrucks)}{n(r.grandTrips)}{pct(r.grandTripsPct, lang)}{''} + + +
+
+ )} +
+ ); +} + +export function QuotaPage() { + const { bar, params, lang, t } = useRange({}); + const q = useTripsReport('trips/quota', params); + const c = useChartColors(); + const r = q.data; + const lines = r ? [{ name: t('rpt.quota.companies'), l: r.companies, color: c.a }, { name: t('rpt.quota.individuals'), l: r.individuals, color: c.b }] : []; + return ( + + {r && ( + + + + + + {t('rpt.quota.kind')} + {(['rpt.quota.trucks', 'rpt.quota.trucksPct', 'rpt.quota.trips', 'rpt.quota.tripsPct'] as const).map((k) => {t(k)})} + + + + {lines.map(({ name, l }) => ( + + {name} + {formatNumber(l.trucks, lang)}{pct(l.truckPct, lang)} + {formatNumber(l.trips, lang)}{pct(l.tripPct, lang)} + + ))} + +
+
+ + ({ name: x.name, value: x.l.trucks, color: x.color }))} /> + ({ name: x.name, value: x.l.trips, color: x.color }))} /> + +
+ )} +
+ ); +} + +export function FrequencyPage() { + const { bar, params, lang, t } = useRange({}); + const q = useTripsReport('trips/frequency', params); + const c = useChartColors(); + const r = q.data; + const cats = r ? r.trucks.map((_, i) => String(i + 1)) : []; + return ( + + {r && ( + + + + + + {t('rpt.freq.freq')} + {t('rpt.freq.trucks')} + {t('rpt.freq.trips')} + {t('rpt.freq.tripsPct')} + + + + {cats.map((k, i) => ( + + {k}{formatNumber(r.trucks[i], lang)}{formatNumber(r.trips[i], lang)}{pct(r.tripsPct[i] ?? 0, lang)} + + ))} + + {t('rpt.total')} + {formatNumber(r.totalTrucks, lang)}{formatNumber(r.totalTrips, lang)}{''} + + +
+
+ +
+ )} +
+ ); +} + +export function DistributionPage() { + const { bar, params, lang, t } = useRange({}); + const q = useTripsReport('trips/distribution', params); + const c = useChartColors(); + const r = q.data; + const label = (g: FrequencyReport['groups'][number]) => + g.fromTrips === g.toTrips ? String(g.fromTrips) : t('rpt.dist.groupLabel', { from: g.fromTrips, to: g.toTrips }); + return ( + + {r && ( + + + + + + {t('rpt.freq.group')} + {(['rpt.det.trucks', 'rpt.dist.trucksPct', 'rpt.det.trips', 'rpt.freq.tripsPct'] as const).map((k) => {t(k)})} + + + + {r.groups.map((g) => ( + + {label(g)} + {formatNumber(g.trucks, lang)}{pct(g.trucksPct, lang)}{formatNumber(g.trips, lang)}{pct(g.tripsPct, lang)} + + ))} + +
+
+ + ({ name: label(g), value: g.trucks, color: [c.a, c.b, c.c, c.d, c.text][i % 5]! }))} /> + ({ name: label(g), value: g.trips, color: [c.a, c.b, c.c, c.d, c.text][i % 5]! }))} /> + +
+ )} +
+ ); +} + +export function DetailsPage() { + const { bar, params, lang, t } = useRange({}); + const q = useTripsReport('trips/details', params); + const r = q.data; + return ( + + {r && (r.groups.length === 0 ? : ( + + {r.groups.map((g) => ( + + + + + {g.company} + {t('rpt.det.trips')} + + + + {g.rows.map((x) => ( + + {x.tn}{formatNumber(x.tt, lang)} + + ))} + + {t('rpt.det.subtotal')} ({formatNumber(g.truckCount, lang)} {t('rpt.det.trucks')}) + {formatNumber(g.totalTrips, lang)} + + +
+
+ ))} +
+ ))} +
+ ); +} + +export function DashboardPage() { + const { bar, params, lang, t } = useRange({ company: true, cargo: true }); + const q = useTripsReport('dashboard', params); + const c = useChartColors(); + const r = q.data; + // buckets 1..9 plus a "more than 9" bucket (the legacy dashboard chart) + const cats = r ? [...r.trucks.slice(0, 9).map((_, i) => String(i + 1)), t('rpt.dash.more9')] : []; + const fold = (a: readonly number[]) => [...a.slice(0, 9), a.slice(9).reduce((s, x) => s + x, 0)]; + return ( + + {r && ( + + + + + + + + + + + + )} + + ); +} + +// ====================================================================== MOT multi-trips (no date filter, as in legacy) +function MotBlockTable({ block, title, buckets }: { block: MotBlock; title: string; buckets: number }) { + const { t, lang } = useFeatureUi(strings); + const heads = Array.from({ length: buckets }, (_, i) => String(i + 1)); + return ( + + {title} + + + + + {t('rpt.mot.month')} + {t('rpt.mot.kind')} + {heads.map((h) => {h})} + {t('rpt.total')} + + + + {block.months.flatMap((m) => [ + + {m.month}{t('rpt.mot.trucksRow')} + {heads.map((_, i) => {formatNumber(m.trucks[i] ?? 0, lang)})}{formatNumber(m.trucksTotal, lang)} + , + + {t('rpt.mot.tripsRow')} + {heads.map((_, i) => {formatNumber(m.trips[i] ?? 0, lang)})}{formatNumber(m.tripsTotal, lang)} + , + ])} + + {t('rpt.mot.avgRow')} + {heads.map((_, i) => {formatNumber(block.avgTrucksPerTrips[i] ?? 0, lang)})}{formatNumber(block.avgTrucksTotal, lang)} + + +
+
+
+ ); +} + +export function MotMultiTripsPage() { + const { t } = useFeatureUi(strings); + const q = useMotReport(); + const c = useChartColors(); + const r: MotReport | undefined = q.data; + const cats = r ? Array.from({ length: r.bucketCount }, (_, i) => String(i + 1)) : []; + const ser = (vals: number[][], names: string[]) => vals.map((v, i) => ({ name: names[i]!, values: v, color: i === 0 ? c.a : c.b })); + const names = [t('rpt.mot.companies'), t('rpt.mot.individuals')]; + return ( + + : undefined} /> + {q.isPending && } + {q.isError && {t('rpt.loadError')}: {errText(q.error, '')}} + {r && ( + + + + + + + + + + + )} + + ); +} + +// ====================================================================== generic tabular report (grid + Excel + print) +function initialDefaults(m: TableReportMeta): Record | undefined { + if (m.defaults === 'today') return { from: todayIso(), to: todayIso() }; + if (m.defaults === 'yesterday') return { from: yesterdayIso(), to: yesterdayIso() }; + return m.defaults; +} + +export function TableReportPage({ reportKey }: { reportKey?: string }) { + const params = useParams(); + const key = reportKey ?? params.key ?? ''; + const meta = tableReports[key]; + if (!meta) return Unknown report; + return ; +} + +function TableReportBody({ meta }: { meta: TableReportMeta }) { + const { t, tr } = useFeatureUi(strings); + const toast = useToast(); + const [sp] = useSearchParams(); + const [busy, setBusy] = useState(false); + const [extra, setExtra] = useState | null>(null); + const defaults = useMemo(() => initialDefaults(meta), [meta]); + + const filterNames = useMemo(() => [...meta.filters.map((f) => f.name), ...(meta.status ? [meta.status.param] : [])], [meta]); + // current effective filters (URL, else the defaults used for the very first request) + const effective = useMemo(() => { + const o: Record = {}; + const seeded = sp.has('f') || !defaults; + for (const n of filterNames) { + const v = seeded ? sp.get(n) : defaults?.[n]; + if (v) o[n] = v; + } + return o; + }, [sp, filterNames, defaults]); + const missing = meta.required.filter((n) => !effective[n]); + + const gridMeta = useMemo>(() => ({ + key: `grains.reports.${meta.key}`, + rowKey: (r) => String(r.__k), + columns: meta.columns, + filters: meta.filters, + status: meta.status, + defaultFilters: defaults, + pageSize: meta.pageSize ?? 50, + fetcher: async ({ page, pageSize, filters }): Promise> => { + // legacy pages validated the required inputs before running the query + if (meta.required.some((n) => !filters[n])) { setExtra(null); return { items: [], page, pageSize, totalCount: 0 }; } + const res = await fetchTable(meta.key, { page, pageSize, ...filters }); + setExtra(res.extra ?? null); + return { items: res.items.map((r, i) => ({ ...r, __k: (page - 1) * pageSize + i })), page: res.page, pageSize: res.pageSize, totalCount: res.totalCount }; + }, + }), [meta, defaults]); + + async function exportExcel() { + setBusy(true); + try { + await downloadExcel(meta.key, effective); + toast.success(t('rpt.excelDone')); + } catch (e) { + toast.error(errText(e, t('rpt.loadError'))); + } finally { + setBusy(false); + } + } + + return ( + + + + + + } + /> + + {meta.inferred && {t('rpt.t.inferredNote')}} + {meta.defaults === 'yesterday' && {t('rpt.f.yesterdayNote')}} + {missing.length > 0 && ( + + {t('rpt.f.required', { names: missing.map((n) => tr(meta.filters.find((f) => f.name === n)?.label) || n).join(', ') })} + + )} + + + + + ); +} + +function TableExtra({ meta, extra }: { meta: TableReportMeta; extra: Record | null }) { + const { t, lang } = useFeatureUi(strings); + if (!extra || !meta.extra) return null; + const n = (k: string) => formatNumber(extra[k], lang); + if (meta.extra === 'incapability') { + return {t('rpt.t.shortageTotal')}: {n('totalShortage')}; + } + return ( + + + + + {t('rpt.summary')} + {t('rpt.count')} + % + + + + {t('rpt.t.individuals')}{n('individuals')}{pct(Number(extra.individualsPct ?? 0), lang)} + {t('rpt.t.companies')}{n('companies')}{pct(Number(extra.companiesPct ?? 0), lang)} + {t('rpt.total')}{n('total')}{''} + +
+
+ ); +} + +// ====================================================================== imports +function FilePicker({ file, onFile, accept, label }: { file: File | null; onFile: (f: File | null) => void; accept: string; label: string }) { + const { t } = useFeatureUi(strings); + const ref = useRef(null); + return ( + + { onFile(e.target.files?.[0] ?? null); e.target.value = ''; }} /> + + {file ? file.name : t('rpt.imp.noFile')} + + ); +} + +export function PhoneApprovalsPage() { + const { t } = useFeatureUi(strings); + const confirm = useConfirm(); + const [file, setFile] = useState(null); + const [res, setRes] = useState(null); + const imp = useImportPhoneApprovals(); + + async function submit() { + if (!file) return; + if (!(await confirm({ message: t('rpt.imp.confirm', { file: file.name }) }))) return; + imp.mutate(file, { onSuccess: (r) => { setRes(r); setFile(null); } }); + } + + return ( + + + + + + + + + {imp.isPending && } + {res && ( + + + + + + + + {res.rows.length > 0 && ( + + + + + {(['rpt.imp.line', 'rpt.imp.permit', 'rpt.imp.action', 'rpt.imp.result'] as const).map((k) => {t(k)})} + + + + {res.rows.map((r) => ( + + {r.line} + {r.permitId} + {r.action === 'Accept' || r.action === 'Reject' ? t(`rpt.imp.${r.action}` as 'rpt.imp.Accept') : r.action} + {r.message} + + ))} + +
+
+ )} +
+ )} +
+ ); +} + +function FileResult({ r }: { r: FileImportResult }) { + const { t, lang } = useFeatureUi(strings); + return ( + + {r.fileName} + + + + + + + + {r.errors?.length > 0 && ( + + {t('rpt.wb.errors')} + {r.errors.slice(0, 20).map((e, i) =>
  • {e}
  • )}
    +
    + )} +
    + ); +} + +function WbFileCard({ kind, title, hint }: { kind: 'irbid' | 'rsifeh' | 'original'; title: string; hint: string }) { + const { t } = useFeatureUi(strings); + const confirm = useConfirm(); + const [file, setFile] = useState(null); + const [replace, setReplace] = useState(false); + const [res, setRes] = useState(null); + const imp = useImportWbFile(kind); + + async function submit() { + if (!file) return; + if (!(await confirm({ message: t('rpt.wb.confirmFile', { file: file.name }), danger: kind === 'original' && replace }))) return; + imp.mutate({ file, replaceExisting: replace }, { onSuccess: (r) => { setRes(r); setFile(null); } }); + } + return ( + + + {title} + {hint} + + {kind === 'original' && ( + setReplace(e.target.checked)} />} label={t('rpt.wb.replace')} /> + )} + + {res && } + + + ); +} + +export function WeighbridgeFilesPage() { + const { t, lang } = useFeatureUi(strings); + const confirm = useConfirm(); + const toast = useToast(); + const [dir, setDir] = useState(''); + const [archive, setArchive] = useState(''); + const [scanRes, setScanRes] = useState(null); + const [syncRes, setSyncRes] = useState(null); + const scan = useScanDirectory(); + const sync = useRawSync(); + + async function doScan() { + if (!dir.trim()) { toast.warning(t('rpt.wb.noFolder')); return; } + if (!(await confirm({ message: t('rpt.wb.confirmScan', { dir }) }))) return; + scan.mutate({ directory: dir.trim(), archiveDirectory: archive.trim() || undefined }, { onSuccess: setScanRes }); + } + async function doSync() { + if (!(await confirm({ message: t('rpt.wb.rawSyncConfirm'), danger: true }))) return; + sync.mutate(undefined, { onSuccess: setSyncRes }); + } + + return ( + + + + + + + + + + {t('rpt.wb.scan')} + {t('rpt.wb.scanHint')} + + setDir(e.target.value)} slotProps={{ htmlInput: { dir: 'ltr' } }} /> + setArchive(e.target.value)} slotProps={{ htmlInput: { dir: 'ltr' } }} /> + + + {scanRes && ( + + {t('rpt.wb.files')}: {formatNumber(scanRes.files, lang)} + {scanRes.results.map((r) => )} + + )} + + + + + + {t('rpt.wb.rawSync')} + {t('rpt.wb.rawSyncHint')} + + {syncRes && ( + + + + + + + )} + + + + + ); +} + diff --git a/web/src/features/grains-reports/routes.tsx b/web/src/features/grains-reports/routes.tsx new file mode 100644 index 0000000..0ba5eec --- /dev/null +++ b/web/src/features/grains-reports/routes.tsx @@ -0,0 +1,88 @@ +import type { RouteObject } from 'react-router-dom'; +import AssessmentIcon from '@mui/icons-material/Assessment'; +import BarChartIcon from '@mui/icons-material/BarChart'; +import DashboardIcon from '@mui/icons-material/Dashboard'; +import LocalShippingIcon from '@mui/icons-material/LocalShipping'; +import PieChartIcon from '@mui/icons-material/PieChart'; +import ScaleIcon from '@mui/icons-material/Scale'; +import TableChartIcon from '@mui/icons-material/TableChart'; +import UploadFileIcon from '@mui/icons-material/UploadFile'; +import type { MenuItem } from '@/shell/types'; +import { + DashboardPage, DetailsPage, DistributionPage, FrequencyPage, MotMultiTripsPage, NumOfTripsPage, PhoneApprovalsPage, + QuotaPage, TableReportPage, WeighbridgeFilesPage, +} from './pages'; +import { tableReports } from './meta'; +import strings from './strings'; + +const B = '/grains/reports'; + +export const routes: RouteObject[] = [ + { path: `${B}/dashboard`, element: }, + { path: `${B}/trips/num-of-trips`, element: }, + { path: `${B}/trips/quota`, element: }, + { path: `${B}/trips/frequency`, element: }, + { path: `${B}/trips/distribution`, element: }, + { path: `${B}/trips/details`, element: }, + { path: `${B}/mot/multi-trips`, element: }, + { path: `${B}/t/:key`, element: }, + { path: `${B}/imports/phone-approvals`, element: }, + { path: `${B}/imports/weighbridge-files`, element: }, +]; + +const table = (key: string, icon: MenuItem['icon'] = TableChartIcon): MenuItem => ({ + key: `grains.reports.t.${key}`, title: strings[tableReports[key]!.titleKey], icon, path: `${B}/t/${key}`, +}); + +export const menu: MenuItem[] = [ + { + key: 'grains.reports', + title: strings['rpt.menu.group'], + icon: AssessmentIcon, + children: [ + { + key: 'grains.reports.trips', title: strings['rpt.menu.trips'], icon: BarChartIcon, + children: [ + { key: 'grains.reports.dashboard', title: strings['rpt.menu.dashboard'], icon: DashboardIcon, path: `${B}/dashboard` }, + { key: 'grains.reports.numOfTrips', title: strings['rpt.menu.numOfTrips'], icon: BarChartIcon, path: `${B}/trips/num-of-trips` }, + { key: 'grains.reports.quota', title: strings['rpt.menu.quota'], icon: PieChartIcon, path: `${B}/trips/quota` }, + { key: 'grains.reports.frequency', title: strings['rpt.menu.frequency'], icon: BarChartIcon, path: `${B}/trips/frequency` }, + { key: 'grains.reports.distribution', title: strings['rpt.menu.distribution'], icon: PieChartIcon, path: `${B}/trips/distribution` }, + { key: 'grains.reports.details', title: strings['rpt.menu.details'], icon: TableChartIcon, path: `${B}/trips/details` }, + ], + }, + { + key: 'grains.reports.ops', title: strings['rpt.menu.ops'], icon: ScaleIcon, + children: [ + table('weighbridge-events', ScaleIcon), table('waybridge-summary', ScaleIcon), table('waybridge-details', ScaleIcon), + table('loading-weights', ScaleIcon), table('closed-permits'), table('incapability'), + ], + }, + { + key: 'grains.reports.orders', title: strings['rpt.menu.orders'], icon: TableChartIcon, + children: [ + table('tender-order'), table('distribution-summary'), table('order-distribution'), table('call-list'), + table('companies-turn'), table('owners-turn'), + ], + }, + { + key: 'grains.reports.registry', title: strings['rpt.menu.registry'], icon: LocalShippingIcon, + children: [table('drivers'), table('trucks')], + }, + { + key: 'grains.reports.mot', title: strings['rpt.menu.mot'], icon: BarChartIcon, + children: [ + { key: 'grains.reports.motMulti', title: strings['rpt.menu.motMulti'], icon: BarChartIcon, path: `${B}/mot/multi-trips` }, + table('mot-grain-cube'), table('mot-grain-frequency'), + ], + }, + { + key: 'grains.reports.imports', title: strings['rpt.menu.imports'], icon: UploadFileIcon, + children: [ + { key: 'grains.reports.phoneApprovals', title: strings['rpt.menu.phoneApprovals'], icon: UploadFileIcon, path: `${B}/imports/phone-approvals` }, + { key: 'grains.reports.wbFiles', title: strings['rpt.menu.wbFiles'], icon: UploadFileIcon, path: `${B}/imports/weighbridge-files`, roles: ['SU'] }, + ], + }, + ], + }, +]; diff --git a/web/src/features/grains-reports/strings.ts b/web/src/features/grains-reports/strings.ts new file mode 100644 index 0000000..32e5af4 --- /dev/null +++ b/web/src/features/grains-reports/strings.ts @@ -0,0 +1,234 @@ +import { defineStrings } from '@/i18n/useUi'; + +/** Strings of the Grains reports slice (prefix `rpt.`). */ +export default defineStrings({ + // ---- menu + 'rpt.menu.group': { en: 'Grains reports', ar: 'تقارير الحبوب' }, + 'rpt.menu.trips': { en: 'Trips and dashboards', ar: 'الرحلات ولوحات المؤشرات' }, + 'rpt.menu.ops': { en: 'Weighbridge and permits', ar: 'القبان والإرساليات' }, + 'rpt.menu.orders': { en: 'Orders and distribution', ar: 'الطلبيات والتوزيع' }, + 'rpt.menu.registry': { en: 'Registered trucks and drivers', ar: 'القاطرات والسائقون' }, + 'rpt.menu.mot': { en: 'MOT reports', ar: 'تقارير وزارة النقل' }, + 'rpt.menu.imports': { en: 'File imports', ar: 'تحميل الملفات' }, + 'rpt.menu.dashboard': { en: 'Trips dashboard', ar: 'لوحة الرحلات' }, + 'rpt.menu.numOfTrips': { en: 'Trucks and trips per company', ar: 'عدد الشاحنات والرحلات لكل شركة' }, + 'rpt.menu.quota': { en: 'Quota report', ar: 'تقرير المحاصصة' }, + 'rpt.menu.frequency': { en: 'Trip frequency', ar: 'تكرار الرحلات' }, + 'rpt.menu.distribution': { en: 'Trips distribution', ar: 'توزيع الرحلات' }, + 'rpt.menu.details': { en: 'Detailed report', ar: 'التقرير التفصيلي' }, + 'rpt.menu.phoneApprovals': { en: 'Approvals file (IVR)', ar: 'تحميل ملف الموافقات' }, + 'rpt.menu.wbFiles': { en: 'Weighbridge files', ar: 'ملفات القبان' }, + 'rpt.menu.motMulti': { en: 'Multi-trip report (MOT)', ar: 'تقرير تعدد الرحلات' }, + + // ---- common page bits + 'rpt.from': { en: 'From', ar: 'من' }, + 'rpt.to': { en: 'To', ar: 'إلى' }, + 'rpt.run': { en: 'Run report', ar: 'عرض التقرير' }, + 'rpt.print': { en: 'Print / PDF', ar: 'طباعة / PDF' }, + 'rpt.excel': { en: 'Export to Excel', ar: 'تصدير إلى Excel' }, + 'rpt.excelDone': { en: 'Excel file downloaded', ar: 'تم تنزيل ملف Excel' }, + 'rpt.rangeInvalid': { en: 'The end date must not be before the start date', ar: 'تاريخ النهاية يجب أن يكون بعد تاريخ البداية' }, + 'rpt.pickRange': { en: 'Choose the period and press "Run report".', ar: 'اختر الفترة ثم اضغط "عرض التقرير".' }, + 'rpt.printedBy': { en: 'Printed by', ar: 'طبع بواسطة' }, + 'rpt.printedOn': { en: 'On', ar: 'بتاريخ' }, + 'rpt.company': { en: 'Company', ar: 'الشركة' }, + 'rpt.cargoType': { en: 'Cargo type', ar: 'نوع المادة' }, + 'rpt.allCompanies': { en: 'All companies', ar: 'جميع الشركات' }, + 'rpt.allCargo': { en: 'All cargo types', ar: 'جميع المواد' }, + 'rpt.period': { en: 'Period', ar: 'الفترة' }, + 'rpt.noData': { en: 'No data for the selected period.', ar: 'لا توجد بيانات للفترة المحددة.' }, + 'rpt.loadError': { en: 'Could not load the report', ar: 'تعذر تحميل التقرير' }, + 'rpt.total': { en: 'Total', ar: 'المجموع' }, + 'rpt.count': { en: 'Count', ar: 'العدد' }, + 'rpt.tableView': { en: 'Table view', ar: 'عرض جدولي' }, + 'rpt.summary': { en: 'Summary', ar: 'الملخص' }, + + // ---- trips: per company + 'rpt.num.title': { en: 'Trucks and trips completed per company during the study period', ar: 'تقرير عدد الشاحنات والرحلات المنجزة لكل شركة خلال فترة الدراسة' }, + 'rpt.num.company': { en: 'Company', ar: 'اسم الشركة' }, + 'rpt.num.approvedTrucks': { en: 'Approved trucks', ar: 'عدد السيارات الموافق عليها' }, + 'rpt.num.pct': { en: 'Percentage', ar: 'النسبة المئوية' }, + 'rpt.num.totalPct': { en: 'Overall percentage', ar: 'النسبة الإجمالية' }, + 'rpt.num.actualTrucks': { en: 'Actual trucks', ar: 'عدد السيارات الفعلي' }, + 'rpt.num.trips': { en: 'All trips', ar: 'كامل عدد الرحلات' }, + 'rpt.num.tripsPct': { en: 'Actual trips %', ar: 'نسبة الرحلات الفعلية' }, + 'rpt.num.trucksDiff': { en: 'Trucks % difference', ar: 'فرق نسبة عدد السيارات' }, + 'rpt.num.companiesTotal': { en: 'Companies total', ar: 'إجمالي الشركات' }, + 'rpt.num.individuals': { en: 'Individuals (Badiya)', ar: 'الأفراد (البادية)' }, + 'rpt.num.grand': { en: 'Grand total', ar: 'الإجمالي العام' }, + + // ---- quota + 'rpt.quota.title': { en: 'Quota report', ar: 'تقرير المحاصصة' }, + 'rpt.quota.trucks': { en: 'Trucks', ar: 'عدد السيارات' }, + 'rpt.quota.trucksPct': { en: 'Trucks %', ar: 'نسبة السيارات' }, + 'rpt.quota.trips': { en: 'Trips', ar: 'عدد الرحلات' }, + 'rpt.quota.tripsPct': { en: 'Trips %', ar: 'نسبة الرحلات' }, + 'rpt.quota.companies': { en: 'Companies', ar: 'الشركات' }, + 'rpt.quota.individuals': { en: 'Individuals', ar: 'الأفراد' }, + + // ---- frequency / distribution / details + 'rpt.freq.title': { en: 'Trip frequency report', ar: 'تقرير تكرار الرحلات' }, + 'rpt.freq.freq': { en: 'Trip frequency', ar: 'تكرار الرحلات' }, + 'rpt.freq.trucks': { en: 'Number of trucks', ar: 'عدد الشاحنات' }, + 'rpt.freq.trips': { en: 'Total trips', ar: 'مجموع الرحلات' }, + 'rpt.freq.tripsPct': { en: 'Trips %', ar: 'نسبة الرحلات' }, + 'rpt.dist.title': { en: 'Trips distribution report', ar: 'تقرير توزيع الرحلات' }, + 'rpt.dist.group': { en: 'Trips distribution', ar: 'توزيع الرحلات' }, + 'rpt.dist.groupLabel': { en: '{from} to {to} trips', ar: 'من {from} إلى {to} رحلات' }, + 'rpt.dist.trucksPct': { en: 'Trucks %', ar: 'نسبة الشاحنات' }, + 'rpt.det.title': { en: 'Detailed report', ar: 'التقرير التفصيلي' }, + 'rpt.det.truck': { en: 'Truck no.', ar: 'رقم السيارة' }, + 'rpt.det.trips': { en: 'Trips', ar: 'عدد الرحلات' }, + 'rpt.det.trucks': { en: 'Trucks', ar: 'عدد الشاحنات' }, + + // ---- dashboard + 'rpt.dash.title': { en: 'Grains trips dashboard', ar: 'لوحة مؤشرات رحلات الحبوب' }, + 'rpt.dash.kpiTrucks': { en: 'Trucks', ar: 'الشاحنات' }, + 'rpt.dash.kpiTrips': { en: 'Trips', ar: 'الرحلات' }, + 'rpt.dash.kpiAvg': { en: 'Trips per truck', ar: 'متوسط الرحلات لكل شاحنة' }, + 'rpt.dash.trucksChart': { en: 'Number of trucks by number of trips', ar: 'عدد الشاحنات حسب عدد الرحلات' }, + 'rpt.dash.tripsChart': { en: 'Total trips by number of trips per truck', ar: 'مجموع الرحلات حسب عدد الرحلات للشاحنة' }, + 'rpt.dash.trucksShare': { en: 'Share of trucks', ar: 'نسبة الشاحنات' }, + 'rpt.dash.tripsShare': { en: 'Share of trips', ar: 'نسبة الرحلات' }, + 'rpt.dash.xTrips': { en: 'Trips per truck', ar: 'عدد الرحلات' }, + 'rpt.dash.more9': { en: 'More than 9', ar: 'أكثر من 9' }, + 'rpt.dash.series.trucks': { en: 'Trucks', ar: 'الشاحنات' }, + 'rpt.dash.series.trips': { en: 'Trips', ar: 'الرحلات' }, + + // ---- MOT + 'rpt.mot.title': { en: 'Multi-trip report for grains (MOT)', ar: 'تقرير تعدد الرحلات لنمط الحبوب' }, + 'rpt.mot.individuals': { en: 'Individuals', ar: 'الأفراد' }, + 'rpt.mot.companies': { en: 'Companies', ar: 'الشركات' }, + 'rpt.mot.month': { en: 'Month', ar: 'الشهر' }, + 'rpt.mot.kind': { en: 'Type', ar: 'الملكية' }, + 'rpt.mot.trucksRow': { en: 'Trucks', ar: 'شاحنات' }, + 'rpt.mot.tripsRow': { en: 'Trips', ar: 'رحلات' }, + 'rpt.mot.avgRow': { en: 'Average trucks', ar: 'معدل الشاحنات' }, + 'rpt.mot.countChart': { en: 'Trips distribution by count', ar: 'توزيع الرحلات حسب العدد' }, + 'rpt.mot.pctChart': { en: 'Trips distribution by percentage', ar: 'توزيع الرحلات حسب النسبة' }, + 'rpt.mot.trucksRatio': { en: 'Company trucks vs individual trucks', ar: 'نسبة شاحنات الشركات لشاحنات الأفراد' }, + 'rpt.mot.tripsRatio': { en: 'Company trips vs individual trips', ar: 'نسبة رحلات الشركات لرحلات الأفراد' }, + 'rpt.mot.note': { en: 'Based on all grains permits recorded in the system (no date filter, as in the legacy report).', ar: 'بناءً على جميع إرساليات الحبوب المسجلة في النظام (بدون فلترة بالتاريخ كما في التقرير القديم).' }, + + // ---- table reports: titles + 'rpt.t.weighbridge-events': { en: 'Loading and discharge weighbridge movements', ar: 'تقارير حركات قبان التحميل والتفريغ' }, + 'rpt.t.waybridge-summary': { en: 'Weighbridge movements - totals', ar: 'حركات القبان - تقرير إجمالي' }, + 'rpt.t.waybridge-details': { en: 'Weighbridge movements - details', ar: 'حركات القبان - تقرير تفصيلي' }, + 'rpt.t.loading-weights': { en: 'Loading weights', ar: 'تقرير أوزان التحميل' }, + 'rpt.t.closed-permits': { en: 'Completed permits', ar: 'الارساليات المكتملة' }, + 'rpt.t.incapability': { en: 'Shortage report', ar: 'تقرير العجز' }, + 'rpt.t.tender-order': { en: 'Tender order permits', ar: 'ارسالية عطاء التموين' }, + 'rpt.t.distribution-summary': { en: 'Distribution summary', ar: 'ملخص التوزيع' }, + 'rpt.t.order-distribution': { en: 'Bulk order distribution ratios', ar: 'نسب التوزيع في طلبيات السائب' }, + 'rpt.t.call-list': { en: 'IVR call list', ar: 'قائمة الاتصال الآلي' }, + 'rpt.t.companies-turn': { en: 'Companies turn', ar: 'تقرير دور الشركات' }, + 'rpt.t.owners-turn': { en: 'Individuals turn', ar: 'تقرير دور الأفراد' }, + 'rpt.t.drivers': { en: 'Registered drivers', ar: 'تقرير السائقين المسجلين' }, + 'rpt.t.trucks': { en: 'Registered trucks', ar: 'تقرير القاطرات المسجلة' }, + 'rpt.t.mot-grain-cube': { en: 'Grain cube (MOT)', ar: 'مكعب الحبوب (وزارة النقل)' }, + 'rpt.t.mot-grain-frequency': { en: 'Grain trip frequency (MOT)', ar: 'تكرار رحلات الحبوب (وزارة النقل)' }, + 'rpt.t.inferredNote': { en: 'Columns of this report were reconstructed from the legacy request parameters (the original template is not readable). Please confirm the layout.', ar: 'أعمدة هذا التقرير أُعيد بناؤها من معاملات الطلب في النظام القديم (قالب التقرير الأصلي غير قابل للقراءة). يرجى تأكيد التصميم.' }, + 'rpt.t.shortageTotal': { en: 'Total shortage', ar: 'إجمالي العجز' }, + 'rpt.t.individuals': { en: 'Individuals', ar: 'أفراد' }, + 'rpt.t.companies': { en: 'Companies', ar: 'شركات' }, + 'rpt.t.unknown': { en: 'Unknown report', ar: 'تقرير غير معروف' }, + + // ---- table reports: filters + 'rpt.f.orderDate': { en: 'Order date', ar: 'تاريخ الطلبية' }, + 'rpt.f.eventType': { en: 'Movement type', ar: 'نوع الحركة' }, + 'rpt.f.shipmentMode': { en: 'Cargo kind', ar: 'نوع المادة' }, + 'rpt.f.distributionType': { en: 'Distribution type', ar: 'نوع التوزيع' }, + 'rpt.f.destination': { en: 'Destination', ar: 'الوجهة' }, + 'rpt.f.tn': { en: 'Truck number', ar: 'رقم القاطرة' }, + 'rpt.f.status': { en: 'Status', ar: 'الحالة' }, + 'rpt.f.chasis': { en: 'Chassis number', ar: 'رقم الشاصي' }, + 'rpt.f.headType': { en: 'Head type', ar: 'نوع الرأس' }, + 'rpt.f.nnpn': { en: 'National number', ar: 'الرقم الوطني' }, + 'rpt.f.name': { en: 'Name', ar: 'الاسم' }, + 'rpt.f.tt': { en: 'Transport type', ar: 'نوع النقل' }, + 'rpt.f.creationDate': { en: 'Permit date', ar: 'تاريخ الإرسالية' }, + 'rpt.f.yesterdayNote': { en: 'The "to" date must not be after yesterday.', ar: 'تاريخ "إلى" لا يجوز أن يتجاوز تاريخ الأمس.' }, + 'rpt.ev.LTW': { en: 'Loading site - entry', ar: 'قبان دخول موقع التحميل' }, + 'rpt.ev.LGW': { en: 'Loading site - exit', ar: 'قبان خروج موقع التحميل' }, + 'rpt.ev.DTW': { en: 'Discharge site - entry', ar: 'قبان دخول موقع التفريغ' }, + 'rpt.ev.DGW': { en: 'Discharge site - exit', ar: 'قبان خروج موقع التفريغ' }, + 'rpt.mode.BULK': { en: 'Bulk', ar: 'سائب' }, + 'rpt.mode.PCKD': { en: 'Packed', ar: 'مشول' }, + 'rpt.mode.GALLAB': { en: 'Bulk - tipper', ar: 'سائب - قلاب' }, + 'rpt.dtype.COMP': { en: 'Companies', ar: 'شركات' }, + 'rpt.dtype.AHALI': { en: 'Individuals', ar: 'أفراد' }, + 'rpt.dtype.all': { en: 'All', ar: 'الكل' }, + 'rpt.st.REQST': { en: 'Requested', ar: 'مطلوبة' }, + 'rpt.st.PLND': { en: 'Planned', ar: 'مخططة' }, + 'rpt.st.OPEN': { en: 'Open', ar: 'مفتوحة' }, + 'rpt.st.ACCPT': { en: 'Accepted', ar: 'مقبولة' }, + 'rpt.st.RESD': { en: 'Released', ar: 'محررة' }, + 'rpt.st.ACTRL': { en: 'Loaded', ar: 'تم التحميل' }, + 'rpt.st.CLRPR': { en: 'Cleared', ar: 'تم التخليص' }, + 'rpt.st.CLOSE': { en: 'Closed', ar: 'مغلقة' }, + 'rpt.st.RVKD': { en: 'Revoked', ar: 'ملغاة' }, + 'rpt.st.REGREQST': { en: 'Registration requested', ar: 'طلب تسجيل' }, + + // ---- phone approvals import + 'rpt.imp.title': { en: 'Approvals file upload', ar: 'تحميل ملف الموافقات' }, + 'rpt.imp.subtitle': { en: 'Upload the IVR call-result file (CSV or Excel). Each row accepts or declines a permit.', ar: 'ارفع ملف نتائج الاتصال الآلي (CSV أو Excel). كل سطر يقبل أو يرفض إرسالية.' }, + 'rpt.imp.choose': { en: 'Choose file', ar: 'اختيار الملف' }, + 'rpt.imp.noFile': { en: 'No file selected', ar: 'لم يتم اختيار ملف' }, + 'rpt.imp.upload': { en: 'Upload and process', ar: 'رفع ومعالجة' }, + 'rpt.imp.confirm': { en: 'Process the approvals in "{file}"? Permits will be accepted or declined (and blacklisted) according to the file.', ar: 'معالجة الموافقات في الملف "{file}"؟ سيتم قبول أو رفض الإرساليات (وإضافتها لقائمة المنع) حسب الملف.' }, + 'rpt.imp.processing': { en: 'Processing the file...', ar: 'جاري معالجة الملف...' }, + 'rpt.imp.accepted': { en: 'Accepted', ar: 'مقبولة' }, + 'rpt.imp.rejected': { en: 'Declined', ar: 'مرفوضة' }, + 'rpt.imp.skipped': { en: 'Skipped lines', ar: 'أسطر متجاوزة' }, + 'rpt.imp.failed': { en: 'Failed', ar: 'فشلت' }, + 'rpt.imp.line': { en: 'Line', ar: 'السطر' }, + 'rpt.imp.permit': { en: 'Permit id', ar: 'رقم الإرسالية (ID)' }, + 'rpt.imp.action': { en: 'Action', ar: 'الإجراء' }, + 'rpt.imp.result': { en: 'Result', ar: 'النتيجة' }, + 'rpt.imp.Accept': { en: 'Accept', ar: 'قبول' }, + 'rpt.imp.Reject': { en: 'Decline', ar: 'رفض' }, + + // ---- weighbridge files (admin) + 'rpt.wb.title': { en: 'Weighbridge files', ar: 'ملفات القبان' }, + 'rpt.wb.subtitle': { en: 'Manual import of the weighbridge files and the matching of raw weighbridge data (administrators).', ar: 'تحميل ملفات القبان يدوياً ومطابقة بيانات القبان الخام (للمشرفين).' }, + 'rpt.wb.irbid': { en: 'Irbid / Gaban file', ar: 'ملف قبان إربد / الجابان' }, + 'rpt.wb.irbidHint': { en: 'Each record is sent to the weighbridge event service (location 225) and stored.', ar: 'يتم إرسال كل سجل إلى خدمة حركات القبان (موقع 225) ثم حفظه.' }, + 'rpt.wb.rsifeh': { en: 'Rsifeh file', ar: 'ملف الرصيفة' }, + 'rpt.wb.rsifehHint': { en: 'Reads the count line + id/data line pairs into the staging tables.', ar: 'قراءة سطر العدد وأزواج (الرقم/البيانات) إلى الجداول المؤقتة.' }, + 'rpt.wb.original': { en: 'Original data snapshot', ar: 'ملف البيانات الأصلية' }, + 'rpt.wb.originalHint': { en: 'Loads a snapshot into the processed-records table.', ar: 'تحميل نسخة أولية إلى جدول السجلات المعالجة.' }, + 'rpt.wb.replace': { en: 'Replace the existing records first', ar: 'حذف السجلات الحالية أولاً' }, + 'rpt.wb.scan': { en: 'Scan a folder now', ar: 'فحص مجلد الآن' }, + 'rpt.wb.scanHint': { en: 'Same work as the folder watcher (which is disabled by default).', ar: 'نفس عمل مراقب المجلد (المعطل افتراضياً).' }, + 'rpt.wb.directory': { en: 'Folder on the server', ar: 'المجلد على الخادم' }, + 'rpt.wb.archive': { en: 'Archive folder (optional)', ar: 'مجلد الأرشيف (اختياري)' }, + 'rpt.wb.scanNow': { en: 'Scan', ar: 'فحص' }, + 'rpt.wb.rawSync': { en: 'Match raw weighbridge data', ar: 'مطابقة بيانات القبان الخام' }, + 'rpt.wb.rawSyncHint': { en: 'Links unmatched raw weighings to permits, adds the discharge weights and closes the permits.', ar: 'ربط الأوزان الخام غير المطابقة بالإرساليات وإضافة أوزان التفريغ وإغلاق الإرساليات.' }, + 'rpt.wb.rawSyncConfirm': { en: 'Match all unmatched raw weighbridge records now? Matching permits will be closed.', ar: 'مطابقة جميع سجلات القبان الخام غير المطابقة الآن؟ سيتم إغلاق الإرساليات المطابقة.' }, + 'rpt.wb.run': { en: 'Run', ar: 'تنفيذ' }, + 'rpt.wb.confirmFile': { en: 'Import "{file}"?', ar: 'تحميل الملف "{file}"؟' }, + 'rpt.wb.confirmScan': { en: 'Import and archive every file in "{dir}"?', ar: 'تحميل وأرشفة جميع الملفات في "{dir}"؟' }, + 'rpt.wb.parsed': { en: 'Records read', ar: 'السجلات المقروءة' }, + 'rpt.wb.inserted': { en: 'Inserted', ar: 'مضافة' }, + 'rpt.wb.updated': { en: 'Updated', ar: 'محدثة' }, + 'rpt.wb.skipped': { en: 'Skipped', ar: 'متجاوزة' }, + 'rpt.wb.errors': { en: 'Errors', ar: 'أخطاء' }, + 'rpt.wb.files': { en: 'Files processed', ar: 'الملفات المعالجة' }, + 'rpt.wb.candidates': { en: 'Candidates', ar: 'سجلات للمطابقة' }, + 'rpt.wb.matched': { en: 'Matched', ar: 'مطابقة' }, + 'rpt.wb.noPermit': { en: 'No permit found', ar: 'بدون إرسالية' }, + + // ---- page extras + 'rpt.f.required': { en: 'Fill in the required filters to run this report: {names}', ar: 'يرجى تعبئة معايير البحث المطلوبة لعرض التقرير: {names}' }, + 'rpt.menu.tables': { en: 'Tabular reports', ar: 'التقارير الجدولية' }, + 'rpt.det.company': { en: 'Company', ar: 'الشركة' }, + 'rpt.det.subtotal': { en: 'Company total', ar: 'إجمالي الشركة' }, + 'rpt.quota.kind': { en: 'Type', ar: 'النوع' }, + 'rpt.freq.group': { en: 'Group', ar: 'المجموعة' }, + 'rpt.imp.fileTypes': { en: 'CSV or Excel files', ar: 'ملفات CSV أو Excel' }, + 'rpt.wb.noFolder': { en: 'Enter the folder path first.', ar: 'أدخل مسار المجلد أولاً.' }, + 'rpt.wb.fileName': { en: 'File', ar: 'الملف' }, + 'rpt.wb.failed': { en: 'Failed', ar: 'فشلت' }, + 'rpt.f.name.orderDate': { en: 'Order date', ar: 'تاريخ الطلبية' }, +}); diff --git a/web/src/i18n/featureStrings.ts b/web/src/i18n/featureStrings.ts new file mode 100644 index 0000000..2e122c7 --- /dev/null +++ b/web/src/i18n/featureStrings.ts @@ -0,0 +1,15 @@ +import type { L10n, Lang } from './ui'; + +// Auto-collects every feature strings.ts (default export or `strings`) for backend-caption lookups. +const modules = import.meta.glob<{ default?: Record; strings?: Record }>( + '../features/*/strings.ts', + { eager: true }, +); + +const registry: Record = {}; +for (const m of Object.values(modules)) Object.assign(registry, m.default ?? m.strings ?? {}); + +export function lookupFeatureString(key: string, lang: Lang): string | undefined { + const e = registry[key]; + return e ? e[lang] || e.ar : undefined; +} diff --git a/web/src/i18n/ui.ts b/web/src/i18n/ui.ts new file mode 100644 index 0000000..889e389 --- /dev/null +++ b/web/src/i18n/ui.ts @@ -0,0 +1,143 @@ +/** + * Built-in UI string table. One file, typed by key (a typo is a compile error). + * Pre-login pages use ONLY this table. Features add their own strings in + * `features//strings.ts` (see useFeatureUi) - do not edit this file per slice. + */ +export type Lang = 'ar' | 'en'; +export type L10n = { en: string; ar: string }; + +export const ui = { + // app / brand + 'app.name': { en: 'Nafith Customer System', ar: 'نظام نافذ للعملاء' }, + 'app.title': { en: 'Nafith', ar: 'نافذ' }, + + // login + 'login.title': { en: 'Sign in', ar: 'تسجيل الدخول' }, + 'login.subtitle': { en: 'Enter your account details to continue', ar: 'أدخل بيانات حسابك للمتابعة' }, + 'login.username': { en: 'Username', ar: 'اسم المستخدم' }, + 'login.password': { en: 'Password', ar: 'كلمة المرور' }, + 'login.submit': { en: 'Sign in', ar: 'دخول' }, + 'login.submitting': { en: 'Signing in...', ar: 'جاري تسجيل الدخول...' }, + 'login.required': { en: 'Enter your username and password', ar: 'أدخل اسم المستخدم وكلمة المرور' }, + 'login.failed': { en: 'Sign in failed. Check your details and try again.', ar: 'تعذر تسجيل الدخول. تحقق من البيانات وحاول مرة أخرى.' }, + 'login.showPassword': { en: 'Show password', ar: 'إظهار كلمة المرور' }, + 'login.hidePassword': { en: 'Hide password', ar: 'إخفاء كلمة المرور' }, + + // nav / shell + 'nav.home': { en: 'Home', ar: 'الرئيسية' }, + 'nav.dashboard': { en: 'Dashboard', ar: 'لوحة المعلومات' }, + 'nav.menu': { en: 'Menu', ar: 'القائمة' }, + 'nav.collapse': { en: 'Collapse menu', ar: 'طي القائمة' }, + 'nav.expand': { en: 'Expand menu', ar: 'توسيع القائمة' }, + 'nav.create': { en: 'Create new', ar: 'إنشاء جديد' }, + 'nav.quickLinks': { en: 'Quick links', ar: 'روابط سريعة' }, + 'nav.empty': { en: 'No pages are available for your role yet.', ar: 'لا توجد صفحات متاحة لدورك حتى الآن.' }, + 'nav.notFoundTitle': { en: 'Page not found', ar: 'الصفحة غير موجودة' }, + 'nav.notFoundText': { en: 'The page you are looking for does not exist or was moved.', ar: 'الصفحة التي تبحث عنها غير موجودة أو تم نقلها.' }, + 'nav.forbiddenTitle': { en: 'Not allowed', ar: 'غير مصرح' }, + 'nav.forbiddenText': { en: 'Your role does not have access to this page.', ar: 'ليس لدور حسابك صلاحية الوصول إلى هذه الصفحة.' }, + 'nav.backHome': { en: 'Back to home', ar: 'العودة إلى الرئيسية' }, + 'dash.welcome': { en: 'Welcome, {name}', ar: 'مرحباً، {name}' }, + 'dash.role': { en: 'Role', ar: 'الدور' }, + 'dash.location': { en: 'Location', ar: 'الموقع' }, + 'dash.company': { en: 'Company', ar: 'الشركة' }, + + // user menu / account + 'user.menu': { en: 'Account', ar: 'الحساب' }, + 'user.logout': { en: 'Sign out', ar: 'تسجيل الخروج' }, + 'user.changePassword': { en: 'Change password', ar: 'تغيير كلمة المرور' }, + 'user.currentPassword': { en: 'Current password', ar: 'كلمة المرور الحالية' }, + 'user.newPassword': { en: 'New password', ar: 'كلمة المرور الجديدة' }, + 'user.confirmPassword': { en: 'Confirm new password', ar: 'تأكيد كلمة المرور الجديدة' }, + 'user.passwordMismatch': { en: 'The passwords do not match', ar: 'كلمتا المرور غير متطابقتين' }, + 'user.passwordChanged': { en: 'Password changed', ar: 'تم تغيير كلمة المرور' }, + 'user.sessionExpired': { en: 'Your session has expired. Please sign in again.', ar: 'انتهت جلستك. الرجاء تسجيل الدخول مرة أخرى.' }, + + // toggles + 'lang.toggle': { en: 'Switch language', ar: 'تبديل اللغة' }, + 'lang.other': { en: 'العربية', ar: 'English' }, + 'theme.toggle': { en: 'Switch theme', ar: 'تبديل المظهر' }, + 'theme.light': { en: 'Light mode', ar: 'الوضع الفاتح' }, + 'theme.dark': { en: 'Dark mode', ar: 'الوضع الداكن' }, + + // common buttons + 'common.save': { en: 'Save', ar: 'حفظ' }, + 'common.cancel': { en: 'Cancel', ar: 'إلغاء' }, + 'common.close': { en: 'Close', ar: 'إغلاق' }, + 'common.back': { en: 'Back', ar: 'رجوع' }, + 'common.next': { en: 'Next', ar: 'التالي' }, + 'common.edit': { en: 'Edit', ar: 'تعديل' }, + 'common.view': { en: 'View', ar: 'عرض' }, + 'common.delete': { en: 'Delete', ar: 'حذف' }, + 'common.create': { en: 'New', ar: 'جديد' }, + 'common.search': { en: 'Search', ar: 'بحث' }, + 'common.apply': { en: 'Apply', ar: 'تطبيق' }, + 'common.clear': { en: 'Clear', ar: 'مسح' }, + 'common.clearFilters': { en: 'Clear filters', ar: 'مسح التصفية' }, + 'common.filters': { en: 'Filters', ar: 'التصفية' }, + 'common.all': { en: 'All', ar: 'الكل' }, + 'common.actions': { en: 'Actions', ar: 'الإجراءات' }, + 'common.yes': { en: 'Yes', ar: 'نعم' }, + 'common.no': { en: 'No', ar: 'لا' }, + 'common.select': { en: 'Select...', ar: 'اختر...' }, + 'common.noOptions': { en: 'No options', ar: 'لا توجد خيارات' }, + 'common.retry': { en: 'Try again', ar: 'إعادة المحاولة' }, + 'common.refresh': { en: 'Refresh', ar: 'تحديث' }, + 'common.required': { en: 'This field is required', ar: 'هذا الحقل مطلوب' }, + 'common.invalid': { en: 'The value is not valid', ar: 'القيمة غير صالحة' }, + 'common.maxLength': { en: 'Maximum {n} characters', ar: 'الحد الأقصى {n} حرفاً' }, + 'common.min': { en: 'Minimum value is {n}', ar: 'الحد الأدنى للقيمة {n}' }, + 'common.max': { en: 'Maximum value is {n}', ar: 'الحد الأقصى للقيمة {n}' }, + 'common.fixErrors': { en: 'Please fix the highlighted fields', ar: 'يرجى تصحيح الحقول المظللة' }, + 'common.upload': { en: 'Choose file', ar: 'اختيار ملف' }, + 'common.uploading': { en: 'Uploading...', ar: 'جاري الرفع...' }, + 'common.uploaded': { en: 'File attached', ar: 'تم إرفاق الملف' }, + 'common.removeFile': { en: 'Remove file', ar: 'إزالة الملف' }, + 'common.uploadFailed': { en: 'File upload failed', ar: 'فشل رفع الملف' }, + + // grid + 'grid.loadingFirst': { en: 'Loading the list from the system...', ar: 'جاري تحميل القائمة من النظام...' }, + 'grid.loadingUpdate': { en: 'Updating the results...', ar: 'جاري تحديث النتائج...' }, + 'grid.loadingSlow': { en: 'Large lists can take a few more seconds.', ar: 'القوائم الكبيرة قد تستغرق بضع ثوانٍ إضافية.' }, + 'grid.empty': { en: 'No results found', ar: 'لا توجد نتائج' }, + 'grid.emptyHint': { en: 'Nothing matches the current filters.', ar: 'لا توجد بيانات تطابق التصفية الحالية.' }, + 'grid.emptyNoFilters': { en: 'There are no records yet.', ar: 'لا توجد سجلات حتى الآن.' }, + 'grid.error': { en: 'Could not load the list', ar: 'تعذر تحميل القائمة' }, + 'grid.rowsPerPage': { en: 'Rows per page', ar: 'عدد الصفوف' }, + 'grid.displayedRows': { en: '{from}-{to} of {count}', ar: '{from}-{to} من {count}' }, + 'grid.filterTitle': { en: 'Filter results', ar: 'تصفية النتائج' }, + 'grid.status': { en: 'Status', ar: 'الحالة' }, + 'grid.clearAll': { en: 'Clear all', ar: 'مسح الكل' }, + 'grid.requireFilter': { en: 'Choose at least one filter to load this list.', ar: 'اختر معياراً واحداً على الأقل لتحميل هذه القائمة.' }, + + // dialogs / overlay + 'confirm.title': { en: 'Please confirm', ar: 'يرجى التأكيد' }, + 'confirm.save': { en: 'Do you want to save?', ar: 'هل تريد الحفظ؟' }, + 'confirm.delete': { en: 'Do you want to delete this record?', ar: 'هل تريد حذف هذا السجل؟' }, + 'confirm.yes': { en: 'Confirm', ar: 'تأكيد' }, + 'confirm.no': { en: 'Cancel', ar: 'إلغاء' }, + 'busy.saving': { en: 'Saving...', ar: 'جاري الحفظ...' }, + 'busy.savingHint': { en: 'Please wait, do not close this page.', ar: 'يرجى الانتظار وعدم إغلاق الصفحة.' }, + + // toasts / errors + 'toast.saved': { en: 'Saved successfully', ar: 'تم الحفظ بنجاح' }, + 'toast.done': { en: 'Done', ar: 'تمت العملية' }, + 'toast.close': { en: 'Dismiss', ar: 'إخفاء' }, + 'error.generic': { en: 'Something went wrong. Please try again.', ar: 'حدث خطأ ما. يرجى المحاولة مرة أخرى.' }, + 'error.network': { en: 'Cannot reach the server. Check your connection.', ar: 'تعذر الاتصال بالخادم. تحقق من الاتصال.' }, + 'error.forbidden': { en: 'You do not have permission to do this.', ar: 'ليس لديك صلاحية لتنفيذ هذا الإجراء.' }, + 'error.notFound': { en: 'The requested item was not found.', ar: 'العنصر المطلوب غير موجود.' }, +} as const satisfies Record; + +export type UiKey = keyof typeof ui; + +export function format(text: string, vars?: Record): string { + if (!vars) return text; + return text.replace(/\{(\w+)\}/g, (_, k: string) => (k in vars ? String(vars[k]) : `{${k}}`)); +} + +/** Non-hook lookup (API client, mock layer). */ +export function uiText(key: UiKey, lang: Lang, vars?: Record): string { + const entry: L10n = ui[key]; + return format(entry[lang] || entry.ar, vars); +} diff --git a/web/src/i18n/useUi.ts b/web/src/i18n/useUi.ts new file mode 100644 index 0000000..3aba822 --- /dev/null +++ b/web/src/i18n/useUi.ts @@ -0,0 +1,50 @@ +import { useCallback, useMemo } from 'react'; +import { useLanguage } from '@/providers/LanguageProvider'; +import { format, ui, type L10n, type Lang, type UiKey } from './ui'; + +export interface UiApi { + lang: Lang; + dir: 'rtl' | 'ltr'; + /** Typed lookup in the shell table. */ + t: (key: UiKey, vars?: Record) => string; + /** Pick the current language from an inline {en, ar} label (metadata, menu titles...). */ + tr: (label: L10n | string | undefined) => string; +} + +export function useUi(): UiApi { + const { lang, dir } = useLanguage(); + const t = useCallback( + (key: UiKey, vars?: Record) => { + const e: L10n = ui[key]; + return format(e[lang] || e.ar, vars); + }, + [lang], + ); + const tr = useCallback( + (label: L10n | string | undefined) => + label === undefined ? '' : typeof label === 'string' ? label : label[lang] || label.ar, + [lang], + ); + return useMemo(() => ({ lang, dir, t, tr }), [lang, dir, t, tr]); +} + +/** Declare a feature string table with full key typing: `export default defineStrings({...})`. */ +export function defineStrings>(s: S): S { + return s; +} + +/** + * Feature-level strings: `const { t } = useFeatureUi(strings)`. `t` accepts the feature's keys AND the shell keys, + * so a feature never needs to edit ui.ts. + */ +export function useFeatureUi>(strings: S) { + const base = useUi(); + const t = useCallback( + (key: (keyof S & string) | UiKey, vars?: Record) => { + const e = (strings as Record)[key] ?? (ui as Record)[key]; + return format(e ? e[base.lang] || e.ar : key, vars); + }, + [strings, base.lang], + ); + return useMemo(() => ({ ...base, t }), [base, t]); +} diff --git a/web/src/lib/pdf.ts b/web/src/lib/pdf.ts new file mode 100644 index 0000000..bae15e4 --- /dev/null +++ b/web/src/lib/pdf.ts @@ -0,0 +1,49 @@ +/** + * Render a DOM element to an A5 PDF in the browser and return an object URL for it. + * html2canvas rasterises the element, so Arabic shaping / RTL and the page fonts come out exactly as on screen + * (text in the PDF is an image, not selectable). Both libraries are loaded on demand, only when a PDF is made. + * Always rendered black on white, whatever the current theme. + */ +export type PdfOrientation = 'portrait' | 'landscape'; + +export async function elementToPdfUrl(el: HTMLElement, orientation: PdfOrientation): Promise { + const [{ default: html2canvas }, { jsPDF }] = await Promise.all([import('html2canvas'), import('jspdf')]); + + // let web fonts (Cairo) finish loading so the capture does not fall back to a system font + if ('fonts' in document) await (document as Document & { fonts: FontFaceSet }).fonts.ready; + + const canvas = await html2canvas(el, { + scale: 2, + backgroundColor: '#ffffff', + useCORS: true, + logging: false, + onclone: (doc, cloned) => { + // print is always light: neutralise the dark theme / paper colours in the cloned tree only + const root = cloned as HTMLElement; + // any letter-spacing makes html2canvas draw Arabic letter by letter, which breaks the joining: keep the default + root.style.letterSpacing = 'normal'; + root.querySelectorAll('*').forEach((n) => { n.style.letterSpacing = 'normal'; }); + // a sheet designed black-on-white (the legacy slips) keeps its own colours and borders + if (root.hasAttribute('data-pdf-literal')) { void doc; return; } + root.style.background = '#ffffff'; + root.style.boxShadow = 'none'; + root.style.color = '#000000'; + root.querySelectorAll('*').forEach((n) => { + n.style.color = '#000000'; + if (getComputedStyle(n).backgroundColor !== 'rgba(0, 0, 0, 0)') n.style.backgroundColor = '#ffffff'; + n.style.borderColor = '#999999'; + }); + void doc; + }, + }); + + const pdf = new jsPDF({ unit: 'mm', format: 'a5', orientation }); + const pageW = pdf.internal.pageSize.getWidth(); + const pageH = pdf.internal.pageSize.getHeight(); + const margin = 6; + const ratio = Math.min((pageW - margin * 2) / canvas.width, (pageH - margin * 2) / canvas.height); + const w = canvas.width * ratio; + const h = canvas.height * ratio; + pdf.addImage(canvas.toDataURL('image/jpeg', 0.95), 'JPEG', (pageW - w) / 2, margin, w, h); + return URL.createObjectURL(pdf.output('blob')); +} diff --git a/web/src/lib/storage.ts b/web/src/lib/storage.ts new file mode 100644 index 0000000..4073b08 --- /dev/null +++ b/web/src/lib/storage.ts @@ -0,0 +1,16 @@ +/** localStorage / sessionStorage wrappers: storage can be blocked, so every access is try/catch. */ +export function lsGet(key: string): string | null { + try { return window.localStorage.getItem(key); } catch { return null; } +} +export function lsSet(key: string, value: string): void { + try { window.localStorage.setItem(key, value); } catch { /* ignore */ } +} +export function ssGet(key: string): string | null { + try { return window.sessionStorage.getItem(key); } catch { return null; } +} +export function ssSet(key: string, value: string | null): void { + try { + if (value === null) window.sessionStorage.removeItem(key); + else window.sessionStorage.setItem(key, value); + } catch { /* ignore */ } +} diff --git a/web/src/main.tsx b/web/src/main.tsx new file mode 100644 index 0000000..770a4d3 --- /dev/null +++ b/web/src/main.tsx @@ -0,0 +1,12 @@ +import { StrictMode } from 'react'; +import { createRoot } from 'react-dom/client'; +import { App } from './App'; +import { AppProviders } from './providers/AppProviders'; + +createRoot(document.getElementById('root')!).render( + + + + + , +); diff --git a/web/src/providers/AppProviders.tsx b/web/src/providers/AppProviders.tsx new file mode 100644 index 0000000..5921173 --- /dev/null +++ b/web/src/providers/AppProviders.tsx @@ -0,0 +1,43 @@ +import { useState, type ReactNode } from 'react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { ApiError } from '@/api/client'; +import { GlobalProgress, SavingOverlay } from '@/components/BusyIndicators'; +import { AuthProvider } from './AuthProvider'; +import { ConfirmProvider } from './ConfirmProvider'; +import { LanguageProvider } from './LanguageProvider'; +import { AppThemeProvider } from './ThemeProvider'; +import { ToastProvider } from './ToastProvider'; + +function makeClient() { + return new QueryClient({ + defaultOptions: { + queries: { + staleTime: 30_000, + refetchOnWindowFocus: false, + retry: (count, err) => !(err instanceof ApiError && err.status >= 400 && err.status < 500) && count < 1, + }, + }, + }); +} + +/** Order matters: language -> theme (needs dir) -> query -> toast/confirm (need ui) -> auth. */ +export function AppProviders({ children }: { children: ReactNode }) { + const [client] = useState(makeClient); + return ( + + + + + + + + {children} + + + + + + + + ); +} diff --git a/web/src/providers/AuthProvider.tsx b/web/src/providers/AuthProvider.tsx new file mode 100644 index 0000000..46571b5 --- /dev/null +++ b/web/src/providers/AuthProvider.tsx @@ -0,0 +1,110 @@ +import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { authApi, type AuthUser, type Permissions } from '@/api/auth'; +import { getToken, setToken, setUnauthorizedHandler } from '@/api/client'; +import type { Lang } from '@/i18n/ui'; +import { useUi } from '@/i18n/useUi'; +import { useLanguage } from './LanguageProvider'; +import { useToast } from './ToastProvider'; + +type Status = 'loading' | 'authed' | 'anon'; + +interface AuthCtx { + status: Status; + user: AuthUser | null; + login: (username: string, password: string) => Promise; + logout: () => void; + /** Backend set-language first, then flip the UI and refetch (see LanguageProvider.setLang). */ + changeLanguage: (lang: Lang) => Promise; + /** True if the user's role is allowed by `roles` (empty/undefined = everyone). */ + hasRole: (roles?: string[]) => boolean; + /** Backend-driven visibility: true if the role may see the module/screen/action `key` (SU: everything). */ + can: (key: string) => boolean; +} +const Ctx = createContext(null); + +export function AuthProvider({ children }: { children: ReactNode }) { + const qc = useQueryClient(); + const toast = useToast(); + const { t } = useUi(); + const { lang, setLang } = useLanguage(); + const [user, setUser] = useState(null); + const [perms, setPerms] = useState(null); + const [status, setStatus] = useState(() => (getToken() ? 'loading' : 'anon')); + + // Restore the session (sessionStorage token) once. + useEffect(() => { + if (!getToken()) return; + let alive = true; + authApi.me().then( + async (u) => { + const p = await authApi.permissions().catch(() => null); + if (alive) { setUser(u); setPerms(p); setStatus('authed'); } + }, + () => { if (alive) { setToken(null); setStatus('anon'); } }, + ); + return () => { alive = false; }; + }, []); + + const logout = useCallback(() => { + setToken(null); + setUser(null); + setPerms(null); + setStatus('anon'); + qc.clear(); + }, [qc]); + + useEffect(() => { + setUnauthorizedHandler(() => { + if (getToken()) toast.warning(t('user.sessionExpired')); + logout(); + }); + return () => setUnauthorizedHandler(null); + }, [logout, toast, t]); + + const login = useCallback( + async (username: string, password: string) => { + const r = await authApi.login(username, password); + setToken(r.token); + // permissions first, so the menu never flashes screens the role may not see + const p = await authApi.permissions().catch(() => null); + setUser(r.user); + setPerms(p); + setStatus('authed'); + // keep the UI language the user chose; tell the backend if its session language differs + if (r.user.lang && r.user.lang.toLowerCase() !== lang) authApi.setLanguage(lang).catch(() => {}); + }, + [lang], + ); + + const changeLanguage = useCallback( + async (next: Lang) => { + await setLang(next, getToken() ? (l) => authApi.setLanguage(l) : undefined); + if (getToken()) await qc.invalidateQueries(); + }, + [setLang, qc], + ); + + const hasRole = useCallback( + (roles?: string[]) => !roles?.length || (!!user && roles.map((r) => r.toUpperCase()).includes(user.roleCode.toUpperCase())), + [user], + ); + + // No permissions answer (request failed) = nothing is allowed except for the role checks above; SU gets all=true. + const can = useCallback( + (key: string) => !!perms && (perms.all || perms.allowed.includes(key)), + [perms], + ); + + const value = useMemo( + () => ({ status, user, login, logout, changeLanguage, hasRole, can }), + [status, user, login, logout, changeLanguage, hasRole, can], + ); + return {children}; +} + +export function useAuth(): AuthCtx { + const v = useContext(Ctx); + if (!v) throw new Error('useAuth must be used inside AuthProvider'); + return v; +} diff --git a/web/src/providers/ConfirmProvider.tsx b/web/src/providers/ConfirmProvider.tsx new file mode 100644 index 0000000..0cf1b7e --- /dev/null +++ b/web/src/providers/ConfirmProvider.tsx @@ -0,0 +1,56 @@ +import { createContext, useCallback, useContext, useRef, useState, type ReactNode } from 'react'; +import { ConfirmDialog } from '@/components/ConfirmDialog'; +import { useUi } from '@/i18n/useUi'; + +export interface ConfirmOptions { + title?: string; + message?: string; + confirmText?: string; + cancelText?: string; + danger?: boolean; +} +type ConfirmFn = (opts?: ConfirmOptions) => Promise; +const Ctx = createContext(null); + +/** `const confirm = useConfirm(); if (await confirm({ message })) save();` */ +export function ConfirmProvider({ children }: { children: ReactNode }) { + const { t } = useUi(); + const [opts, setOpts] = useState(null); + const resolver = useRef<((v: boolean) => void) | null>(null); + + const confirm = useCallback((o) => { + return new Promise((resolve) => { + resolver.current?.(false); + resolver.current = resolve; + setOpts(o ?? {}); + }); + }, []); + + const finish = (v: boolean) => { + resolver.current?.(v); + resolver.current = null; + setOpts(null); + }; + + return ( + + {children} + finish(true)} + onCancel={() => finish(false)} + /> + + ); +} + +export function useConfirm(): ConfirmFn { + const v = useContext(Ctx); + if (!v) throw new Error('useConfirm must be used inside ConfirmProvider'); + return v; +} diff --git a/web/src/providers/LanguageProvider.tsx b/web/src/providers/LanguageProvider.tsx new file mode 100644 index 0000000..28382d1 --- /dev/null +++ b/web/src/providers/LanguageProvider.tsx @@ -0,0 +1,60 @@ +import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'; +import type { Lang } from '@/i18n/ui'; +import { lsGet, lsSet } from '@/lib/storage'; +import { setApiLang } from '@/api/client'; + +const KEY = 'ntp.lang'; + +interface LanguageCtx { + lang: Lang; + dir: 'rtl' | 'ltr'; + /** False while a language switch is in flight (backend "set language" call). Gate language-dependent queries on it. */ + langReady: boolean; + /** + * Switch language. `beforeApply` (e.g. the backend set-language call) runs FIRST; the UI flips afterwards, + * so language-dependent queries never fire in the gap and get cached under the wrong language. + */ + setLang: (lang: Lang, beforeApply?: (lang: Lang) => Promise) => Promise; +} + +const Ctx = createContext(null); + +function initialLang(): Lang { + // Arabic only for now (the English option was removed); the stored value is ignored. + void lsGet(KEY); + return 'ar'; +} + +export function LanguageProvider({ children }: { children: ReactNode }) { + const [lang, setLangState] = useState(initialLang); + const [switching, setSwitching] = useState(false); + const dir = lang === 'ar' ? 'rtl' : 'ltr'; + + useEffect(() => { + document.documentElement.lang = lang; + document.documentElement.dir = dir; + setApiLang(lang); + }, [lang, dir]); + + const setLang = useCallback(async (next: Lang, beforeApply?: (l: Lang) => Promise) => { + setSwitching(true); + try { + if (beforeApply) await beforeApply(next); + } catch { + /* the UI language still changes even if the backend call fails */ + } + lsSet(KEY, next); + setApiLang(next); + setLangState(next); + setSwitching(false); + }, []); + + const value = useMemo(() => ({ lang, dir, langReady: !switching, setLang }) as LanguageCtx, [lang, dir, switching, setLang]); + return {children}; +} + +export function useLanguage(): LanguageCtx { + const v = useContext(Ctx); + if (!v) throw new Error('useLanguage must be used inside LanguageProvider'); + return v; +} diff --git a/web/src/providers/ThemeProvider.tsx b/web/src/providers/ThemeProvider.tsx new file mode 100644 index 0000000..b9a62d4 --- /dev/null +++ b/web/src/providers/ThemeProvider.tsx @@ -0,0 +1,57 @@ +import { createContext, useContext, useEffect, useMemo, useState, useCallback, type ReactNode } from 'react'; +import { CacheProvider } from '@emotion/react'; +import createCache from '@emotion/cache'; +import { prefixer } from 'stylis'; +import rtlPlugin from 'stylis-plugin-rtl'; +import { CssBaseline, ThemeProvider as MuiThemeProvider } from '@mui/material'; +import { lsGet, lsSet } from '@/lib/storage'; +import { buildTheme } from '@/theme/theme'; +import type { ThemeMode } from '@/theme/tokens'; +import { useLanguage } from './LanguageProvider'; + +const KEY = 'ntp.theme'; + +// Two Emotion caches: custom CSS (not only MUI components) mirrors in RTL. +const cacheLtr = createCache({ key: 'ntp-ltr', stylisPlugins: [prefixer] }); +const cacheRtl = createCache({ key: 'ntp-rtl', stylisPlugins: [prefixer, rtlPlugin as never] }); + +interface ThemeCtx { + mode: ThemeMode; + setMode: (m: ThemeMode) => void; + toggle: () => void; +} +const Ctx = createContext(null); + +export function AppThemeProvider({ children }: { children: ReactNode }) { + const { dir } = useLanguage(); + // Light is the default; prefers-color-scheme is intentionally ignored. A saved explicit choice wins. + const [mode, setModeState] = useState(() => (lsGet(KEY) === 'dark' ? 'dark' : 'light')); + const setMode = useCallback((m: ThemeMode) => { + lsSet(KEY, m); + setModeState(m); + }, []); + const toggle = useCallback(() => setMode(mode === 'dark' ? 'light' : 'dark'), [mode, setMode]); + + useEffect(() => { + document.documentElement.dataset.theme = mode; + document.documentElement.style.colorScheme = mode; + }, [mode]); + + const theme = useMemo(() => buildTheme(mode, dir), [mode, dir]); + const value = useMemo(() => ({ mode, setMode, toggle }), [mode, setMode, toggle]); + + return ( + + + + {children} + + + ); +} + +export function useThemeMode(): ThemeCtx { + const v = useContext(Ctx); + if (!v) throw new Error('useThemeMode must be used inside AppThemeProvider'); + return v; +} diff --git a/web/src/providers/ToastProvider.tsx b/web/src/providers/ToastProvider.tsx new file mode 100644 index 0000000..3bbe6c8 --- /dev/null +++ b/web/src/providers/ToastProvider.tsx @@ -0,0 +1,87 @@ +import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'; +import { Alert, Snackbar } from '@mui/material'; +import { useUi } from '@/i18n/useUi'; +import { lookupFeatureString } from '@/i18n/featureStrings'; +import { useLanguage } from './LanguageProvider'; + +type Severity = 'success' | 'warning' | 'error' | 'info'; +interface ToastItem { id: number; message: string; severity: Severity; at: number } + +interface ToastApi { + success: (message: string) => void; + warning: (message: string) => void; + error: (message: string) => void; + info: (message: string) => void; + /** + * Call when the user moves to another page: removes the message that was already on screen before the move. A message created + * in the same moment as the move (e.g. "saved" right before redirecting to the new record) is kept. + */ + dismissOnNavigate: () => void; +} + +/** A toast younger than this when the route changes belongs to the action that caused the navigation. */ +const KEEP_WHEN_NAVIGATING_MS = 800; +const Ctx = createContext(null); +let seq = 0; + +const CAPTION_KEY = /^[A-Z0-9_.]+$/; + +export function ToastProvider({ children }: { children: ReactNode }) { + const { t } = useUi(); + const { lang } = useLanguage(); + // One message at a time: a new message replaces the current one immediately (no queue of old messages) + const [current, setCurrent] = useState(null); + + const push = useCallback( + (severity: Severity, raw: string) => { + // Backend text is shown verbatim; only caption-LIKE keys are translated (when a feature string exists). + const message = CAPTION_KEY.test(raw) ? lookupFeatureString(raw, lang) ?? raw : raw; + setCurrent({ id: ++seq, message, severity, at: Date.now() }); + }, + [lang], + ); + const api = useMemo( + () => ({ + success: (m) => push('success', m), + warning: (m) => push('warning', m), + error: (m) => push('error', m), + info: (m) => push('info', m), + dismissOnNavigate: () => setCurrent((c) => (c && Date.now() - c.at > KEEP_WHEN_NAVIGATING_MS ? null : c)), + }), + [push], + ); + const close = (id: number) => setCurrent((c) => (c && c.id === id ? null : c)); + + return ( + + {children} + {current && ( + reason !== 'clickaway' && close(current.id)} + anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }} + sx={{ zIndex: (th) => th.zIndex.snackbar + 10 }} + > + close(current.id)} + closeText={t('toast.close')} + sx={{ minWidth: 280, maxWidth: 560, whiteSpace: 'pre-line', alignItems: 'center' }} + > + {current.message} + + + )} + + ); +} + +export function useToast(): ToastApi { + const v = useContext(Ctx); + if (!v) throw new Error('useToast must be used inside ToastProvider'); + return v; +} diff --git a/web/src/registry.ts b/web/src/registry.ts new file mode 100644 index 0000000..21574a4 --- /dev/null +++ b/web/src/registry.ts @@ -0,0 +1,19 @@ +import type { RouteObject } from 'react-router-dom'; +import type { MenuItem } from '@/shell/types'; + +interface FeatureModule { + routes?: RouteObject[]; + menu?: MenuItem[]; +} + +/** + * Feature registry: every `features//routes.tsx` is picked up automatically. + * A feature exports `routes: RouteObject[]` (absolute paths, e.g. '/grains/permits') and `menu: MenuItem[]`. + * Do NOT edit shell files to add a feature. + */ +const modules = import.meta.glob('./features/*/routes.tsx', { eager: true }); + +const sorted = Object.entries(modules).sort(([a], [b]) => a.localeCompare(b)); + +export const featureRoutes: RouteObject[] = sorted.flatMap(([, m]) => m.routes ?? []); +export const featureMenu: MenuItem[] = sorted.flatMap(([, m]) => m.menu ?? []); diff --git a/web/src/shell/AppShell.tsx b/web/src/shell/AppShell.tsx new file mode 100644 index 0000000..6876eaf --- /dev/null +++ b/web/src/shell/AppShell.tsx @@ -0,0 +1,45 @@ +import { useMemo, useState } from 'react'; +import { Outlet, useLocation } from 'react-router-dom'; +import { Box, useMediaQuery, type Theme } from '@mui/material'; +import { lsGet, lsSet } from '@/lib/storage'; +import { featureMenu } from '@/registry'; +import { useAuth } from '@/providers/AuthProvider'; +import { ForbiddenPage } from './ErrorPages'; +import { filterMenu, findOwner, itemAllowed } from './menuUtils'; +import { Sidebar } from './Sidebar'; +import { TopBar } from './TopBar'; + +export function AppShell() { + const { hasRole, can } = useAuth(); + const { pathname } = useLocation(); + const isDesktop = useMediaQuery((t: Theme) => t.breakpoints.up('md')); + const [collapsed, setCollapsed] = useState(() => lsGet('ntp.nav.collapsed') === '1'); + const [mobileOpen, setMobileOpen] = useState(false); + + const isAllowed = useMemo(() => itemAllowed(hasRole, can), [hasRole, can]); + const menu = useMemo(() => filterMenu(featureMenu, isAllowed, can), [isAllowed, can]); + + // Route-level role guard: the menu entry that owns this URL decides (full menu, not the filtered one). + const owner = findOwner(featureMenu, pathname); + const allowed = !owner || isAllowed(owner.item) && owner.trail.every((g) => hasRole(g.roles)); + + return ( + + setCollapsed((c) => { lsSet('ntp.nav.collapsed', c ? '0' : '1'); return !c; })} + mobileOpen={mobileOpen} + onMobileClose={() => setMobileOpen(false)} + isDesktop={isDesktop} + /> + + setMobileOpen(true)} menu={menu} + onToggleCollapsed={() => setCollapsed((c) => { lsSet('ntp.nav.collapsed', c ? '0' : '1'); return !c; })} /> + + {allowed ? : } + + + + ); +} diff --git a/web/src/shell/Breadcrumbs.tsx b/web/src/shell/Breadcrumbs.tsx new file mode 100644 index 0000000..08eebe6 --- /dev/null +++ b/web/src/shell/Breadcrumbs.tsx @@ -0,0 +1,46 @@ +import { Link as RouterLink, useLocation, useMatches } from 'react-router-dom'; +import { Breadcrumbs as MuiBreadcrumbs, Link, Typography } from '@mui/material'; +import NavigateNextIcon from '@mui/icons-material/NavigateNext'; +import { useUi } from '@/i18n/useUi'; +import type { L10n } from '@/i18n/ui'; +import { findOwner } from './menuUtils'; +import type { MenuItem } from './types'; + +/** Route `handle: { crumb: L10n }` adds an extra trailing crumb (e.g. "New" / "Edit") for pages not in the menu. */ +export interface RouteHandle { crumb?: L10n } + +export function Breadcrumbs({ menu }: { menu: MenuItem[] }) { + const { t, tr, dir } = useUi(); + const { pathname } = useLocation(); + const matches = useMatches(); + if (pathname === '/') return null; + + const owner = findOwner(menu, pathname); + const crumbs: { label: string; to?: string }[] = [{ label: t('nav.home'), to: '/' }]; + if (owner) { + for (const g of owner.trail) crumbs.push({ label: tr(g.title) }); + const onCreate = owner.item.createPath && pathname.startsWith(owner.item.createPath) && owner.item.createPath !== owner.item.path; + crumbs.push({ label: tr(owner.item.title), to: onCreate || pathname !== owner.item.path ? owner.item.path : undefined }); + } + for (const m of matches) { + const c = (m.handle as RouteHandle | undefined)?.crumb; + if (c) crumbs.push({ label: tr(c) }); + } + if (crumbs.length < 2) return null; + const last = crumbs.length - 1; + return ( + } + > + {crumbs.map((c, i) => + c.to && i !== last ? ( + {c.label} + ) : ( + {c.label} + ), + )} + + ); +} diff --git a/web/src/shell/ChangePasswordDialog.tsx b/web/src/shell/ChangePasswordDialog.tsx new file mode 100644 index 0000000..4b6224f --- /dev/null +++ b/web/src/shell/ChangePasswordDialog.tsx @@ -0,0 +1,54 @@ +import { useState, type FormEvent } from 'react'; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Stack, TextField } from '@mui/material'; +import { authApi } from '@/api/auth'; +import { ApiError } from '@/api/client'; +import { useWrite } from '@/api/hooks'; +import { useUi } from '@/i18n/useUi'; + +export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose: () => void }) { + const { t } = useUi(); + const [cur, setCur] = useState(''); + const [next, setNext] = useState(''); + const [again, setAgain] = useState(''); + const [err, setErr] = useState>({}); + + const save = useWrite(({ c, n }: { c: string; n: string }) => authApi.changePassword(c, n), { + successMessage: t('user.passwordChanged'), + onSuccess: () => { setCur(''); setNext(''); setAgain(''); onClose(); }, + }); + + function submit(e: FormEvent) { + e.preventDefault(); + const out: Record = {}; + if (!cur) out.cur = t('common.required'); + if (!next) out.next = t('common.required'); + if (next && again !== next) out.again = t('user.passwordMismatch'); + setErr(out); + if (Object.keys(out).length) return; + save.mutate({ c: cur, n: next }, { + onError: (x) => x instanceof ApiError && setErr({ cur: x.fieldErrors.currentPassword ?? '', next: x.fieldErrors.newPassword ?? '' }), + }); + } + + return ( + + + {t('user.changePassword')} + + + setCur(e.target.value)} error={!!err.cur} helperText={err.cur} slotProps={{ htmlInput: { dir: 'ltr' } }} /> + setNext(e.target.value)} error={!!err.next} helperText={err.next} slotProps={{ htmlInput: { dir: 'ltr' } }} /> + setAgain(e.target.value)} error={!!err.again} helperText={err.again} slotProps={{ htmlInput: { dir: 'ltr' } }} /> + + + + + + + + + ); +} diff --git a/web/src/shell/DashboardPage.tsx b/web/src/shell/DashboardPage.tsx new file mode 100644 index 0000000..36349f9 --- /dev/null +++ b/web/src/shell/DashboardPage.tsx @@ -0,0 +1,50 @@ +import { useMemo } from 'react'; +import { Link as RouterLink } from 'react-router-dom'; +import { Alert, Box, Card, CardActionArea, Chip, Stack, Typography } from '@mui/material'; +import { PageHeader } from '@/components/PageHeader'; +import { useUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { featureMenu } from '@/registry'; +import { filterMenu, flatten, itemAllowed } from './menuUtils'; + +/** Simple landing: who you are + quick links to every page the role can open. */ +export function DashboardPage() { + const { t, tr } = useUi(); + const { user, hasRole, can } = useAuth(); + const links = useMemo( + () => flatten(filterMenu(featureMenu, itemAllowed(hasRole, can), can)).filter((e) => e.item.path), + [hasRole, can], + ); + + return ( + <> + + + {user?.roleName && } + {user?.locationName && } + {user?.companyCode && } + + {t('nav.quickLinks')} + {links.length === 0 ? ( + {t('nav.empty')} + ) : ( + + {links.map(({ item, trail }) => { + const Icon = item.icon; + return ( + + + + + {tr(item.title)} + {trail.length > 0 && {trail.map((g) => tr(g.title)).join(' / ')}} + + + + ); + })} + + )} + + ); +} diff --git a/web/src/shell/ErrorPages.tsx b/web/src/shell/ErrorPages.tsx new file mode 100644 index 0000000..4179b41 --- /dev/null +++ b/web/src/shell/ErrorPages.tsx @@ -0,0 +1,24 @@ +import { Link as RouterLink } from 'react-router-dom'; +import { Box, Button, Typography } from '@mui/material'; +import { useUi } from '@/i18n/useUi'; + +function Big({ code, title, text }: { code: string; title: string; text: string }) { + const { t } = useUi(); + return ( + + {code} + {title} + {text} + + + ); +} + +export function NotFoundPage() { + const { t } = useUi(); + return ; +} +export function ForbiddenPage() { + const { t } = useUi(); + return ; +} diff --git a/web/src/shell/LoginPage.tsx b/web/src/shell/LoginPage.tsx new file mode 100644 index 0000000..f3ef003 --- /dev/null +++ b/web/src/shell/LoginPage.tsx @@ -0,0 +1,88 @@ +import { useState, type FormEvent } from 'react'; +import { Navigate, useLocation } from 'react-router-dom'; +import { Alert, Box, Button, Card, CardContent, IconButton, InputAdornment, Stack, TextField, Typography } from '@mui/material'; +import VisibilityIcon from '@mui/icons-material/Visibility'; +import VisibilityOffIcon from '@mui/icons-material/VisibilityOff'; +import { ApiError } from '@/api/client'; +import { Logo } from '@/components/Logo'; +import { useUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { ThemeToggle } from './Toggles'; + +/** Pre-login page: uses ONLY the built-in ui table (no server captions exist before sign-in). */ +export function LoginPage() { + const { t } = useUi(); + const { status, login } = useAuth(); + const location = useLocation(); + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [show, setShow] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + + if (status === 'authed') { + const from = (location.state as { from?: string } | null)?.from; + return ; + } + + async function submit(e: FormEvent) { + e.preventDefault(); + if (!username.trim() || !password) { setError(t('login.required')); return; } + setBusy(true); + setError(''); + try { + await login(username.trim(), password); + } catch (err) { + // backend message verbatim; our own text only when there is none + setError(err instanceof ApiError && err.status !== 0 && err.message ? err.message : err instanceof ApiError ? err.message : t('login.failed')); + } finally { + setBusy(false); + } + } + + return ( + + + + + + + + + + + {t('login.title')} + {t('login.subtitle')} + + {error && {error}} + setUsername(e.target.value)} + autoComplete="username" autoFocus required slotProps={{ htmlInput: { dir: 'ltr', style: { textAlign: 'start' } } }} + /> + setPassword(e.target.value)} + type={show ? 'text' : 'password'} autoComplete="current-password" required + slotProps={{ + htmlInput: { dir: 'ltr' }, + input: { + endAdornment: ( + + setShow((s) => !s)} aria-label={show ? t('login.hidePassword') : t('login.showPassword')}> + {show ? : } + + + ), + }, + }} + /> + + + + + + {t('app.name')} + + ); +} diff --git a/web/src/shell/ProtectedRoute.tsx b/web/src/shell/ProtectedRoute.tsx new file mode 100644 index 0000000..0f3dcac --- /dev/null +++ b/web/src/shell/ProtectedRoute.tsx @@ -0,0 +1,15 @@ +import { Navigate, Outlet, useLocation } from 'react-router-dom'; +import { Box, CircularProgress } from '@mui/material'; +import { useAuth } from '@/providers/AuthProvider'; + +export function ProtectedRoute() { + const { status } = useAuth(); + const location = useLocation(); + if (status === 'loading') { + return ; + } + if (status === 'anon') { + return ; + } + return ; +} diff --git a/web/src/shell/Sidebar.tsx b/web/src/shell/Sidebar.tsx new file mode 100644 index 0000000..8e391c3 --- /dev/null +++ b/web/src/shell/Sidebar.tsx @@ -0,0 +1,202 @@ +import { Fragment, useEffect, useState, type MouseEvent } from 'react'; +import { useLocation, useNavigate } from 'react-router-dom'; +import { + Box, Collapse, Divider, Drawer, IconButton, List, ListItemButton, ListItemText, Menu, MenuItem, Tooltip, Typography, +} from '@mui/material'; +import { alpha } from '@mui/material/styles'; +import AddIcon from '@mui/icons-material/Add'; +import ChevronLeftIcon from '@mui/icons-material/ChevronLeft'; +import ChevronRightIcon from '@mui/icons-material/ChevronRight'; +import ExpandLess from '@mui/icons-material/ExpandLess'; +import ExpandMore from '@mui/icons-material/ExpandMore'; +import HomeIcon from '@mui/icons-material/Home'; +import { Logo } from '@/components/Logo'; +import { useUi } from '@/i18n/useUi'; +import { badgeColors } from '@/theme/tokens'; +import { pathMatches } from './menuUtils'; +import type { MenuItem as Item } from './types'; + +export const DRAWER_FULL = 272; +export const DRAWER_MINI = 76; + +function colorOf(item: Item): string { + if (item.color) return item.color; + let h = 0; + for (const ch of item.key) h = (h * 31 + ch.charCodeAt(0)) >>> 0; + return badgeColors[h % badgeColors.length]!; +} + +/** Coloured icon on a soft tinted badge: stays readable in dark mode and when the menu is expanded. */ +function IconBadge({ item, size = 34 }: { item: Item; size?: number }) { + const c = colorOf(item); + const Icon = item.icon; + return ( + + + + ); +} + +interface SidebarProps { + items: Item[]; + collapsed: boolean; + onToggleCollapsed: () => void; + mobileOpen: boolean; + onMobileClose: () => void; + isDesktop: boolean; +} + +export function Sidebar({ items, collapsed, onToggleCollapsed, mobileOpen, onMobileClose, isDesktop }: SidebarProps) { + const { t, tr, dir } = useUi(); + const HOME: Item = { key: 'home', title: { en: t('nav.home'), ar: t('nav.home') }, icon: HomeIcon, path: '/', color: '#1e88e5' }; + const toEdge = dir === 'rtl' ? ChevronRightIcon : ChevronLeftIcon; + const toContent = dir === 'rtl' ? ChevronLeftIcon : ChevronRightIcon; + const CollapseIcon = toEdge; + const ExpandIcon = toContent; + const navigate = useNavigate(); + const { pathname } = useLocation(); + const mini = isDesktop && collapsed; + const [open, setOpen] = useState>({}); + const [pop, setPop] = useState<{ anchor: HTMLElement; item: Item } | null>(null); + + // open the group that owns the current page + useEffect(() => { + const next: Record = {}; + const walk = (list: Item[]): boolean => { + let any = false; + for (const it of list) { + const own = pathMatches(pathname, it.path) || pathMatches(pathname, it.createPath); + const kid = it.children ? walk(it.children) : false; + if (kid) next[it.key] = true; + any = any || own || kid; + } + return any; + }; + walk(items); + setOpen((o) => ({ ...o, ...next })); + }, [pathname, items]); + + const go = (path: string) => { + navigate(path); + if (!isDesktop) onMobileClose(); + setPop(null); + }; + + const isActive = (it: Item): boolean => + (it.path === '/' ? pathname === '/' : pathMatches(pathname, it.path)) || pathMatches(pathname, it.createPath) || !!it.children?.some(isActive); + + const renderRow = (it: Item, depth: number) => { + const isGroup = !!it.children?.length; + const active = isActive(it); + const title = tr(it.title); + + if (mini) { + return ( + + ) => (isGroup ? setPop({ anchor: e.currentTarget, item: it }) : it.path && go(it.path))} + sx={{ justifyContent: 'center', px: 0, mx: 1, borderRadius: 1.5, minHeight: 46 }} + > + + + + ); + } + + return ( + <> + + (isGroup ? setOpen((o) => ({ ...o, [it.key]: !o[it.key] })) : it.path && go(it.path))} + sx={{ borderRadius: 1.5, gap: 1.25, paddingInlineStart: 1 + depth * 2, py: 0.75, minWidth: 0, flex: 1 }} + > + + + {isGroup && (open[it.key] ? : )} + + {it.createPath && ( + + go(it.createPath!)} sx={{ marginInlineStart: 0.5, color: colorOf(it) }}> + + + + )} + + {isGroup && ( + + {it.children!.map((c) => {renderRow(c, depth + 1)})} + + )} + + ); + }; + + const content = ( + + + {mini ? {t('app.title').charAt(0)} : } + + + + {renderRow(HOME, 0)} + {items.map((it) => {renderRow(it, 0)})} + + {isDesktop && ( + <> + + + + + {mini ? : } + + + + + )} + setPop(null)} anchorOrigin={{ vertical: 'top', horizontal: dir === 'rtl' ? 'left' : 'right' }} transformOrigin={{ vertical: 'top', horizontal: dir === 'rtl' ? 'right' : 'left' }}> + {pop && {tr(pop.item.title)}} + {pop?.item.children?.map((c) => ( + c.path && go(c.path)} sx={{ gap: 1.5, paddingInlineEnd: c.createPath ? 0.5 : 2 }}> + + {tr(c.title)} + {c.createPath && ( + { e.stopPropagation(); go(c.createPath!); }} sx={{ color: colorOf(c) }}> + + + )} + + ))} + + + ); + + if (!isDesktop) { + return ( + + {content} + + ); + } + return ( + + {content} + + ); +} diff --git a/web/src/shell/Toggles.tsx b/web/src/shell/Toggles.tsx new file mode 100644 index 0000000..5a19cd5 --- /dev/null +++ b/web/src/shell/Toggles.tsx @@ -0,0 +1,32 @@ +import { Button, IconButton, Tooltip } from '@mui/material'; +import DarkModeIcon from '@mui/icons-material/DarkMode'; +import LightModeIcon from '@mui/icons-material/LightMode'; +import TranslateIcon from '@mui/icons-material/Translate'; +import { useUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { useThemeMode } from '@/providers/ThemeProvider'; + +/** Language toggle (AR <-> EN). Uses the backend set-language call first when signed in (see AuthProvider). */ +export function LanguageToggle() { + const { t, lang } = useUi(); + const { changeLanguage } = useAuth(); + return ( + + + + ); +} + +export function ThemeToggle() { + const { t } = useUi(); + const { mode, toggle } = useThemeMode(); + return ( + + + {mode === 'dark' ? : } + + + ); +} diff --git a/web/src/shell/TopBar.tsx b/web/src/shell/TopBar.tsx new file mode 100644 index 0000000..7300136 --- /dev/null +++ b/web/src/shell/TopBar.tsx @@ -0,0 +1,54 @@ +import { useState } from 'react'; +import { AppBar, Avatar, Box, Divider, IconButton, ListItemIcon, Menu, MenuItem, Toolbar, Tooltip, Typography } from '@mui/material'; +import LockResetIcon from '@mui/icons-material/LockReset'; +import LogoutIcon from '@mui/icons-material/Logout'; +import MenuIcon from '@mui/icons-material/Menu'; +import PersonOutlineIcon from '@mui/icons-material/PersonOutlineOutlined'; +import { Logo } from '@/components/Logo'; +import { useUi } from '@/i18n/useUi'; +import { useAuth } from '@/providers/AuthProvider'; +import { ChangePasswordDialog } from './ChangePasswordDialog'; +import { ThemeToggle } from './Toggles'; +import { Breadcrumbs } from './Breadcrumbs'; +import type { MenuItem as NavItem } from './types'; + +export function TopBar({ isDesktop, onMenu, onToggleCollapsed, menu }: { isDesktop: boolean; onMenu: () => void; onToggleCollapsed: () => void; menu: NavItem[] }) { + const { t } = useUi(); + const { user, logout } = useAuth(); + const [anchor, setAnchor] = useState(null); + const [pwd, setPwd] = useState(false); + + return ( + + + {/* mobile: opens the drawer; desktop: minimizes / expands the side menu */} + + {!isDesktop && } + + + + setAnchor(e.currentTarget)} aria-label={t('user.menu')} sx={{ marginInlineStart: 0.5 }}> + + + + + + setAnchor(null)}> + + {user?.name} + {user?.roleName} + {user?.locationName && {user.locationName}} + + + { setAnchor(null); setPwd(true); }}> + {t('user.changePassword')} + + { setAnchor(null); logout(); }}> + {t('user.logout')} + + + setPwd(false)} /> + + + ); +} diff --git a/web/src/shell/menuUtils.ts b/web/src/shell/menuUtils.ts new file mode 100644 index 0000000..b9bf1aa --- /dev/null +++ b/web/src/shell/menuUtils.ts @@ -0,0 +1,44 @@ +import type { MenuItem } from './types'; + +/** + * Is this entry visible? `roles` (static, optional) AND the backend permission `key` (GET /auth/permissions; + * SU = everything). Groups (children) are visible when the roles allow and at least one child is (see filterMenu). + */ +export function itemAllowed(hasRole: (roles?: string[]) => boolean, can: (key: string) => boolean) { + return (it: MenuItem): boolean => hasRole(it.roles) && (it.children ? true : can(it.key)); +} + +/** Recursively keep only items the role may see; drop groups left empty. */ +export function filterMenu(items: MenuItem[], allowed: (item: MenuItem) => boolean, can?: (key: string) => boolean): MenuItem[] { + const out: MenuItem[] = []; + for (const it of items) { + if (!allowed(it)) continue; + if (it.children) { + const kids = filterMenu(it.children, allowed, can); + if (kids.length === 0 && !it.path) continue; + out.push({ ...it, children: kids }); + } else if (it.createPath && it.createKey && can && !can(it.createKey)) out.push({ ...it, createPath: undefined }); + else out.push(it); + } + return out; +} + +export function flatten(items: MenuItem[], trail: MenuItem[] = []): { item: MenuItem; trail: MenuItem[] }[] { + return items.flatMap((it) => [{ item: it, trail }, ...(it.children ? flatten(it.children, [...trail, it]) : [])]); +} + +export function pathMatches(pathname: string, target?: string): boolean { + if (!target) return false; + return pathname === target || pathname.startsWith(target.endsWith('/') ? target : `${target}/`); +} + +/** Longest-prefix match: the menu entry (and its parent groups) that owns `pathname`. */ +export function findOwner(items: MenuItem[], pathname: string): { item: MenuItem; trail: MenuItem[] } | null { + let best: { item: MenuItem; trail: MenuItem[]; len: number } | null = null; + for (const e of flatten(items)) { + for (const p of [e.item.path, e.item.createPath]) { + if (p && pathMatches(pathname, p) && (!best || p.length > best.len)) best = { ...e, len: p.length }; + } + } + return best; +} diff --git a/web/src/shell/types.ts b/web/src/shell/types.ts new file mode 100644 index 0000000..2fae16a --- /dev/null +++ b/web/src/shell/types.ts @@ -0,0 +1,22 @@ +import type { ElementType } from 'react'; +import type { L10n } from '@/i18n/ui'; + +/** + * One navigation entry. A leaf has `path`; a group has `children`. + * `roles`: allowed role codes (e.g. ['SU','CO']); omitted = every signed-in user. Groups with no visible child are hidden. + * `createPath`: shows a "+" on the row that goes straight to the create page (the row itself opens the list). + */ +export interface MenuItem { + key: string; + title: L10n; + /** An MUI icon component, e.g. `icon: GrassIcon` (from '@mui/icons-material/Grass'). */ + icon: ElementType; + path?: string; + createPath?: string; + /** Permission key of the create action; without it the "+" shortcut is hidden (the list itself stays visible). */ + createKey?: string; + roles?: string[]; + /** Badge colour (any CSS colour). Default: picked from the palette by key. */ + color?: string; + children?: MenuItem[]; +} diff --git a/web/src/theme/theme.ts b/web/src/theme/theme.ts new file mode 100644 index 0000000..a481287 --- /dev/null +++ b/web/src/theme/theme.ts @@ -0,0 +1,93 @@ +import { createTheme, type Theme } from '@mui/material/styles'; +import { tokens, type ThemeMode } from './tokens'; + +// Cairo covers Arabic and Latin in one family (loaded in index.html), as in the mams project. +const fontFamily = ['"Cairo"', '"Segoe UI"', 'Tahoma', 'system-ui', 'sans-serif'].join(','); + +/** Field text, labels, menu items and grid cells share one size (mams: 13.5px). */ +const BASE = 13.5; + +export function buildTheme(mode: ThemeMode, direction: 'rtl' | 'ltr'): Theme { + const k = tokens[mode]; + return createTheme({ + direction, + palette: { + mode, + primary: { main: k.primary, contrastText: k.primaryText }, + secondary: { main: k.accent }, + background: { default: k.bg, paper: k.paper }, + text: { primary: k.text, secondary: k.sub }, + divider: k.border, + action: { hover: k.hover }, + }, + shape: { borderRadius: 12 }, + typography: { + fontFamily, + h4: { fontWeight: 700, letterSpacing: '-0.01em' }, + h5: { fontWeight: 700, letterSpacing: '-0.01em', fontSize: '1.3rem' }, + h6: { fontWeight: 700 }, + button: { textTransform: 'none', fontWeight: 600 }, + }, + components: { + MuiCssBaseline: { + styleOverrides: { + body: { backgroundColor: k.bg, color: k.text }, + }, + }, + MuiPaper: { + defaultProps: { elevation: 0 }, + styleOverrides: { root: { backgroundImage: 'none' }, outlined: { borderColor: k.border } }, + }, + MuiTextField: { defaultProps: { fullWidth: true, size: 'small' } }, + MuiFormControl: { defaultProps: { fullWidth: true } }, + MuiAutocomplete: { + defaultProps: { fullWidth: true }, + styleOverrides: { option: { fontSize: BASE }, noOptions: { fontSize: BASE } }, + }, + MuiButton: { + defaultProps: { disableElevation: true, size: 'small' }, + styleOverrides: { root: { borderRadius: 8, fontSize: 13 } }, + }, + // every popup shares one title size and text size + MuiDialog: { styleOverrides: { paper: { borderRadius: 12 } } }, + MuiDialogTitle: { styleOverrides: { root: { fontSize: '1.05rem', fontWeight: 700, lineHeight: 1.4 } } }, + MuiDialogContent: { + styleOverrides: { root: { fontSize: '0.9rem', '& .MuiTypography-root:not(.MuiTypography-caption)': { fontSize: '0.9rem' } } }, + }, + MuiDialogActions: { styleOverrides: { root: { padding: '8px 24px 16px', gap: 4 } } }, + MuiTable: { defaultProps: { size: 'small' } }, + MuiInputBase: { styleOverrides: { root: { fontSize: BASE } } }, + MuiMenuItem: { styleOverrides: { root: { fontSize: BASE } } }, + MuiInputLabel: { styleOverrides: { root: { fontSize: BASE } } }, + MuiFormHelperText: { styleOverrides: { root: { fontSize: 12 } } }, + MuiChip: { styleOverrides: { root: { fontWeight: 600 } } }, + MuiTableCell: { + styleOverrides: { + // dense rows; the header is a quiet tint of the surface, not a bright band + root: { borderColor: k.border, padding: '5px 12px', fontSize: BASE, lineHeight: 1.35 }, + head: { + backgroundColor: k.headBg, + color: k.headText, + fontWeight: 700, + fontSize: 13, + padding: '9px 12px', + lineHeight: 1.3, + borderBottomColor: k.headBorder, + }, + }, + }, + MuiListItemButton: { + styleOverrides: { + root: { + borderRadius: 8, + paddingTop: 5, + paddingBottom: 5, + '&.Mui-selected': { backgroundColor: k.selectedBg, color: k.primary }, + '&.Mui-selected:hover': { backgroundColor: k.selectedHoverBg }, + }, + }, + }, + MuiAppBar: { styleOverrides: { root: { backgroundImage: 'none' } } }, + }, + }); +} diff --git a/web/src/theme/tokens.ts b/web/src/theme/tokens.ts new file mode 100644 index 0000000..abe8f36 --- /dev/null +++ b/web/src/theme/tokens.ts @@ -0,0 +1,67 @@ +/** Design tokens, defined once (values ported from the `mams` project's theme). Components read the MUI theme; nothing hard-codes a hex. */ +export type ThemeMode = 'light' | 'dark'; + +export interface Tokens { + bg: string; + paper: string; + border: string; + primary: string; + primaryText: string; + text: string; // brand navy in light mode + sub: string; + accent: string; + hover: string; + /** page / record titles (gold-orange in mams) */ + title: string; + /** table header band */ + headBg: string; + headText: string; + headBorder: string; + /** selected list item */ + selectedBg: string; + selectedHoverBg: string; + /** section title bar on forms/records */ + sectionBar: string; +} + +export const tokens: Record = { + light: { + bg: '#f4f6fa', + paper: '#ffffff', + border: '#e2e8f0', + primary: '#0b6ea8', + primaryText: '#ffffff', + text: '#0b3a5c', + sub: '#5b6b7d', + accent: '#d6336c', + hover: 'rgba(11, 110, 168, 0.06)', + title: '#d1a233', + headBg: '#eaf2fc', + headText: '#1f3a5f', + headBorder: '#cfe0f5', + selectedBg: '#e6f2fa', + selectedHoverBg: '#dbeaf6', + sectionBar: '#eceff3', + }, + dark: { + bg: '#0d1520', + paper: '#141f2d', + border: '#243245', + primary: '#5fb4ea', + primaryText: '#06243b', + text: '#e6edf5', + sub: '#9aabbd', + accent: '#f06595', + hover: 'rgba(95, 180, 234, 0.10)', + title: '#d1a233', + headBg: '#13263b', + headText: '#bcd4ea', + headBorder: '#24405e', + selectedBg: '#17324a', + selectedHoverBg: '#1b3a56', + sectionBar: 'rgba(255, 255, 255, 0.08)', + }, +}; + +/** Section icon hues: used as tinted badge (alpha background + solid icon), readable in both modes. */ +export const badgeColors = ['#1e88e5', '#8e24aa', '#00897b', '#f4511e', '#3949ab', '#c0a000', '#d81b60', '#43a047'] as const; diff --git a/web/src/vite-env.d.ts b/web/src/vite-env.d.ts new file mode 100644 index 0000000..cf2959f --- /dev/null +++ b/web/src/vite-env.d.ts @@ -0,0 +1,4 @@ +/// +interface ImportMetaEnv { + readonly VITE_MOCK?: string; +} diff --git a/web/tsconfig.json b/web/tsconfig.json new file mode 100644 index 0000000..9ff92e2 --- /dev/null +++ b/web/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedIndexedAccess": false, + "skipLibCheck": true, + "isolatedModules": true, + "resolveJsonModule": true, + "allowImportingTsExtensions": false, + "noEmit": true, + "types": ["vite/client", "node"], + "paths": { "@/*": ["./src/*"] } + }, + "include": ["src", "vite.config.ts"] +} diff --git a/web/vite.config.ts b/web/vite.config.ts new file mode 100644 index 0000000..5b3c509 --- /dev/null +++ b/web/vite.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; +import { fileURLToPath, URL } from 'node:url'; + +export default defineConfig({ + plugins: [react()], + resolve: { + alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) }, + }, + server: { + port: 5173, + proxy: { + '/api': { target: 'https://localhost:7180', changeOrigin: true, secure: false }, + }, + }, +});