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 <noreply@anthropic.com>
This commit is contained in:
commit
0c0b64239c
|
|
@ -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
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
<Project>
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<NoWarn>$(NoWarn);CS1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
<Project>
|
||||
<PropertyGroup>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!--
|
||||
IMPORTANT: stay on the 3.21.x line of Oracle.ManagedDataAccess.Core.
|
||||
ODP.NET Core 21.x is the last line that supports Oracle Database 11.2.0.4.
|
||||
The 23.x line requires Oracle Database 19c or later - do NOT upgrade to it
|
||||
until the database itself is upgraded. Bump only within 3.21.x.
|
||||
-->
|
||||
<PackageVersion Include="Oracle.ManagedDataAccess.Core" Version="3.21.130" />
|
||||
<PackageVersion Include="Dapper" Version="2.1.66" />
|
||||
<!-- Excel export/import for the Grains reports slice -->
|
||||
<PackageVersion Include="ClosedXML" Version="0.104.2" />
|
||||
|
||||
<PackageVersion Include="FluentValidation" Version="12.0.0" />
|
||||
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.0.0" />
|
||||
|
||||
<PackageVersion Include="Asp.Versioning.Mvc" Version="8.1.0" />
|
||||
<PackageVersion Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" />
|
||||
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" />
|
||||
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="9.0.4" />
|
||||
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
|
||||
|
||||
<!-- tests -->
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageVersion Include="xunit" Version="2.9.3" />
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/NTP.Api/NTP.Api.csproj" />
|
||||
<Project Path="src/NTP.Application/NTP.Application.csproj" />
|
||||
<Project Path="src/NTP.Domain/NTP.Domain.csproj" />
|
||||
<Project Path="src/NTP.Infrastructure/NTP.Infrastructure.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/NTP.Tests/NTP.Tests.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Solution Items/">
|
||||
<File Path="Directory.Build.props" />
|
||||
<File Path="Directory.Packages.props" />
|
||||
<File Path="README.md" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
|
|
@ -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=<password>;Data Source=<host>:1521/<service>"`, `"NtpSchema": "User Id=NTP;Password=<password>;Data Source=<host>:1521/<service>"`.
|
||||
|
||||
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=<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/<Name>.cs`, one property per column (`ORDER_DATE` → `OrderDate`).
|
||||
2. **Repository interface** — `Application/Abstractions/I<Name>Repository.cs`.
|
||||
3. **Repository** — copy `ShipmentRepository.cs`; explicit column lists, `:Param` binds, `OracleSql.Paginate` for lists, `<SEQ>.NEXTVAL ... RETURNING ... INTO` for inserts.
|
||||
4. **Service** — port the old business logic into `Application/<Module>/<Name>Service.cs`; wrap multi-statement writes in `unitOfWork.ExecuteInTransactionAsync`.
|
||||
5. **Validators + DTOs** — keep max lengths in sync with `VARCHAR2` sizes.
|
||||
6. **Controller** — `Controllers/V1/<Name>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).
|
||||
|
|
@ -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
|
||||
|
|
@ -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;
|
||||
|
|
@ -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.
|
||||
|
|
@ -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://<web-host>`. Replaces the placeholder in the settings file; until it is set no browser origin is allowed |
|
||||
| `Auth__SuperUsers__0`, `__1` ... | Logins that may hold role `SU`. Empty in production by default; QA lists its own in `appsettings.QA.json` |
|
||||
|
||||
Connection string shape (values are examples only):
|
||||
`User Id=<schema>;Password=<secret>;Data Source=<host>:1521/<service>;Min Pool Size=1;Max Pool Size=50;Connection Timeout=15;Statement Cache Size=50`
|
||||
|
||||
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-host>/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='<at least 32 random characters>'
|
||||
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
|
||||
|
|
@ -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/<Slice>/`
|
||||
- `NTP.Application/Grains/<Slice>/` (interfaces `I<X>Repository`, `I<X>Service`, DTOs, validators)
|
||||
- `NTP.Infrastructure/Persistence/Repositories/Grains/<Slice>/`
|
||||
- `NTP.Api/Controllers/V1/Grains/<Slice>Controller.cs`, route `api/v{version}/grains/<slice>`
|
||||
- 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<T>` 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/<feature>/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/<entity>.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/<Slice>/`: `I<X>Repository`, `I<X>Service` + `<X>Service` (class name MUST end in `Service`, interface MUST be `I<ClassName>`), DTOs, `AbstractValidator<T>` classes. Namespace `NTP.Application.Grains.<Slice>`.
|
||||
2. `NTP.Infrastructure/Persistence/Repositories/Grains/<Slice>/<X>Repository.cs`: `internal sealed class <X>Repository(IDbSession session, ILogger<<X>Repository> logger) : OracleRepositoryBase(session, logger), I<X>Repository`. Base helpers: `QueryAsync`, `QueryFirstAsync` (new), `QuerySingleOrDefaultAsync`, `ExecuteScalarAsync`, `ExecuteAsync`.
|
||||
3. `NTP.Api/Controllers/V1/Grains/<Slice>Controller.cs`: `[ApiController] [ApiVersion(1.0)] [Route("api/v{version:apiVersion}/grains/<slice>")]`, 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<ClassName>` 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 <token>`. 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/<f>/` (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/<entity>.ts(x)` (or `meta.tsx`) - declarative tables, types in `@/components/meta/types`:
|
||||
- `GridMeta<T>`: `{ key, endpoint | fetcher, rowKey, columns: ColumnMeta<T>[], filters?: FilterMeta[], status?: {param, options: StatusMeta[]}, defaultFilters?, requireFilter?, pageSize?, rowActions?: RowAction<T>[], 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<T>` = `{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<OptionItem[]>, 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` + `<DataGrid meta={...}/>` for lists; `<MetaForm meta mode initialValues onSubmit onCancel serverErrors/>` 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/<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 (<your sql>) 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).
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
internal sealed class ActiveUserValidator(
|
||||
IAuthService authService, IMemoryCache cache, IOptions<JwtOptions> jwt, IOptions<AuthOptions> auth)
|
||||
{
|
||||
public async Task<bool> 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
{
|
||||
/// <summary>JWT bearer + ICurrentUser + fallback "authenticated user required" policy (use [AllowAnonymous] explicitly).</summary>
|
||||
public static IServiceCollection AddNtpAuthentication(this IServiceCollection services, IConfiguration configuration, IHostEnvironment env)
|
||||
{
|
||||
var jwt = configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>() ?? 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<JwtOptions>(o =>
|
||||
{
|
||||
o.Key = jwt.Key; o.Issuer = jwt.Issuer; o.Audience = jwt.Audience;
|
||||
o.ExpiryMinutes = jwt.ExpiryMinutes; o.ActiveCheckCacheSeconds = jwt.ActiveCheckCacheSeconds;
|
||||
});
|
||||
services.Configure<AuthOptions>(configuration.GetSection(AuthOptions.SectionName));
|
||||
|
||||
services.AddMemoryCache();
|
||||
services.AddHttpContextAccessor();
|
||||
services.AddScoped<ICurrentUser, CurrentUser>();
|
||||
services.AddSingleton<ITokenIssuer, JwtTokenIssuer>();
|
||||
services.AddScoped<ActiveUserValidator>();
|
||||
|
||||
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<ActiveUserValidator>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace NTP.Api.Auth;
|
||||
|
||||
/// <summary>Adds the "Bearer" JWT scheme to the OpenAPI document so Swagger UI shows the Authorize button.</summary>
|
||||
internal sealed class BearerSecurityTransformer : IOpenApiDocumentTransformer
|
||||
{
|
||||
public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
document.Components ??= new OpenApiComponents();
|
||||
document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
using System.Security.Claims;
|
||||
using NTP.Application.Abstractions;
|
||||
|
||||
namespace NTP.Api.Auth;
|
||||
|
||||
/// <summary>ICurrentUser over the request's JWT claims (IHttpContextAccessor).</summary>
|
||||
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);
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
namespace NTP.Api.Auth;
|
||||
|
||||
/// <summary>Config section "Jwt". Key comes from user-secrets / env (Jwt__Key) / appsettings.Local.json - never appsettings.json.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Seconds to cache the per-request "user still active with same role" check (0 = query every request, like legacy).</summary>
|
||||
public int ActiveCheckCacheSeconds { get; set; } = 10;
|
||||
|
||||
public const int MinKeyLength = 32;
|
||||
}
|
||||
|
||||
/// <summary>Config section "Auth".</summary>
|
||||
public sealed class AuthOptions
|
||||
{
|
||||
public const string SectionName = "Auth";
|
||||
|
||||
/// <summary>Application.cfc: users with role SU not in this list are rejected on every request.</summary>
|
||||
public string[] SuperUsers { get; set; } = [];
|
||||
}
|
||||
|
|
@ -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<JwtOptions> 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);
|
||||
}
|
||||
|
||||
/// <summary>Claim set for a user (null/empty values are omitted). Exposed for tests.</summary>
|
||||
public static IEnumerable<Claim> 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!);
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Gate an endpoint (or a whole controller) on a permission resource key from the database permission table
|
||||
/// (see <see cref="PermissionKeys"/>). SU always passes; unauthenticated callers are rejected by the app-wide
|
||||
/// fallback policy before this runs. A failure answers 403 with code <c>FORBIDDEN_RESOURCE</c>.
|
||||
/// Several keys mean "any of them" (a shared endpoint serving more than one screen).
|
||||
/// </summary>
|
||||
[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", "ليس لديك صلاحية للوصول إلى هذه الشاشة");
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
{
|
||||
/// <summary>Legacy signon.checkLogin. UserName is "DOMAIN.login" (e.g. ASEZA.50034).</summary>
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType<LoginResponse>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||
public Task<LoginResponse> Login(LoginRequest request, CancellationToken ct) =>
|
||||
service.LoginAsync(request, Client(), ct);
|
||||
|
||||
/// <summary>The caller's claims (legacy session snapshot).</summary>
|
||||
[HttpGet("me")]
|
||||
[ProducesResponseType<CurrentUserDto>(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);
|
||||
|
||||
/// <summary>Legacy signon.changePass.</summary>
|
||||
[HttpPost("change-password")]
|
||||
[ProducesResponseType<MessageResponse>(StatusCodes.Status200OK)]
|
||||
public Task<MessageResponse> ChangePassword(ChangePasswordRequest request, CancellationToken ct) =>
|
||||
service.ChangePasswordAsync(request, ct);
|
||||
|
||||
/// <summary>Switches AR/EN; returns a fresh token carrying the new language claim.</summary>
|
||||
[HttpPost("language")]
|
||||
[ProducesResponseType<TokenResponse>(StatusCodes.Status200OK)]
|
||||
public Task<TokenResponse> Language(SetLanguageRequest request, CancellationToken ct) =>
|
||||
service.SetLanguageAsync(request, ct);
|
||||
|
||||
/// <summary>Legacy signon.signOut: writes the sign-out audit row (the token itself is stateless; the client drops it).</summary>
|
||||
[HttpPost("logout")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> 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());
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
/// <summary>Tender orders (legacy tenderOrderGrid.cfm / createNewTenderOrder.cfm / tenderOrder.cfc) and mobile publish.</summary>
|
||||
[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<PagedResult<TenderOrderDto>> 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<OrdersResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.OrdersCreate)]
|
||||
public Task<OrdersResult> Create(CreateTenderOrderRequest request, CancellationToken ct) => orders.CreateAsync(request, ct);
|
||||
|
||||
[HttpDelete("{id:long}")]
|
||||
[ProducesResponseType<OrdersResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.OrdersList)]
|
||||
public Task<OrdersResult> Delete(long id, CancellationToken ct) => orders.DeleteAsync(id, ct);
|
||||
|
||||
/// <summary>Show / hide the order on the mobile app (legacy publishMobile).</summary>
|
||||
[HttpPut("{id:long}/mobile")]
|
||||
[RequirePermission(PermissionKeys.OrdersList)]
|
||||
public Task<OrdersResult> 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<IReadOnlyList<LookupOptionDto>> CargoTypes(CancellationToken ct) => lookups.CargoTypesAsync(ct);
|
||||
|
||||
[HttpGet("lookups/loading-locations")]
|
||||
[RequirePermission(PermissionKeys.OrdersList)]
|
||||
public Task<IReadOnlyList<LookupOptionDto>> LoadingLocations(CancellationToken ct) => lookups.LoadingLocationsAsync(ct);
|
||||
|
||||
[HttpGet("lookups/destinations")]
|
||||
[RequirePermission(PermissionKeys.OrdersList)]
|
||||
public Task<IReadOnlyList<LookupOptionDto>> Destinations(CancellationToken ct) => lookups.DestinationsAsync(ct);
|
||||
|
||||
[HttpGet("lookups/billing-destinations")]
|
||||
[RequirePermission(PermissionKeys.OrdersBilling)]
|
||||
public Task<IReadOnlyList<LookupOptionDto>> BillingDestinations(CancellationToken ct) => lookups.BillingDestinationsAsync(ct);
|
||||
|
||||
[HttpGet("lookups/packed-destinations")]
|
||||
[RequirePermission(PermissionKeys.OrdersCompanyDest)]
|
||||
public Task<IReadOnlyList<LookupOptionDto>> PackedDestinations(CancellationToken ct) => lookups.PackedDestinationsAsync(ct);
|
||||
|
||||
[HttpGet("lookups/companies")]
|
||||
[RequirePermission(PermissionKeys.OrdersBilling, PermissionKeys.OrdersCompanyDest, PermissionKeys.OrdersReportFinance)]
|
||||
public Task<IReadOnlyList<CompanyOptionDto>> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>Daily quota per destination (legacy quotaGrid.cfm, grains.cfc getQuotaList / editQuota).</summary>
|
||||
[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<PagedResult<QuotaDto>> 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<OrdersResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.OrdersQuotas)]
|
||||
public Task<OrdersResult> Set(SetQuotaRequest request, CancellationToken ct) => quotas.SetQuotaAsync(request, ct);
|
||||
}
|
||||
|
||||
/// <summary>Financial billing entry and list (legacy BillingScreen.cfm / BillingGrid.cfm, Invoice.cfc).</summary>
|
||||
[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<PagedResult<BillingDto>> 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);
|
||||
|
||||
/// <summary>Prefill of the billing form from a CLOSEd permit (legacy getBillingInfo).</summary>
|
||||
[HttpGet("permit/{pn:long}")]
|
||||
[ProducesResponseType<BillingPermitDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.OrdersBilling)]
|
||||
public Task<BillingPermitDto> Permit(long pn, [FromQuery] long? scac, CancellationToken ct) => billing.GetPermitAsync(pn, scac, ct);
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType<OrdersResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.OrdersBilling)]
|
||||
public Task<OrdersResult> Add(AddBillingRequest request, CancellationToken ct) => billing.AddAsync(request, ct);
|
||||
}
|
||||
|
||||
/// <summary>Invoices list (legacy InvoiceGrid.cfm, Invoice.cfc getInvoiceGrid).</summary>
|
||||
[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<PagedResult<InvoiceDto>> Search(
|
||||
[FromQuery] long? invoiceNumber, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) =>
|
||||
invoices.SearchAsync(invoiceNumber, new PageRequest(page, pageSize), ct);
|
||||
}
|
||||
|
||||
/// <summary>Loading weights entry (legacy addGrainsWeights.cfm).</summary>
|
||||
[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<PermitWeightsDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.OrdersWeights)]
|
||||
public Task<PermitWeightsDto> Get(long pn, CancellationToken ct) => weights.GetAsync(pn, ct);
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType<OrdersResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.OrdersWeights)]
|
||||
public Task<OrdersResult> Save(SaveWeightsRequest request, CancellationToken ct) => weights.SaveAsync(request, ct);
|
||||
}
|
||||
|
||||
/// <summary>Which packed destinations a company may receive (legacy compdest.cfm over GRAINS_COMPANIES_LOCATION).</summary>
|
||||
[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<CompanyDestinationsDto> Get(long scac, CancellationToken ct) => service.GetAsync(scac, ct);
|
||||
|
||||
[HttpPut("{scac:long}")]
|
||||
[ProducesResponseType<OrdersResult>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status422UnprocessableEntity)]
|
||||
[RequirePermission(PermissionKeys.OrdersCompanyDest)]
|
||||
public Task<OrdersResult> Save(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct) =>
|
||||
service.SaveAsync(scac, request, ct);
|
||||
}
|
||||
|
||||
/// <summary>Reports (legacy tenderOrderReport_xls.cfm, FinancialBilling.cfm, FinancialRpts.cfm): JSON grids + CSV/XLSX export.</summary>
|
||||
[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<TenderOrderReportDto> 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<IActionResult> 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<FinancialBillingPage> 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<IActionResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Invoice numbers of a company for the report picker (legacy getInvoiceNo, which does not exist in the CFC).</summary>
|
||||
[HttpGet("invoice-numbers")]
|
||||
[Produces("application/json")]
|
||||
[RequirePermission(PermissionKeys.OrdersReportFinance)]
|
||||
public Task<IReadOnlyList<long>> InvoiceNumbers([FromQuery] long scac, CancellationToken ct) => reports.GetInvoiceNumbersAsync(scac, ct);
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/grains/permits")]
|
||||
[Produces("application/json")]
|
||||
public sealed class PermitsController(IPermitService permits) : ControllerBase
|
||||
{
|
||||
// ---- lists
|
||||
/// <summary>getGNPermits: empty until at least one filter is given (legacy behaviour).</summary>
|
||||
[HttpGet]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PagedResult<PermitListItem>> 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);
|
||||
|
||||
/// <summary>getGNList (permitsGrid.cfm): gate / clearance list.</summary>
|
||||
[HttpGet("gate")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<PagedResult<GatePermitItem>> 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<PermitDetailDto> Get(long id, CancellationToken ct) => permits.GetAsync(id, ct);
|
||||
|
||||
[HttpGet("{id:long}/events")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<IReadOnlyList<PermitEventDto>> Events(long id, CancellationToken ct) => permits.GetEventsAsync(id, ct);
|
||||
|
||||
// ---- lookups used by the order form
|
||||
[HttpGet("lookups/truck/{tn}")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<TruckInfoDto?> Truck(string tn, [FromQuery] bool validate = false, CancellationToken ct = default) =>
|
||||
permits.GetTruckInfoAsync(tn, validate, ct);
|
||||
|
||||
[HttpGet("lookups/trailer/{trn}")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<TrailerInfoDto?> Trailer(string trn, CancellationToken ct) => permits.GetTrailerInfoAsync(trn, ct);
|
||||
|
||||
[HttpGet("lookups/driver/{nnpn}")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<DriverInfoDto?> Driver(string nnpn, CancellationToken ct) => permits.GetDriverInfoAsync(nnpn, ct);
|
||||
|
||||
// ---- order lifecycle (companies and staff)
|
||||
[HttpPost("{id:long}/submit")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> Submit(long id, SubmitOrderRequest request, CancellationToken ct) => permits.SubmitAsync(id, request, ct);
|
||||
|
||||
[HttpPut("{id:long}")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> Update(long id, UpdateOrderRequest request, CancellationToken ct) => permits.UpdateAsync(id, request, ct);
|
||||
|
||||
[HttpPost("{id:long}/accept")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> Accept(long id, CancellationToken ct) => permits.AcceptAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/revoke")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> Revoke(long id, CancellationToken ct) => permits.RevokeAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/revoke-accepted")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> RevokeAccepted(long id, CancellationToken ct) => permits.RevokeAcceptedAsync(id, ct);
|
||||
|
||||
// ---- staff operations
|
||||
[HttpPost("{id:long}/convert-to-resd")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> ConvertToResd(long id, CancellationToken ct) => permits.ConvertToResdAsync(id, ct);
|
||||
|
||||
[HttpPost("{id:long}/cancel-order")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> CancelOrder(long id, ReasonRequest request, CancellationToken ct) => permits.CancelOrderAsync(id, request, ct);
|
||||
|
||||
[HttpPost("{id:long}/revoke-permit")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> RevokePermit(long id, ReasonRequest request, CancellationToken ct) => permits.RevokePermitAsync(id, request, ct);
|
||||
|
||||
[HttpPost("{id:long}/reactivate")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> Reactivate(long id, CancellationToken ct) => permits.ReactivateAsync(id, ct);
|
||||
|
||||
/// <summary>GrainsFactory(Web).cancelGrainsPermit: RESD back to ACCPT.</summary>
|
||||
[HttpPost("{id:long}/cancel-grains-permit")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> CancelGrainsPermit(long id, CancellationToken ct) => permits.CancelGrainsPermitAsync(id, ct);
|
||||
|
||||
/// <summary>closePermit / arrivalTruck.cfm.</summary>
|
||||
[HttpPost("close")]
|
||||
[RequirePermission(PermissionKeys.PermitsClose)]
|
||||
public Task<PermitOperationResult> Close(ClosePermitRequest request, CancellationToken ct) => permits.CloseManualAsync(request, ct);
|
||||
|
||||
[HttpPost("{id:long}/phone-accept")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> PhoneAccept(long id, PhoneAcceptRequest request, CancellationToken ct) => permits.PhoneAcceptAsync(id, request, ct);
|
||||
|
||||
[HttpPost("{id:long}/phone-reject")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<PermitOperationResult> 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<StoredWeightsDto> Weights(string pn, CancellationToken ct) => permits.LookupWeightsAsync(pn, ct);
|
||||
|
||||
[HttpPut("weights")]
|
||||
[RequirePermission(PermissionKeys.OrdersWeights)]
|
||||
public Task<PermitOperationResult> 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<PermitOperationResult> ToggleAbsenceFeature(CancellationToken ct) => permits.ToggleAbsenceFeatureAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>Turns (legacy CreateQueue.cfm / queueGrid.cfm / createPermit.cfm / dblMovePN.cfm): OPEN permit records and the TCS permit.</summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/grains/permit-queue")]
|
||||
[Produces("application/json")]
|
||||
public sealed class PermitQueueController(IQueueService queue) : ControllerBase
|
||||
{
|
||||
/// <summary>getGNQueueList (queueGrid.cfm).</summary>
|
||||
[HttpGet]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public Task<PagedResult<QueueItem>> 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);
|
||||
|
||||
/// <summary>AddToQueue (CreateQueue.cfm).</summary>
|
||||
[HttpPost]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public Task<PermitOperationResult> Add(AddToQueueRequest request, CancellationToken ct) => queue.AddToQueueAsync(request, ct);
|
||||
|
||||
[HttpGet("trailer-of/{tn}")]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public async Task<ActionResult<object>> TrailerOf(string tn, CancellationToken ct) => new { trailer = await queue.GetTrailerNumberAsync(tn, ct) };
|
||||
|
||||
/// <summary>checkTrucks.</summary>
|
||||
[HttpPost("check-trucks")]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public Task<PermitOperationResult> CheckTrucks([FromQuery] long tn, [FromQuery] long scac, CancellationToken ct) => queue.CheckTrucksAsync(tn, scac, ct);
|
||||
|
||||
/// <summary>parseGrainsPermits job, on demand: create OPEN permits for the given companies.</summary>
|
||||
[HttpPost("seed")]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public Task<PermitOperationResult> Seed(SeedPermitsRequest request, CancellationToken ct) => queue.SeedPermitsAsync(request, ct);
|
||||
|
||||
// ---- TCS permit form (createPermit.cfm)
|
||||
[HttpGet("{id:long}/tcs-form")]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public Task<TcsFormDataDto?> TcsForm(long id, CancellationToken ct) => queue.GetTcsFormDataAsync(id, ct);
|
||||
|
||||
[HttpGet("tcs/routing-templates")]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public Task<IReadOnlyList<RoutingTemplateDto>> 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<IReadOnlyList<LookupItem>> Origins([FromQuery] long routing, CancellationToken ct) => queue.GetOriginAddressesAsync(routing, ct);
|
||||
|
||||
[HttpGet("tcs/ph-routes")]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public Task<IReadOnlyList<RoutingTemplateDto>> PhRoutes(CancellationToken ct) => queue.GetPhRoutesAsync(ct);
|
||||
|
||||
[HttpGet("tcs/clearing-agent/{can:long}")]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public async Task<ActionResult<object>> ClearingAgent(long can, CancellationToken ct) => new { name = await queue.GetClearingAgentNameAsync(can, ct) };
|
||||
|
||||
[HttpGet("tcs/fop/{fop}")]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public Task<TcsFopDetail> Fop(string fop, CancellationToken ct) => queue.GetFopDetailAsync(fop, ct);
|
||||
|
||||
[HttpPost("{id:long}/tcs-permit")]
|
||||
[RequirePermission(PermissionKeys.PermitsQueue)]
|
||||
public Task<PermitOperationResult> CreateTcsPermit(long id, CreateTcsPermitRequest request, CancellationToken ct) =>
|
||||
queue.CreateTcsPermitAsync(id, request, ct);
|
||||
}
|
||||
|
||||
/// <summary>Destinations of permits and companies (legacy assginggdest.cfm / compdest.cfm / ManualInput.cfm / activateOrders.cfm).</summary>
|
||||
[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<IReadOnlyList<LookupItem>> Locations(CancellationToken ct) => destinations.GetGrainsLocationsAsync(ct);
|
||||
|
||||
/// <summary>Destination filter of the permit list (GNPermits.cfm): every GN exit location by name, active or not.</summary>
|
||||
[HttpGet("lookups/filter-destinations")]
|
||||
[RequirePermission(PermissionKeys.PermitsList)]
|
||||
public Task<IReadOnlyList<LookupItem>> FilterDestinations(CancellationToken ct) => destinations.GetPermitFilterDestinationsAsync(ct);
|
||||
|
||||
[HttpGet("lookups/exit-locations")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)]
|
||||
public Task<IReadOnlyList<LookupItem>> ExitLocations(CancellationToken ct) => destinations.GetExitLocationsAsync(ct);
|
||||
|
||||
[HttpGet("lookups/cargo-types")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)]
|
||||
public Task<IReadOnlyList<LookupItem>> CargoTypes(CancellationToken ct) => destinations.GetCargoTypesAsync(ct);
|
||||
|
||||
[HttpGet("lookups/location-groups")]
|
||||
[RequirePermission(PermissionKeys.PermitsDestinations)]
|
||||
public Task<LocationGroupsDto> LocationGroups(CancellationToken ct) => destinations.GetLocationGroupsAsync(ct);
|
||||
|
||||
[HttpGet("lookups/companies")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsDestinations, PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsActivation, PermissionKeys.PermitsQueue)]
|
||||
public Task<IReadOnlyList<CompanyOption>> Companies(CancellationToken ct) => destinations.GetCompaniesAsync(ct);
|
||||
|
||||
[HttpGet("companies/{scac:long}")]
|
||||
[RequirePermission(PermissionKeys.PermitsDestinations)]
|
||||
public Task<IReadOnlyList<long>> CompanyDestinations(long scac, CancellationToken ct) => destinations.GetCompanyDestinationsAsync(scac, ct);
|
||||
|
||||
[HttpPut("companies/{scac:long}")]
|
||||
[RequirePermission(PermissionKeys.PermitsDestinations)]
|
||||
public Task<PermitOperationResult> SaveCompanyDestinations(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct) =>
|
||||
destinations.SaveCompanyDestinationsAsync(scac, request, ct);
|
||||
|
||||
/// <summary>savegrainsdest (assginggdest.cfm).</summary>
|
||||
[HttpPost("assign-by-pn")]
|
||||
[RequirePermission(PermissionKeys.PermitsDestinations)]
|
||||
public Task<PermitOperationResult> AssignByPn(AssignByPnRequest request, CancellationToken ct) => destinations.AssignByPnAsync(request, ct);
|
||||
|
||||
// ---- manual input (ManualInput.cfm)
|
||||
[HttpGet("order-dates")]
|
||||
[RequirePermission(PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsDestinations)]
|
||||
public Task<IReadOnlyList<string>> OrderDates(CancellationToken ct) => destinations.GetOrderDatesAsync(ct);
|
||||
|
||||
[HttpGet("allowed-destinations")]
|
||||
[RequirePermission(PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsDestinations)]
|
||||
public Task<IReadOnlyList<AllowedDestinationDto>> 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<IReadOnlyList<AllowedCargoDto>> AllowedCargo(long permitId, CancellationToken ct) => destinations.GetAllowedCargoAsync(permitId, ct);
|
||||
|
||||
[HttpGet("orders-for-permit")]
|
||||
[RequirePermission(PermissionKeys.PermitsManualEntry, PermissionKeys.PermitsDestinations)]
|
||||
public Task<IReadOnlyList<OrderChoiceDto>> OrdersForPermit([FromQuery] string pn, [FromQuery] string orderDate, CancellationToken ct) =>
|
||||
destinations.GetOrdersForPermitAsync(pn, orderDate, ct);
|
||||
|
||||
[HttpPost("manual-input")]
|
||||
[RequirePermission(PermissionKeys.PermitsManualEntry)]
|
||||
public Task<PermitOperationResult> ManualInput(ManualInputRequest request, CancellationToken ct) => destinations.ManualInputAsync(request, ct);
|
||||
|
||||
/// <summary>searchDestination (WeightBridge.cfm): the truck's destination, assigning one when needed.</summary>
|
||||
[HttpGet("search/{tn}")]
|
||||
[RequirePermission(PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<DestinationSearchResult> Search(string tn, CancellationToken ct) => destinations.SearchDestinationAsync(tn, ct);
|
||||
|
||||
// ---- activation of today's orders (activateOrders.cfm)
|
||||
[HttpGet("activation")]
|
||||
[RequirePermission(PermissionKeys.PermitsActivation)]
|
||||
public Task<IReadOnlyList<OrderActivationRow>> Activation(CancellationToken ct) => destinations.GetActivationAsync(ct);
|
||||
|
||||
[HttpPost("activation")]
|
||||
[RequirePermission(PermissionKeys.PermitsActivation)]
|
||||
public Task<PermitOperationResult> Activate(ActivateOrdersRequest request, CancellationToken ct) => destinations.ActivateOrdersAsync(request, ct);
|
||||
|
||||
/// <summary>activateGrainsDestination job, on demand.</summary>
|
||||
[HttpPost("jobs/activate-company-destinations")]
|
||||
[Authorize(Roles = "SU")]
|
||||
public async Task<ActionResult<object>> ActivatePending(CancellationToken ct) => new { activated = await destinations.ActivatePendingCompanyDestinationsAsync(ct) };
|
||||
}
|
||||
|
||||
/// <summary>Distribution of OPEN permits (legacy distributedOrder.cfm / distributionDetails.cfm / distributeSingelTruck.cfm / processOpenPermit.cfm ...).</summary>
|
||||
[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<PermitOperationResult> Distribute(DistributeRequest request, CancellationToken ct) => distribution.DistributeAsync(request, ct);
|
||||
|
||||
[HttpPost("release")]
|
||||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<PermitOperationResult> Release(ReleasePermitRequest request, CancellationToken ct) => distribution.ReleaseAsync(request, ct);
|
||||
|
||||
[HttpPost("process-open")]
|
||||
[RequirePermission(PermissionKeys.PermitsTruckOrder)]
|
||||
public Task<PermitOperationResult> ProcessOpen(OpenPermitRequest request, CancellationToken ct) => distribution.ProcessOpenPermitAsync(request, ct);
|
||||
|
||||
[HttpPost("process-open-with-destination")]
|
||||
[RequirePermission(PermissionKeys.PermitsTruckOrder)]
|
||||
public Task<PermitOperationResult> ProcessOpenWithDestination(OpenPermitWithDestinationRequest request, CancellationToken ct) =>
|
||||
distribution.ProcessOpenPermitWithDestinationAsync(request, ct);
|
||||
|
||||
[HttpPost("process-company-open")]
|
||||
[RequirePermission(PermissionKeys.PermitsTruckOrder)]
|
||||
public Task<PermitOperationResult> ProcessCompanyOpen(CompanyOpenPermitsRequest request, CancellationToken ct) =>
|
||||
distribution.ProcessCompanyOpenPermitsAsync(request, ct);
|
||||
|
||||
[HttpPost("single-truck")]
|
||||
[RequirePermission(PermissionKeys.PermitsTruckOrder)]
|
||||
public Task<PermitOperationResult> SingleTruck([FromQuery] string tn, CancellationToken ct) => distribution.DistributeSingleTruckAsync(tn, ct);
|
||||
|
||||
[HttpGet("summary")]
|
||||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<IReadOnlyList<DistributionSummaryRow>> Summary(CancellationToken ct) => distribution.GetSummaryAsync(ct);
|
||||
|
||||
[HttpGet("pivot")]
|
||||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<IReadOnlyList<DistributionPivotRow>> Pivot(CancellationToken ct) => distribution.GetPivotAsync(ct);
|
||||
|
||||
[HttpGet("search-truck")]
|
||||
[RequirePermission(PermissionKeys.PermitsTruckStatus)]
|
||||
public Task<TruckDistributionDto> SearchTruck([FromQuery] string tn, CancellationToken ct) => distribution.SearchTruckAsync(tn, ct);
|
||||
|
||||
[HttpGet("blacklisted")]
|
||||
[RequirePermission(PermissionKeys.PermitsTruckStatus, PermissionKeys.PermitsDistribution)]
|
||||
public Task<IReadOnlyList<BlacklistedDistributionDto>> Blacklisted([FromQuery] string tn, CancellationToken ct) => distribution.GetBlacklistedAsync(tn, ct);
|
||||
|
||||
[HttpPost("check-trips")]
|
||||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<PermitOperationResult> CheckTrips(CheckTripsRequest request, CancellationToken ct) => distribution.CheckTripsAsync(request, ct);
|
||||
|
||||
/// <summary>RevokeAllREQST.cfm: send every REQST / PLND permit of an order id below the given limit back to OPEN.</summary>
|
||||
[HttpPost("revoke-all-requested")]
|
||||
[Authorize(Roles = "SU")]
|
||||
public Task<PermitOperationResult> RevokeAllRequested([FromQuery] long scrnBelow, CancellationToken ct) => distribution.RevokeAllRequestedAsync(scrnBelow, ct);
|
||||
|
||||
/// <summary>checkForGabanEvents job, on demand.</summary>
|
||||
[HttpPost("jobs/revert-unloaded")]
|
||||
[Authorize(Roles = "SU")]
|
||||
public async Task<ActionResult<object>> RevertUnloaded(CancellationToken ct) => new { reverted = await distribution.RevertUnloadedPermitsAsync("SYSTEM", ct) };
|
||||
|
||||
// ---- auto call (GrainsFactoryWeb.autoCallService2 / callAPI)
|
||||
[HttpPost("auto-call/send")]
|
||||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<PermitOperationResult> SendAutoCall(AutoCallRequest request, CancellationToken ct) => distribution.SendAutoCallFileAsync(request, ct);
|
||||
|
||||
[HttpPost("auto-call/ivr")]
|
||||
[RequirePermission(PermissionKeys.PermitsDistribution)]
|
||||
public Task<PermitOperationResult> TriggerIvr(CancellationToken ct) => distribution.TriggerIvrAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>autoCallResponse.cfc: the dialer's callback. Authenticated with the X-Api-Key header (Grains:Permits:AutoCall:ApiKey), not a JWT.</summary>
|
||||
[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<IActionResult> 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 });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Weighbridges and print pages (legacy WeightBridge.cfm / EN_WeightBridge.cfm / EX_WeightBridge.cfm / loadingWeightBridge.cfm / printIn / printOut / acceptPrint).</summary>
|
||||
[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<WeighbridgeResult> Enter(WeighbridgeReadingRequest request, CancellationToken ct) => weighbridge.EnterAsync(request, ct);
|
||||
|
||||
[HttpPost("exit")]
|
||||
[RequirePermission(PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<WeighbridgeResult> Exit(WeighbridgeReadingRequest request, CancellationToken ct) => weighbridge.ExitAsync(request, ct);
|
||||
|
||||
[HttpPost("manual")]
|
||||
[RequirePermission(PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<PermitOperationResult> Manual(ManualWeighbridgeRequest request, CancellationToken ct) => weighbridge.ManualAsync(request, ct);
|
||||
|
||||
[HttpPost("loading-weights")]
|
||||
[RequirePermission(PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<PermitOperationResult> Loading(WeighbridgeWeightsRequest request, CancellationToken ct) => weighbridge.LoadingWeightsAsync(request, ct);
|
||||
|
||||
[HttpPost("discharge-weights")]
|
||||
[RequirePermission(PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<PermitOperationResult> Discharge(WeighbridgeWeightsRequest request, CancellationToken ct) => weighbridge.DischargeWeightsAsync(request, ct);
|
||||
|
||||
/// <summary>getTruckInfoFromTN.</summary>
|
||||
[HttpGet("truck/{tn}")]
|
||||
[RequirePermission(PermissionKeys.PermitsWeighbridge, PermissionKeys.PermitsClose)]
|
||||
public Task<TruckPermitBriefDto?> Truck(string tn, [FromQuery] string status, CancellationToken ct) => weighbridge.GetTruckPermitAsync(tn, status, ct);
|
||||
|
||||
[HttpGet("truck/{tn}/weight")]
|
||||
[RequirePermission(PermissionKeys.PermitsWeighbridge, PermissionKeys.PermitsClose)]
|
||||
public Task<WaybridgeEventDto?> TruckWeight(string tn, CancellationToken ct) => weighbridge.GetTruckWaybridgeEventAsync(tn, ct);
|
||||
|
||||
/// <summary>getlocTruckNum (locTruckNumGrid.cfm).</summary>
|
||||
[HttpGet("location-truck-counts")]
|
||||
[RequirePermission(PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<IReadOnlyList<LocationTruckCountDto>> LocationCounts(CancellationToken ct) => weighbridge.GetLocationTruckCountsAsync(ct);
|
||||
|
||||
// ---- print data
|
||||
[HttpGet("{permitId:long}/print/accept")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<AcceptPrintDto> AcceptPrint(long permitId, CancellationToken ct) => weighbridge.GetAcceptPrintAsync(permitId, ct);
|
||||
|
||||
[HttpGet("{permitId:long}/print/in")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<PrintInDto> PrintIn(long permitId, CancellationToken ct) => weighbridge.GetPrintInAsync(permitId, ct);
|
||||
|
||||
[HttpGet("{permitId:long}/print/out")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<PrintOutDto> PrintOut(long permitId, CancellationToken ct) => weighbridge.GetPrintOutAsync(permitId, ct);
|
||||
|
||||
[HttpGet("{permitId:long}/print/details")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsWeighbridge)]
|
||||
public Task<PermitDetailsPrintDto> Details(long permitId, CancellationToken ct) => weighbridge.GetPermitDetailsAsync(permitId, ct);
|
||||
|
||||
// ---- jobs on demand
|
||||
[HttpPost("jobs/sync")]
|
||||
[Authorize(Roles = "SU")]
|
||||
public async Task<ActionResult<object>> Sync([FromQuery] bool aqaba, CancellationToken ct) => new { processed = await weighbridge.SyncAsync(aqaba, ct) };
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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
|
||||
|
||||
/// <summary>What the caller may do on the registry screens (legacy isActAuthorized buttons).</summary>
|
||||
[HttpGet("permissions")]
|
||||
public Task<RegistryPermissionsDto> Permissions(CancellationToken ct) => lookups.PermissionsAsync(ct);
|
||||
|
||||
/// <summary>NTP_TENDERS_COMPANIES (ACTIVE): the company select of the truck/trailer forms and filters.</summary>
|
||||
[HttpGet("lookups/companies")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers, PermissionKeys.RegistryBlacklist)]
|
||||
public Task<IReadOnlyList<TenderCompanyDto>> Companies(CancellationToken ct) => lookups.CompaniesAsync(ct);
|
||||
|
||||
/// <summary>TRUCKKINDS by code (S, T for trucks; HTR, TR for trailers): the axial loads select.</summary>
|
||||
[HttpGet("lookups/truck-kinds")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)]
|
||||
public Task<IReadOnlyList<TruckKindDto>> TruckKinds([FromQuery] string kinds, CancellationToken ct) =>
|
||||
lookups.TruckKindsAsync((kinds ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), ct);
|
||||
|
||||
/// <summary>Destination locations grouped as on the truck form (packed / bulk / bulk-gallab).</summary>
|
||||
[HttpGet("lookups/destinations")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks)]
|
||||
public Task<RegistryDestinationOptionsDto> Destinations(CancellationToken ct) => lookups.DestinationsAsync(ct);
|
||||
|
||||
[HttpGet("lookups/driver-nationalities")]
|
||||
[RequirePermission(PermissionKeys.RegistryDrivers)]
|
||||
public Task<IReadOnlyList<RegistryNationalityDto>> DriverNationalities(CancellationToken ct) => lookups.DriverNationalitiesAsync(ct);
|
||||
|
||||
[HttpGet("lookups/weighbridge-locations")]
|
||||
[RequirePermission(PermissionKeys.RegistryWeighbridge)]
|
||||
public Task<IReadOnlyList<RegistryLocationDto>> WeighbridgeLocations(CancellationToken ct) => lookups.WeighbridgeLocationsAsync(ct);
|
||||
|
||||
// ------------------------------------------------------------------------------------------ trucks (truckGrid.cfm, registerGrainsTruck.cfm)
|
||||
|
||||
/// <summary>getTruckGrid. searchType TN (trucks, default) or TRN (searches the trailers table, rows carry tnId).</summary>
|
||||
[HttpGet("trucks")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks)]
|
||||
public Task<PagedResult<TruckGridRowDto>> 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);
|
||||
|
||||
/// <summary>getTruckInfo (+ connected trailer, destinations, attachments).</summary>
|
||||
[HttpGet("trucks/{id:long}")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks)]
|
||||
public Task<TruckDetailDto> GetTruck(long id, CancellationToken ct) => trucks.GetAsync(id, ct);
|
||||
|
||||
/// <summary>getAllTrnOnthisTn: trailers connected to the truck.</summary>
|
||||
[HttpGet("trucks/{id:long}/trailers")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)]
|
||||
public Task<IReadOnlyList<TrailerGridRowDto>> TrailersOfTruck(long id, CancellationToken ct) => trucks.TrailersAsync(id, null, ct);
|
||||
|
||||
/// <summary>saveTrucksDetails.</summary>
|
||||
[HttpPost("trucks")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucksCreate)]
|
||||
public Task<RegistryResult> CreateTruck(SaveTruckRequest request, CancellationToken ct) => trucks.CreateAsync(request, ct);
|
||||
|
||||
/// <summary>editTrucksDetails.</summary>
|
||||
[HttpPut("trucks/{id:long}")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucksEdit)]
|
||||
public Task<RegistryResult> UpdateTruck(long id, SaveTruckRequest request, CancellationToken ct) => trucks.UpdateAsync(id, request, ct);
|
||||
|
||||
/// <summary>acceptTruck (-> ACCPT).</summary>
|
||||
[HttpPost("trucks/{id:long}/accept")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks)]
|
||||
public Task<RegistryResult> AcceptTruck(long id, CancellationToken ct) => trucks.AcceptAsync(id, ct);
|
||||
|
||||
/// <summary>revokeTruck (-> RVKD, cascades to trailers, destinations and open permits).</summary>
|
||||
[HttpPost("trucks/{id:long}/revoke")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks)]
|
||||
public Task<RegistryResult> RevokeTruck(long id, CancellationToken ct) => trucks.RevokeAsync(id, ct);
|
||||
|
||||
// ------------------------------------------------------------------------------------------ trailers (trailerGrid.cfm, registerGrainsTrailer.cfm)
|
||||
|
||||
[HttpGet("trailers")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrailers)]
|
||||
public Task<PagedResult<TrailerGridRowDto>> 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<TrailerDetailDto> GetTrailer(long id, CancellationToken ct) => trailers.GetAsync(id, ct);
|
||||
|
||||
/// <summary>saveTrailerDetails.</summary>
|
||||
[HttpPost("trailers")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrailersCreate)]
|
||||
public Task<RegistryResult> CreateTrailer(SaveTrailerRequest request, CancellationToken ct) => trailers.CreateAsync(request, ct);
|
||||
|
||||
/// <summary>editTrailerDetails.</summary>
|
||||
[HttpPut("trailers/{id:long}")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrailersEdit)]
|
||||
public Task<RegistryResult> UpdateTrailer(long id, SaveTrailerRequest request, CancellationToken ct) => trailers.UpdateAsync(id, request, ct);
|
||||
|
||||
[HttpPost("trailers/{id:long}/accept")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrailers)]
|
||||
public Task<RegistryResult> AcceptTrailer(long id, CancellationToken ct) => trailers.AcceptAsync(id, ct);
|
||||
|
||||
[HttpPost("trailers/{id:long}/revoke")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrailers)]
|
||||
public Task<RegistryResult> RevokeTrailer(long id, CancellationToken ct) => trailers.RevokeAsync(id, ct);
|
||||
|
||||
// ------------------------------------------------------------------------------------------ drivers (driverGrid.cfm, regesterDriver.cfm)
|
||||
|
||||
[HttpGet("drivers")]
|
||||
[RequirePermission(PermissionKeys.RegistryDrivers)]
|
||||
public Task<PagedResult<DriverGridRowDto>> 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<DriverDetailDto> GetDriver(long id, CancellationToken ct) => drivers.GetAsync(id, ct);
|
||||
|
||||
/// <summary>saveDriverDetails.</summary>
|
||||
[HttpPost("drivers")]
|
||||
[RequirePermission(PermissionKeys.RegistryDriversCreate)]
|
||||
public Task<RegistryResult> CreateDriver(SaveDriverRequest request, CancellationToken ct) => drivers.CreateAsync(request, ct);
|
||||
|
||||
[HttpPost("drivers/{id:long}/accept")]
|
||||
[RequirePermission(PermissionKeys.RegistryDrivers)]
|
||||
public Task<RegistryResult> AcceptDriver(long id, CancellationToken ct) => drivers.AcceptAsync(id, ct);
|
||||
|
||||
[HttpPost("drivers/{id:long}/revoke")]
|
||||
[RequirePermission(PermissionKeys.RegistryDrivers)]
|
||||
public Task<RegistryResult> RevokeDriver(long id, CancellationToken ct) => drivers.RevokeAsync(id, ct);
|
||||
|
||||
// ------------------------------------------------------------------------------------------ blacklist (blackListGrid.cfm, createBlacklist.cfm, confirmDeleteBL.cfm)
|
||||
|
||||
/// <summary>getBlackListGrid. entityId = permit number.</summary>
|
||||
[HttpGet("blacklist")]
|
||||
[RequirePermission(PermissionKeys.RegistryBlacklist)]
|
||||
public Task<PagedResult<BlacklistGridRowDto>> 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);
|
||||
|
||||
/// <summary>BL_addToBlacklist.</summary>
|
||||
[HttpPost("blacklist")]
|
||||
[RequirePermission(PermissionKeys.RegistryBlacklist)]
|
||||
public Task<BlacklistAddedDto> AddToBlacklist(AddBlacklistRequest request, CancellationToken ct) => blacklist.AddAsync(request, ct);
|
||||
|
||||
/// <summary>deleteFromBlackList (roles GNSU, GNCO, GTO).</summary>
|
||||
[HttpPost("blacklist/{id:long}/cancel")]
|
||||
[RequirePermission(PermissionKeys.RegistryBlacklist)]
|
||||
public Task<RegistryResult> CancelBlacklist(long id, CancelBlacklistRequest request, CancellationToken ct) => blacklist.CancelAsync(id, request, ct);
|
||||
|
||||
// ------------------------------------------------------------------------------------------ weighbridge exceptions, weights, counts, fleet
|
||||
|
||||
/// <summary>saveWeighbridgesControlInfo (WeighbridgesControl.cfm).</summary>
|
||||
[HttpPost("weighbridge-control")]
|
||||
[RequirePermission(PermissionKeys.RegistryWeighbridge)]
|
||||
public Task<RegistryResult> SaveWeighbridgeControl(SaveWeighbridgeControlRequest request, CancellationToken ct) =>
|
||||
ops.SaveWeighbridgeControlAsync(request, ct);
|
||||
|
||||
/// <summary>saveGrainsWeights.</summary>
|
||||
[HttpPost("permit-weights")]
|
||||
[RequirePermission(PermissionKeys.OrdersWeights)]
|
||||
public Task<RegistryResult> SaveGrainsWeights(SaveGrainsWeightsRequest request, CancellationToken ct) => ops.SaveGrainsWeightsAsync(request, ct);
|
||||
|
||||
/// <summary>getlocTruckNum (locTruckNumGrid.cfm, refreshed every 5 minutes by the screen).</summary>
|
||||
[HttpGet("location-truck-counts")]
|
||||
[RequirePermission(PermissionKeys.RegistryLocationCounts)]
|
||||
public Task<IReadOnlyList<LocationTruckCountDto>> LocationTruckCounts(CancellationToken ct) => ops.LocationTruckCountsAsync(ct);
|
||||
|
||||
/// <summary>checkTrucks: every company must use its whole fleet before reusing a truck.</summary>
|
||||
[HttpPost("fleet-check")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.PermitsQueue)]
|
||||
public Task<FleetCheckResult> FleetCheck(FleetCheckRequest request, CancellationToken ct) => ops.CheckTrucksAsync(request, ct);
|
||||
|
||||
/// <summary>validateNtpTrucks.</summary>
|
||||
[HttpGet("validate-truck")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)]
|
||||
public async Task<object> ValidateTruck([FromQuery] string tn, CancellationToken ct) => new { validTn = await ops.ValidateNtpTruckAsync(tn ?? string.Empty, ct) };
|
||||
|
||||
// ------------------------------------------------------------------------------------------ permit-screen lookups (grains.cfc)
|
||||
|
||||
/// <summary>grains.cfc getDriverInfo: latest permit of the driver (active status).</summary>
|
||||
[HttpGet("permit-lookups/driver")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)]
|
||||
public Task<DriverFromPermitDto?> DriverFromPermits([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverFromPermitsAsync(nnpn ?? string.Empty, ct);
|
||||
|
||||
/// <summary>grains.cfc getTruckInfo: latest finished permit of the truck.</summary>
|
||||
[HttpGet("permit-lookups/truck")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)]
|
||||
public Task<TruckFromPermitDto?> TruckFromPermits([FromQuery] string tn, CancellationToken ct) => lookups.TruckFromPermitsAsync(tn ?? string.Empty, ct);
|
||||
|
||||
/// <summary>grains.cfc isTrailerInUse.</summary>
|
||||
[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<IReadOnlyList<TrailerInUseDto>> TrailerInUse([FromQuery] string trn, [FromQuery] long? permitId, CancellationToken ct) =>
|
||||
lookups.TrailerInUseAsync(trn ?? string.Empty, permitId, ct);
|
||||
|
||||
/// <summary>grains.cfc getTruckInfoFromTN.</summary>
|
||||
[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<PermitByTruckDto?> PermitByTruck([FromQuery] string tn, [FromQuery] string status, CancellationToken ct) =>
|
||||
lookups.PermitByTruckAsync(tn ?? string.Empty, status ?? string.Empty, ct);
|
||||
|
||||
/// <summary>grains.cfc getTrailerNumber: the trailer of a truck.</summary>
|
||||
[HttpGet("permit-lookups/truck-trailer")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)]
|
||||
public Task<TrailerOfTruckDto> TruckTrailer([FromQuery] string tn, CancellationToken ct) => lookups.TrailerNumberOfTruckAsync(tn ?? string.Empty, ct);
|
||||
|
||||
/// <summary>grains.cfc getTNinfo (validate = ownership + MOT checks).</summary>
|
||||
[HttpGet("permit-lookups/truck-info")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)]
|
||||
public Task<TruckInfoForPermitDto> TruckInfo([FromQuery] string tn, [FromQuery] bool validate = true, CancellationToken ct = default) =>
|
||||
lookups.TruckInfoAsync(tn ?? string.Empty, validate, ct);
|
||||
|
||||
/// <summary>grains.cfc getTRNinfo.</summary>
|
||||
[HttpGet("permit-lookups/trailer-info")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)]
|
||||
public Task<TrailerInfoForPermitDto> TrailerInfo([FromQuery] string trn, CancellationToken ct) => lookups.TrailerInfoAsync(trn ?? string.Empty, ct);
|
||||
|
||||
/// <summary>grains.cfc getDRVRinfo.</summary>
|
||||
[HttpGet("permit-lookups/driver-info")]
|
||||
[RequirePermission(PermissionKeys.PermitsList, PermissionKeys.PermitsQueue, PermissionKeys.PermitsTruckOrder, PermissionKeys.PermitsClose, PermissionKeys.PermitsManualEntry, PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)]
|
||||
public Task<DriverInfoForPermitDto> DriverInfo([FromQuery] string nnpn, CancellationToken ct) => lookups.DriverInfoAsync(nnpn ?? string.Empty, ct);
|
||||
|
||||
// ------------------------------------------------------------------------------------------ MOT (register.cfc validate*)
|
||||
|
||||
/// <summary>validateTNMOT: result '' (ok), 'not_registered' or 'wrongCT'.</summary>
|
||||
[HttpGet("mot/truck")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)]
|
||||
public async Task<object> MotTruck([FromQuery] string tn, [FromQuery] long scac, [FromQuery] string? truckType, CancellationToken ct) =>
|
||||
new { result = await lookups.ValidateTruckMotAsync(tn ?? string.Empty, scac, truckType, ct) };
|
||||
|
||||
/// <summary>validateTRNMOT: result '' (ok) or 'not_registered'.</summary>
|
||||
[HttpGet("mot/trailer")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)]
|
||||
public async Task<object> MotTrailer([FromQuery] string trn, [FromQuery] long scac, CancellationToken ct) =>
|
||||
new { result = await lookups.ValidateTrailerMotAsync(trn ?? string.Empty, scac, ct) };
|
||||
|
||||
/// <summary>validateOwnerTN: message '' (ok) or the legacy Arabic error.</summary>
|
||||
[HttpGet("mot/owner")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers)]
|
||||
public async Task<object> MotOwner([FromQuery] string tn, [FromQuery] long scac, CancellationToken ct) =>
|
||||
new { message = await lookups.ValidateOwnerAsync(scac, tn ?? string.Empty, ct) };
|
||||
|
||||
// ------------------------------------------------------------------------------------------ attachments
|
||||
|
||||
/// <summary>Temp upload: returns { id, name, size }; the id goes into attachmentIds of a save request.</summary>
|
||||
[HttpPost("files/temp")]
|
||||
[RequestSizeLimit(20_000_000)]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)]
|
||||
public async Task<RegistryTempFileDto> UploadTemp(IFormFile file, CancellationToken ct)
|
||||
{
|
||||
await using var stream = file.OpenReadStream();
|
||||
return await attachments.UploadTempAsync(stream, file.FileName, file.Length, ct);
|
||||
}
|
||||
|
||||
/// <summary>Downloads a stored attachment (kind: truck | trailer | driver).</summary>
|
||||
[HttpGet("files/{kind}/{fileName}")]
|
||||
[RequirePermission(PermissionKeys.RegistryTrucks, PermissionKeys.RegistryTrailers, PermissionKeys.RegistryDrivers)]
|
||||
public async Task<IActionResult> 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)
|
||||
|
||||
/// <summary>jobs\changeBlacklistStatus.cfm: OPEN entries past their expiry date become EXPIRED.</summary>
|
||||
[HttpPost("jobs/expire-blacklist")]
|
||||
[Authorize(Roles = "SU")]
|
||||
public async Task<object> ExpireBlacklist(CancellationToken ct) => new { expired = await blacklist.ExpireDueAsync(ct) };
|
||||
|
||||
/// <summary>jobs\RegisterGrainsQueueForNewTrucks.cfm: PCKD + BULK queue permits for 327 trucks that have none.</summary>
|
||||
[HttpPost("jobs/register-queue-new-trucks")]
|
||||
[Authorize(Roles = "SU")]
|
||||
public async Task<object> RegisterQueueForNewTrucks(CancellationToken ct) => new { trucks = await queuePermits.RegisterQueueForNewTrucksAsync(ct) };
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Grains reports, dashboards, MOT reports and the file imports (legacy reports.cfc, Reports\*.cfm, *.cfr, ParseFile.cfc, ReadFiles\*).
|
||||
/// Tabular reports share one shape: <c>GET tables/{key}</c> (paged JSON for the grid) and <c>GET tables/{key}/export</c> (xlsx).
|
||||
/// </summary>
|
||||
[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<IReadOnlyList<LookupItem>> 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<IReadOnlyList<LookupItem>> 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<IReadOnlyList<LookupItem>> 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<NumOfTripsAndTrucksReport> NumOfTripsAndTrucks([FromQuery] DateOnly from, [FromQuery] DateOnly to, CancellationToken ct) =>
|
||||
reports.NumOfTripsAndTrucksAsync(from, to, ct);
|
||||
|
||||
[HttpGet("trips/quota")]
|
||||
[RequirePermission(PermissionKeys.ReportsQuota)]
|
||||
public Task<QuotaReport> Quota([FromQuery] DateOnly from, [FromQuery] DateOnly to, CancellationToken ct) =>
|
||||
reports.QuotaAsync(from, to, ct);
|
||||
|
||||
[HttpGet("trips/frequency")]
|
||||
[RequirePermission(PermissionKeys.ReportsFrequency)]
|
||||
public Task<FrequencyReport> Frequency([FromQuery] DateOnly from, [FromQuery] DateOnly to, [FromQuery] string? scac,
|
||||
[FromQuery] string? cargoType, CancellationToken ct) => reports.FrequencyAsync(from, to, scac, cargoType, ct);
|
||||
|
||||
/// <summary>TripsDistributionRpt (grouped 1-3, 4-6...) uses the same data as the frequency report (field <c>groups</c>).</summary>
|
||||
[HttpGet("trips/distribution")]
|
||||
[RequirePermission(PermissionKeys.ReportsDistribution)]
|
||||
public Task<FrequencyReport> Distribution([FromQuery] DateOnly from, [FromQuery] DateOnly to, CancellationToken ct) =>
|
||||
reports.FrequencyAsync(from, to, null, null, ct);
|
||||
|
||||
[HttpGet("trips/details")]
|
||||
[RequirePermission(PermissionKeys.ReportsDetails)]
|
||||
public Task<DetailsReport> Details([FromQuery] DateOnly from, [FromQuery] DateOnly to, CancellationToken ct) =>
|
||||
reports.DetailsAsync(from, to, ct);
|
||||
|
||||
/// <summary>grainsDashboards.cfm: charts input (trucks per number of trips) with optional company / cargo filter.</summary>
|
||||
[HttpGet("dashboard")]
|
||||
[RequirePermission(PermissionKeys.ReportsDashboard)]
|
||||
public Task<FrequencyReport> 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<MotMultiTripsReport> MotMultiTrips(CancellationToken ct) => reports.MotMultiTripsAsync(ct);
|
||||
|
||||
// ------------------------------------------------------------------ table reports
|
||||
[HttpGet("tables/{key}")]
|
||||
public async Task<ReportPage> 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<IActionResult> 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
|
||||
|
||||
/// <summary>uploadAccptExlFile.cfm: IVR approvals file (CSV or XLSX) -> one accept / reject per row.</summary>
|
||||
[HttpPost("imports/phone-approvals")]
|
||||
[RequestSizeLimit(MaxUpload)]
|
||||
[Authorize(Roles = "SU")]
|
||||
public async Task<PhoneImportResult> 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<FileImportResult> 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<FileImportResult> 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<FileImportResult> 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);
|
||||
|
||||
/// <summary>One pass of the directory watcher (the background watcher itself is disabled by default).</summary>
|
||||
[HttpPost("weighbridge-files/scan")]
|
||||
[Authorize(Roles = "SU")]
|
||||
public Task<WeighbridgeScanResult> Scan(ScanRequest request, CancellationToken ct) =>
|
||||
files.ScanDirectoryAsync(request.Directory, request.ArchiveDirectory, ct);
|
||||
|
||||
/// <summary>jobs/getWeighbridgeEvents.cfm (matching half): raw weighbridge rows -> permit events + CLOSE.</summary>
|
||||
[HttpPost("weighbridge-files/raw-sync")]
|
||||
[Authorize(Roles = "SU")]
|
||||
public Task<RawSyncResult> RawSync(CancellationToken ct) => files.SyncRawDataAsync(ct);
|
||||
|
||||
/// <summary>The table key is dynamic, so the permission is checked here instead of with an attribute.</summary>
|
||||
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", "الملف فارغ");
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Authentication of the external web-service area: either a configured API key (header <c>X-Api-Key</c>, config
|
||||
/// <c>GrainsReports:Ws:ApiKeys</c>) 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>External authenticated API used by weighbridge / TCS systems (legacy services\Grains\cfc\ws.cfc).</summary>
|
||||
[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 };
|
||||
|
||||
/// <summary>getTrackNo(TN, TRNAT, CLOSEDATE)</summary>
|
||||
[HttpPost("track-no")]
|
||||
public Task<WsResult> GetTrackNo(GetTrackNoRequest request, CancellationToken ct) => ws.GetTrackNoAsync(request, Caller, ct);
|
||||
|
||||
/// <summary>changeStatusToReqst(TN)</summary>
|
||||
[HttpPost("status-to-requested")]
|
||||
public Task<WsResult> ChangeStatusToReqst(ChangeStatusToReqstRequest request, CancellationToken ct) =>
|
||||
ws.ChangeStatusToReqstAsync(request, Caller, ct);
|
||||
|
||||
/// <summary>saveShipmentInfo: commented out in the legacy ws.cfc, so disabled unless GrainsReports:Ws:EnableSaveShipmentInfo=true.</summary>
|
||||
[HttpPost("shipment-info")]
|
||||
public Task<WsResult> SaveShipmentInfo(SaveShipmentInfoRequest request, CancellationToken ct)
|
||||
{
|
||||
if (!new GrainsReportsConfig(configuration).SaveShipmentInfoEnabled)
|
||||
throw new BusinessException("WS_OPERATION_DISABLED", "هذه العملية غير مفعلة");
|
||||
return ws.SaveShipmentInfoAsync(request, Caller, ct);
|
||||
}
|
||||
|
||||
/// <summary>addLoadingWeightEvent (pid is the plain permit id; the legacy encrypted id relied on the session key).</summary>
|
||||
[HttpPost("loading-weight-event")]
|
||||
public Task<WsResult> AddLoadingWeightEvent(LoadingWeightRequest request, CancellationToken ct) =>
|
||||
ws.AddLoadingWeightEventAsync(request, Caller, ct);
|
||||
|
||||
[HttpPost("discharge-weight-event")]
|
||||
public Task<WsResult> AddDischargeWeightEvent(LoadingWeightRequest request, CancellationToken ct) =>
|
||||
ws.AddDischargeWeightEventAsync(request, Caller, ct);
|
||||
|
||||
/// <summary>createPermitRecord(TN, SCAC, NEXTSTATUS, TT, checkStatuses)</summary>
|
||||
[HttpPost("permit-record")]
|
||||
public Task<WsResult> CreatePermitRecord(CreatePermitRecordRequest request, CancellationToken ct) =>
|
||||
ws.CreatePermitRecordAsync(request, Caller, ct);
|
||||
|
||||
/// <summary>addWeightBridgeEventWS (same as addWeightBridgeEvent + an audit row in GN_TCS_INTEGRATION).</summary>
|
||||
[HttpPost("weighbridge-event")]
|
||||
public Task<WbEventResult> AddWeightBridgeEvent(WeighbridgeEventRequest request, CancellationToken ct) =>
|
||||
ws.AddWeightBridgeEventWsAsync(request, Caller, HttpContext.Connection.RemoteIpAddress?.ToString(), ct);
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Application.Lookups;
|
||||
|
||||
namespace NTP.Api.Controllers.V1;
|
||||
|
||||
/// <summary>Generic lookups only. Grains-specific lookups belong to the Grains slice controllers. Domain defaults to the caller's domain.</summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/lookups")]
|
||||
[Produces("application/json")]
|
||||
public sealed class LookupsController(ILookupService service) : ControllerBase
|
||||
{
|
||||
/// <summary>STATUS rows for a domain (e.g. GN). isActive=true -> ISACTIVE = 1.</summary>
|
||||
[HttpGet("statuses")]
|
||||
public Task<IReadOnlyList<StatusDto>> Statuses([FromQuery] string? domain, [FromQuery] bool? isActive, CancellationToken ct) =>
|
||||
service.StatusesAsync(domain, isActive, ct);
|
||||
|
||||
/// <summary>LOCATIONS for a domain, optional type (LOC, EX, EN ...). Active only unless includeInactive.</summary>
|
||||
[HttpGet("locations")]
|
||||
public Task<IReadOnlyList<LocationDto>> Locations([FromQuery] string? domain, [FromQuery] string? type,
|
||||
[FromQuery] bool includeInactive, CancellationToken ct) =>
|
||||
service.LocationsAsync(domain, type, includeInactive, ct);
|
||||
|
||||
[HttpGet("cargo-types")]
|
||||
public Task<IReadOnlyList<CargoTypeDto>> CargoTypes([FromQuery] string? domain, CancellationToken ct) =>
|
||||
service.CargoTypesAsync(domain, ct);
|
||||
|
||||
[HttpGet("companies")]
|
||||
public Task<IReadOnlyList<CompanyDto>> Companies([FromQuery] bool includeInactive, CancellationToken ct) =>
|
||||
service.CompaniesAsync(includeInactive, ct);
|
||||
|
||||
[HttpGet("nationalities")]
|
||||
public Task<IReadOnlyList<NationalityDto>> Nationalities(CancellationToken ct) => service.NationalitiesAsync(ct);
|
||||
|
||||
[HttpGet("cities")]
|
||||
public Task<IReadOnlyList<CityDto>> Cities(CancellationToken ct) => service.CitiesAsync(ct);
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Application.Access;
|
||||
|
||||
namespace NTP.Api.Controllers.V1;
|
||||
|
||||
/// <summary>Tells the front end which modules, screens and actions the caller's role code may see.</summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/auth/permissions")]
|
||||
[Produces("application/json")]
|
||||
public sealed class PermissionsController(IPermissionService permissions) : ControllerBase
|
||||
{
|
||||
/// <summary><c>{ roleCode, all, allowed[] }</c>. SU gets <c>all = true</c> and an empty list.</summary>
|
||||
[HttpGet]
|
||||
public Task<PermissionsDto> Get(CancellationToken ct) => permissions.GetForCurrentUserAsync(ct);
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
using Asp.Versioning;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NTP.Application.Common;
|
||||
using NTP.Application.Shipments;
|
||||
|
||||
namespace NTP.Api.Controllers.V1;
|
||||
|
||||
/// <summary>SAMPLE controller - thin: HTTP in, service call, HTTP out. No SQL, no business rules.</summary>
|
||||
[ApiController]
|
||||
[ApiVersion(1.0)]
|
||||
[Route("api/v{version:apiVersion}/shipments")]
|
||||
[Produces("application/json")]
|
||||
public sealed class ShipmentsController(IShipmentService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[ProducesResponseType<PagedResult<ShipmentDto>>(StatusCodes.Status200OK)]
|
||||
public Task<PagedResult<ShipmentDto>> 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<ShipmentDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
public Task<ShipmentDto> GetShipment(long id, CancellationToken ct) => service.GetAsync(id, ct);
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType<ShipmentDto>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> 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<ShipmentDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public Task<ShipmentDto> Update(long id, UpdateShipmentRequest request, CancellationToken ct) =>
|
||||
service.UpdateAsync(id, request, ct);
|
||||
|
||||
[HttpDelete("{id:long}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> Delete(long id, [FromQuery] int rowVersion, CancellationToken ct)
|
||||
{
|
||||
await service.DeleteAsync(id, rowVersion, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class GlobalExceptionHandler(
|
||||
IProblemDetailsService problemDetails,
|
||||
IHostEnvironment env,
|
||||
ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
|
||||
{
|
||||
public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct)
|
||||
{
|
||||
var (status, title, detail, errors) = Map(exception);
|
||||
|
||||
if (status >= 500) logger.LogError(exception, "Unhandled error: {Title}", title);
|
||||
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<string, string[]>? 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<string, string[]>?) 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)
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<UserSecretsId>ntp-api-7c1e2f4a</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="NTP.Tests" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\NTP.Application\NTP.Application.csproj" />
|
||||
<ProjectReference Include="..\NTP.Infrastructure\NTP.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Asp.Versioning.Mvc" />
|
||||
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
@ -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<BearerSecurityTransformer>());
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
|
||||
|
||||
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<string[]>() ?? ["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<IOptions<OracleOptions>>().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();
|
||||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
@ -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=<password>;Data Source=<host>:1521/<service>;Min Pool Size=1;Max Pool Size=50;Connection Timeout=15;Statement Cache Size=50",
|
||||
"NtpSchema": "User Id=NTP;Password=<password>;Data Source=<host>:1521/<service>;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"
|
||||
}
|
||||
}
|
||||
|
|
@ -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://<web-host>
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
|
@ -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://<qa-web-host>
|
||||
"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
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
namespace NTP.Application.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// The authenticated caller. Replaces legacy session.*. Values come from JWT claims (see <see cref="AppClaims"/>);
|
||||
/// when the request is anonymous strings are empty and numbers null/0.
|
||||
/// </summary>
|
||||
public interface ICurrentUser
|
||||
{
|
||||
bool IsAuthenticated { get; }
|
||||
/// <summary>NTPUSERS.ID.</summary>
|
||||
long Id { get; }
|
||||
/// <summary>Upper-cased login, like legacy session.userid.</summary>
|
||||
string UserId { get; }
|
||||
/// <summary>legacy session.username (NTPUSERS.FIRSTNAME).</summary>
|
||||
string Name { get; }
|
||||
/// <summary>legacy session.userRoleCode.</summary>
|
||||
string RoleCode { get; }
|
||||
/// <summary>legacy session.rolecodeName (ROLES.NAME).</summary>
|
||||
string RoleName { get; }
|
||||
/// <summary>legacy session.domain (NTPUSERS.DOMAINNAME, e.g. ASEZA, GN).</summary>
|
||||
string Domain { get; }
|
||||
long? LocationId { get; }
|
||||
string LocationName { get; }
|
||||
/// <summary>legacy session.STKID (GROUPS.STAKEHOLDERID).</summary>
|
||||
long? StkId { get; }
|
||||
/// <summary>legacy session.COMPID (hierarchy query companyid).</summary>
|
||||
long? CompId { get; }
|
||||
/// <summary>legacy session.CompanyId.</summary>
|
||||
long? CompanyId { get; }
|
||||
string CompanyName { get; }
|
||||
/// <summary>legacy session.companyCode (COMPANIES.DESCRIPTION).</summary>
|
||||
string CompanyCode { get; }
|
||||
string EmpNo { get; }
|
||||
/// <summary>"AR" or "EN".</summary>
|
||||
string Lang { get; }
|
||||
/// <summary>legacy session.nafithEmp (CompanyId = 15).</summary>
|
||||
bool IsStaff { get; }
|
||||
|
||||
/// <summary>Case-insensitive role-code check (legacy listFindNoCase(..., session.userrolecode)).</summary>
|
||||
bool IsInRole(string roleCode);
|
||||
bool IsInAnyRole(params string[] roleCodes);
|
||||
}
|
||||
|
||||
/// <summary>JWT claim names shared by the token issuer and <see cref="ICurrentUser"/>.</summary>
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>Issues the signed access token (implemented in Api).</summary>
|
||||
public interface ITokenIssuer
|
||||
{
|
||||
(string Token, DateTime ExpiresAtUtc) Issue(NTP.Application.Auth.AuthenticatedUser user);
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
namespace NTP.Application.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// One row of the legacy EVENTS audit table (port of services.cfc addEvent).
|
||||
/// <c>RefColumn</c> is the id column to fill: PERMITID, CRID, ORDERID, WAYBILLID (any identifier ^[A-Z][A-Z0-9_]{0,29}$).
|
||||
/// </summary>
|
||||
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<string, object?>? ExtraColumns = null);
|
||||
|
||||
public interface IEventLogger
|
||||
{
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
Task AddAsync(EventEntry entry, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Same, taking DoneBy/Domain/LocationId from <see cref="ICurrentUser"/> (legacy session.userid/domain/locationid).</summary>
|
||||
Task AddForCurrentUserAsync(string refColumn, long refId, string? prevStatus, string? currentStatus,
|
||||
string eventType, string? remarks = null, string? weight = null, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
using NTP.Application.Common;
|
||||
using NTP.Application.Shipments;
|
||||
using NTP.Domain.Entities;
|
||||
|
||||
namespace NTP.Application.Abstractions;
|
||||
|
||||
public interface IShipmentRepository
|
||||
{
|
||||
Task<Shipment?> GetByIdAsync(long id, CancellationToken ct = default);
|
||||
Task<PagedResult<Shipment>> SearchAsync(ShipmentQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<bool> ExistsByNumberAsync(string shipmentNo, long? excludeId = null, CancellationToken ct = default);
|
||||
Task<long> InsertAsync(Shipment shipment, CancellationToken ct = default);
|
||||
|
||||
/// <returns>Number of rows affected (0 = not found or concurrency conflict).</returns>
|
||||
Task<int> UpdateAsync(Shipment shipment, CancellationToken ct = default);
|
||||
|
||||
/// <returns>Number of rows affected.</returns>
|
||||
Task<int> DeleteAsync(long id, int rowVersion, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
namespace NTP.Application.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Wraps a single Oracle connection + optional transaction for the current request.
|
||||
/// Repositories resolved in the same scope automatically enlist in the active transaction.
|
||||
/// </summary>
|
||||
public interface IUnitOfWork
|
||||
{
|
||||
Task BeginAsync(CancellationToken ct = default);
|
||||
Task CommitAsync(CancellationToken ct = default);
|
||||
Task RollbackAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> inside a transaction; commits on success, rolls back on exception.</summary>
|
||||
Task<T> ExecuteInTransactionAsync<T>(Func<CancellationToken, Task<T>> work, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unit of work on the second connection (NTP schema: NTPUSERS, LOGS ...). Separate from <see cref="IUnitOfWork"/>
|
||||
/// (primary NAFITHTCS connection); there is no distributed transaction across the two.
|
||||
/// </summary>
|
||||
public interface INtpUnitOfWork : IUnitOfWork;
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
namespace NTP.Application.Access;
|
||||
|
||||
/// <summary>
|
||||
/// Stable resource keys the front end and the API agree on. A key is a menu entry (module/screen) or an action
|
||||
/// inside a screen. The front end uses the menu <c>key</c> of each entry (see web/src/features/*/routes.tsx).
|
||||
/// </summary>
|
||||
public static class PermissionKeys
|
||||
{
|
||||
// Screens (menu keys)
|
||||
public const string OrdersList = "grains.orders.list";
|
||||
/// <summary>Action: new order (طلبية جديدة) button, create page and POST /orders.</summary>
|
||||
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";
|
||||
|
||||
/// <summary>Prefix of the per-table report keys (const so attributes can use it).</summary>
|
||||
public const string TableKeyPrefix = "grains.reports.t.";
|
||||
|
||||
/// <summary>Tabular report menu key (grains.reports.t.<table key>; keys in web/src/features/grains-reports/meta.tsx).</summary>
|
||||
public static string ReportTable(string tableKey) => TableKeyPrefix + tableKey;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static class PermissionDefaults
|
||||
{
|
||||
public static readonly IReadOnlyDictionary<string, string[]> RolesByResource = new Dictionary<string, string[]>(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"], // تحديد وجهة ارسالية تموين
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
using System.Collections.Concurrent;
|
||||
using NTP.Application.Abstractions;
|
||||
|
||||
namespace NTP.Application.Access;
|
||||
|
||||
/// <summary>What the front end needs to show or hide modules, screens and actions for the caller's role.</summary>
|
||||
/// <param name="RoleCode">Caller's role code.</param>
|
||||
/// <param name="All">True for SU: everything is allowed, <paramref name="Allowed"/> is then empty.</param>
|
||||
/// <param name="Allowed">Allowed resource keys (see <see cref="PermissionKeys"/>), e.g. grains.orders.list.</param>
|
||||
public sealed record PermissionsDto(string RoleCode, bool All, IReadOnlyList<string> Allowed);
|
||||
|
||||
public interface IPermissionRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// Resource keys allowed for the role from GRAINS_SCREEN_PERMISSIONS, or <c>null</c> when that table does not
|
||||
/// exist yet (the caller then falls back to <see cref="PermissionDefaults"/>).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<string>?> GetAllowedAsync(string roleCode, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IPermissionService
|
||||
{
|
||||
/// <summary>Permissions of the current caller.</summary>
|
||||
Task<PermissionsDto> GetForCurrentUserAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>True if the current caller may use the resource (SU: always).</summary>
|
||||
Task<bool> IsAllowedAsync(string resourceKey, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Role -> allowed resource keys. SU is always allowed everything; any other role is allow-listed.</summary>
|
||||
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<string, (DateTime ExpiresUtc, HashSet<string> Keys)> Cache = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public async Task<PermissionsDto> 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<bool> 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<HashSet<string>> 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<string>(fromDb ?? DefaultsFor(role), StringComparer.OrdinalIgnoreCase);
|
||||
Cache[role] = (DateTime.UtcNow + CacheTtl, keys);
|
||||
return keys;
|
||||
}
|
||||
|
||||
private static IEnumerable<string> DefaultsFor(string role) =>
|
||||
PermissionDefaults.RolesByResource
|
||||
.Where(kv => kv.Value.Contains(role, StringComparer.OrdinalIgnoreCase))
|
||||
.Select(kv => kv.Key);
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
namespace NTP.Application.Auth;
|
||||
|
||||
/// <summary>UserName is the legacy "DOMAIN.login" form (e.g. "ASEZA.50034" or "GN.company1").</summary>
|
||||
public sealed record LoginRequest(string UserName, string Password);
|
||||
|
||||
public sealed record ChangePasswordRequest(string OldPassword, string NewPassword, string? ConfirmNewPassword = null);
|
||||
|
||||
/// <summary>Lang is "AR" or "EN".</summary>
|
||||
public sealed record SetLanguageRequest(string Lang);
|
||||
|
||||
public sealed record ClientInfo(string? IpAddress, string? UserAgent);
|
||||
|
||||
/// <summary>Everything the legacy assignUserVariables put in the session that the new system needs.</summary>
|
||||
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);
|
||||
|
|
@ -0,0 +1,190 @@
|
|||
using FluentValidation;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Auth;
|
||||
|
||||
public interface IAuthService
|
||||
{
|
||||
Task<LoginResponse> LoginAsync(LoginRequest request, ClientInfo client, CancellationToken ct);
|
||||
Task<TokenResponse> SetLanguageAsync(SetLanguageRequest request, CancellationToken ct);
|
||||
Task<MessageResponse> ChangePasswordAsync(ChangePasswordRequest request, CancellationToken ct);
|
||||
Task SignOutAsync(ClientInfo client, CancellationToken ct);
|
||||
|
||||
/// <summary>Application.cfc: user still active with the same role code.</summary>
|
||||
Task<bool> IsUserStillActiveAsync(string login, string roleCode, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of NTP_LIVE components/signon.cfc (checkLogin, assignUserVariables, changePass, signOut).</summary>
|
||||
public sealed class AuthService(
|
||||
IAuthRepository repository,
|
||||
ITokenIssuer tokenIssuer,
|
||||
ICurrentUser currentUser,
|
||||
IValidator<LoginRequest> loginValidator,
|
||||
IValidator<ChangePasswordRequest> changePasswordValidator,
|
||||
IValidator<SetLanguageRequest> 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<LoginResponse> 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<TokenResponse> 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<MessageResponse> 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<bool> 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<Task> action)
|
||||
{
|
||||
try { await action(); }
|
||||
catch { /* legacy swallows audit-log failures; they must never block sign-in/out */ }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
using FluentValidation;
|
||||
|
||||
namespace NTP.Application.Auth;
|
||||
|
||||
public sealed class LoginRequestValidator : AbstractValidator<LoginRequest>
|
||||
{
|
||||
public LoginRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.UserName).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.Password).NotEmpty().MaximumLength(200);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ChangePasswordRequestValidator : AbstractValidator<ChangePasswordRequest>
|
||||
{
|
||||
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<SetLanguageRequest>
|
||||
{
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
|
@ -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; }
|
||||
}
|
||||
|
||||
/// <summary>Legacy info.getConactInfo (ntpusers joined to companies).</summary>
|
||||
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
|
||||
{
|
||||
/// <summary>Credential check. <paramref name="requireActiveCompany"/> mirrors the ASEZA branch (join COMPANIES, status = 1).</summary>
|
||||
Task<UserLoginRow?> FindActiveUserByPasswordAsync(string login, string domain, IReadOnlyList<string> passwordCandidates,
|
||||
bool requireActiveCompany, CancellationToken ct = default);
|
||||
|
||||
/// <summary>GateEventsFactory.CheckAuthorization: active UTT (booth) row for the login.</summary>
|
||||
Task<bool> HasActiveBoothAsync(string login, CancellationToken ct = default);
|
||||
|
||||
Task<UserProfileRow?> GetProfileAsync(string login, string domain, CancellationToken ct = default);
|
||||
Task<string?> GetRoleNameAsync(string roleCode, CancellationToken ct = default);
|
||||
Task<UserHierarchyRow?> GetHierarchyAsync(long userDbId, CancellationToken ct = default);
|
||||
Task<LocationRow?> GetLocationAsync(long locationId, string? domain, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Application.cfc onRequestStart: still active, same role.</summary>
|
||||
Task<bool> IsActiveWithRoleAsync(string login, string roleCode, CancellationToken ct = default);
|
||||
|
||||
Task<int> UpdatePasswordAsync(string login, string domain, string newPassword, string updatedBy, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<string>> GetLocationIpsAsync(string locationId, CancellationToken ct = default);
|
||||
/// <summary>LOCATIONS_IPS.LOCATION_ID that owns this IP, or null.</summary>
|
||||
Task<string?> GetLocationForIpAsync(string ip, CancellationToken ct = default);
|
||||
Task InsertInvalidAccessLogAsync(InvalidAccessEntry entry, CancellationToken ct = default);
|
||||
|
||||
/// <summary>logs.addLog: LOGS row (1 = sign in, 2 = sign out, 35 = SSO).</summary>
|
||||
Task InsertLogAsync(AuditLogEntry entry, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace NTP.Application.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// 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";
|
||||
/// <see cref="Sha1Base64"/> 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.
|
||||
/// </summary>
|
||||
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()
|
||||
}
|
||||
|
||||
/// <summary>UNVERIFIED guess of EncryptPwd.doEncryption (see class remarks).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Stored-password values that count as a match for this login (legacy "password in (...)").</summary>
|
||||
public static IReadOnlyList<string> Candidates(string domain, string login, string password) =>
|
||||
IsAseza(domain)
|
||||
? [Sha1Base64(password), Sha1Hex(login, password)]
|
||||
: [Sha1Hex(login, password)];
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
using System.Reflection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace NTP.Application.Common;
|
||||
|
||||
public static class ConventionRegistration
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
namespace NTP.Application.Common;
|
||||
|
||||
public sealed class NotFoundException(string entity, object key)
|
||||
: Exception($"{entity} '{key}' was not found.");
|
||||
|
||||
/// <summary>Raised when an UPDATE/DELETE affects 0 rows because ROW_VERSION changed.</summary>
|
||||
public sealed class ConcurrencyException(string entity, object key)
|
||||
: Exception($"{entity} '{key}' was modified by another user. Reload and retry.");
|
||||
|
||||
/// <summary>
|
||||
/// A business-rule violation ported from legacy code (HTTP 422). <c>message</c> is the user-facing text
|
||||
/// (keep the legacy Arabic wording); <c>code</c> is a stable machine-readable code returned to the client
|
||||
/// as the ProblemDetails extension "code".
|
||||
/// </summary>
|
||||
public class BusinessException(string code, string message) : Exception(message)
|
||||
{
|
||||
public string Code { get; } = code;
|
||||
}
|
||||
|
||||
/// <summary>Credentials / account state rejected (HTTP 401). Same shape as <see cref="BusinessException"/>.</summary>
|
||||
public sealed class AuthenticationFailedException(string code, string message) : BusinessException(code, message);
|
||||
|
||||
/// <summary>Authenticated but the role/rules do not allow the action (HTTP 403).</summary>
|
||||
public sealed class ForbiddenException(string code, string message) : BusinessException(code, message);
|
||||
|
|
@ -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
|
||||
};
|
||||
|
||||
/// <summary>Exclusive lower ROWNUM bound for the Oracle 11g paging pattern.</summary>
|
||||
public int MinRow => (SafePage - 1) * SafePageSize;
|
||||
|
||||
/// <summary>Inclusive upper ROWNUM bound for the Oracle 11g paging pattern.</summary>
|
||||
public int MaxRow => SafePage * SafePageSize;
|
||||
}
|
||||
|
||||
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int Page, int PageSize, long TotalCount)
|
||||
{
|
||||
public int TotalPages => PageSize == 0 ? 0 : (int)Math.Ceiling(TotalCount / (double)PageSize);
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
using FluentValidation;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
/// <summary>
|
||||
/// Convention based: *Service classes are registered against I*Service (scoped) and all
|
||||
/// FluentValidation validators are discovered. Do NOT add per-slice lines here.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddApplication(this IServiceCollection services)
|
||||
{
|
||||
var assembly = typeof(DependencyInjection).Assembly;
|
||||
services.AddValidatorsFromAssembly(assembly, includeInternalTypes: true);
|
||||
services.AddConventionalServices(assembly);
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
|
@ -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<BillingPermitDto> GetPermitAsync(long pn, long? scac, CancellationToken ct);
|
||||
Task<OrdersResult> AddAsync(AddBillingRequest request, CancellationToken ct);
|
||||
Task<PagedResult<BillingDto>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of Invoice.cfc getBillingInfo / addBillingInfo / getBillingGrid (BillingScreen.cfm, BillingGrid.cfm).</summary>
|
||||
public sealed class BillingService(
|
||||
IBillingRepository repository,
|
||||
IUnitOfWork unitOfWork,
|
||||
IValidator<AddBillingRequest> validator) : IBillingService
|
||||
{
|
||||
private static string? Date(DateTime? d) => d?.ToString("yyyy-MM-dd");
|
||||
|
||||
public async Task<BillingPermitDto> 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<OrdersResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Legacy returned an empty grid when no filter was supplied.</summary>
|
||||
public async Task<PagedResult<BillingDto>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
if (!query.HasFilter) return new PagedResult<BillingDto>([], 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<BillingDto>(items, r.Page, r.PageSize, r.TotalCount);
|
||||
}
|
||||
}
|
||||
|
||||
public interface IInvoiceService
|
||||
{
|
||||
Task<PagedResult<InvoiceDto>> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of Invoice.cfc getInvoiceGrid (InvoiceGrid.cfm).</summary>
|
||||
public sealed class InvoiceService(IInvoiceRepository repository) : IInvoiceService
|
||||
{
|
||||
public async Task<PagedResult<InvoiceDto>> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct)
|
||||
{
|
||||
// Legacy returned an empty grid when no invoice number was given.
|
||||
if (!invoiceNumber.HasValue) return new PagedResult<InvoiceDto>([], 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<InvoiceDto>(items, r.Page, r.PageSize, r.TotalCount);
|
||||
}
|
||||
}
|
||||
|
|
@ -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<TenderOrderReportDto> GetTenderOrderReportAsync(DateTime orderDate, CancellationToken ct);
|
||||
Task<ExportFile> ExportTenderOrderReportAsync(DateTime orderDate, string format, CancellationToken ct);
|
||||
|
||||
Task<FinancialBillingPage> GetFinancialBillingAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct);
|
||||
Task<ExportFile> ExportFinancialBillingAsync(long scac, long invoiceNumber, string format, CancellationToken ct);
|
||||
Task<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<TenderOrderReportDto> 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<ExportFile> 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<object?>)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<object?>)new object?[]
|
||||
{ x.Destination, x.Individuals, x.IndividualsPercent + "%", x.Companies, x.CompaniesPercent + "%", x.Total }).ToList(),
|
||||
[L("المجموع", "Total"), r.TotalIndividuals, null, r.TotalCompanies, null, r.TotalIndividuals + r.TotalCompanies]);
|
||||
|
||||
return Build([t1, t2], format, $"ordersReport_{r.OrderDate}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ financial billing
|
||||
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<FinancialBillingRow> 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<FinancialBillingPage> 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<ExportFile> 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<string>
|
||||
{
|
||||
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<object?>)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<object?>? 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<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct) =>
|
||||
repository.GetInvoiceNumbersAsync(scac, ct);
|
||||
|
||||
// ------------------------------------------------------------------ helpers
|
||||
private ExportFile Build(IReadOnlyList<ExportTable> 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");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,254 @@
|
|||
namespace NTP.Application.Grains.Orders;
|
||||
|
||||
/// <summary>Envelope for write operations: <c>message</c> is the legacy Arabic success text (toasted by the client).</summary>
|
||||
public sealed record OrdersResult(string Message, long? Id = null);
|
||||
|
||||
public sealed record LookupOptionDto(long Id, string? Name);
|
||||
|
||||
/// <summary>NTP_TENDERS_COMPANIES (ACTIVE) row: Label = "scac-company name" (legacy getCompanies.companycode).</summary>
|
||||
public sealed record CompanyOptionDto(long Scac, string? Label);
|
||||
|
||||
// ---------------------------------------------------------------- tender orders
|
||||
public sealed record TenderOrderQuery(DateTime? OrderDate);
|
||||
|
||||
/// <summary>Raw row of the legacy getTenderOrders query.</summary>
|
||||
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
|
||||
/// <summary>Result of the legacy getBillingInfo query (events-based weights for a CLOSEd permit).</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>Billing screen prefill (page JS getAllInformation + price table).</summary>
|
||||
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<long> LocationIds);
|
||||
public sealed record SaveCompanyDestinationsRequest(IReadOnlyList<long> 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<TenderTypeSummaryDto> ByType,
|
||||
decimal TypeTotal,
|
||||
IReadOnlyList<TenderDestinationSummaryDto> ByDestination,
|
||||
decimal TotalIndividuals,
|
||||
decimal TotalCompanies);
|
||||
|
||||
/// <summary>Row of view/table billing1 (GNB datasource in legacy) used by FinancialBilling*.cfm.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Same JSON shape as PagedResult plus totals over the whole invoice.</summary>
|
||||
public sealed record FinancialBillingPage(
|
||||
IReadOnlyList<FinancialBillingDto> Items, int Page, int PageSize, long TotalCount, FinancialBillingTotals Totals);
|
||||
|
||||
public sealed record ExportFile(byte[] Content, string ContentType, string FileName);
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
using NTP.Application.Common;
|
||||
using NTP.Domain.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Grains.Orders;
|
||||
|
||||
public interface ITenderOrderRepository
|
||||
{
|
||||
/// <summary>Legacy getTenderOrders query (non-deleted orders, active EN/EX GN locations), newest first.</summary>
|
||||
Task<PagedResult<TenderOrderRow>> SearchAsync(DateTime? orderDate, PageRequest page, CancellationToken ct = default);
|
||||
|
||||
Task<long> InsertAsync(NewTenderOrder order, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Status and date of an order (null when the id does not exist).</summary>
|
||||
Task<(string? StatusCode, DateTime OrderDate)?> GetHeaderAsync(long id, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Permits with SCRN = order id in shipment status REQST/PLND (orders already distributed).</summary>
|
||||
Task<bool> 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
|
||||
{
|
||||
/// <summary>CARGOTYPE where DOMAIN='GN'.</summary>
|
||||
Task<IReadOnlyList<LookupOptionDto>> GetCargoTypesAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>LOCATIONS where DOMAIN='GN', STATUS=1 and TYPE = EN (loading) or EX (destination).</summary>
|
||||
Task<IReadOnlyList<LookupOptionDto>> GetLocationsAsync(string type, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Invoice.cfc getLocations: GN exit locations with AREA IS NULL and STATUS=1.</summary>
|
||||
Task<IReadOnlyList<LookupOptionDto>> GetBillingDestinationsAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>register.getDistination: GN exit locations of GN_TYPE 'PCKD', ordered by SORTORDER.</summary>
|
||||
Task<IReadOnlyList<LookupOptionDto>> GetPackedDestinationsAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>NTP_TENDERS_COMPANIES with STATUSCODE='ACTIVE' (grains.cfc getCompanies).</summary>
|
||||
Task<IReadOnlyList<CompanyOptionDto>> GetCompaniesAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IQuotaRepository
|
||||
{
|
||||
/// <summary>All GN DESTINATIONS left-joined with their active DESTINATION_QUOTA row of the date.</summary>
|
||||
Task<PagedResult<QuotaRow>> GetListAsync(DateTime date, PageRequest page, CancellationToken ct = default);
|
||||
|
||||
Task<bool> DestinationExistsAsync(long destinationId, CancellationToken ct = default);
|
||||
|
||||
Task<ActiveQuota?> 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<PermitBillingInfo?> GetPermitBillingInfoAsync(long pn, CancellationToken ct = default);
|
||||
Task<WageRate?> GetWageRateAsync(long destination, DateTime loadDate, CancellationToken ct = default);
|
||||
Task<FineRate?> GetFineRateAsync(DateTime loadDate, CancellationToken ct = default);
|
||||
Task<long> InsertAsync(NewGrainsBilling billing, CancellationToken ct = default);
|
||||
Task<PagedResult<BillingRow>> SearchAsync(BillingQuery query, PageRequest page, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IInvoiceRepository
|
||||
{
|
||||
Task<PagedResult<InvoiceRow>> SearchAsync(long? invoiceNumber, PageRequest page, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IGrainsWeightRepository
|
||||
{
|
||||
/// <summary>permits by PN in status CLOSE/RESD/ACTRL, company 327, domain GN (permitAutoComplete).</summary>
|
||||
Task<PermitWeightsRow?> GetPermitAsync(long pn, CancellationToken ct = default);
|
||||
|
||||
Task<SavedWeightsRow?> 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<IReadOnlyList<long>> GetLocationIdsAsync(long scac, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Deletes the company's rows whose LOCATIONID is in <paramref name="scopeLocationIds"/> and inserts the new ones.</summary>
|
||||
Task ReplaceAsync(long scac, IReadOnlyCollection<long> scopeLocationIds, IReadOnlyCollection<long> newLocationIds,
|
||||
string userId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IOrderReportRepository
|
||||
{
|
||||
Task<IReadOnlyList<TenderTypeTotalRow>> GetTenderTypeTotalsAsync(DateTime orderDate, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<TenderDestinationTotalRow>> GetTenderDestinationTotalsAsync(DateTime orderDate, CancellationToken ct = default);
|
||||
|
||||
Task<PagedResult<FinancialBillingRow>> GetFinancialBillingPageAsync(long scac, long invoiceNumber, PageRequest page, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<FinancialBillingRow>> GetFinancialBillingAsync(long scac, long invoiceNumber, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Distinct invoice numbers already present in GRAINS_BILLING for a company (newest first).</summary>
|
||||
Task<IReadOnlyList<long>> GetInvoiceNumbersAsync(long scac, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
using NTP.Application.Common;
|
||||
using NTP.Domain.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Grains.Orders;
|
||||
|
||||
/// <summary>Stable error codes + legacy Arabic messages for the orders slice.</summary>
|
||||
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 = "تمت العملية بنجاح";
|
||||
}
|
||||
|
||||
/// <summary>Pure business rules of tender orders (ported from createNewTenderOrder.cfm / tenderOrder.cfc).</summary>
|
||||
public static class TenderOrderRules
|
||||
{
|
||||
/// <summary>Legacy createTenderOrder: packed cargo => PCKD; tipper destinations or the tipper tick => BULK_GALLAB; else BULK.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Order date dropdown offered today .. today + 4 days.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>The type (individuals/companies) is mandatory except for packed cargo.</summary>
|
||||
public static bool IsTypeRequired(long cargoTypeId) => cargoTypeId != GrainsOrderConstants.PackedCargoTypeId;
|
||||
|
||||
public static bool IsValidType(string? type) =>
|
||||
type is TenderOrderType.Company or TenderOrderType.Individuals;
|
||||
|
||||
/// <summary>Legacy showed the delete icon only when DateCompare(orderDate, now()) > 0, i.e. strictly after today.</summary>
|
||||
public static bool CanDelete(DateTime orderDate, DateTime today) => orderDate.Date > today.Date;
|
||||
|
||||
/// <summary>Empty type means "everyone" in the legacy grid.</summary>
|
||||
public static string? NormalizeType(string? type) =>
|
||||
string.IsNullOrWhiteSpace(type) ? null : type.Trim().ToUpperInvariant();
|
||||
}
|
||||
|
||||
public static class QuotaRules
|
||||
{
|
||||
/// <summary>Legacy editQuota silently ignored a new quota lower than the used quota.</summary>
|
||||
public static bool CanSetQuota(int newQuota, int doneQuota) => newQuota - doneQuota >= 0;
|
||||
}
|
||||
|
||||
/// <summary>Static price table of legacy Invoice.cfc getPrices (destination ids 215/220/225, cargo ids 38-41).</summary>
|
||||
public static class BillingPrices
|
||||
{
|
||||
private static readonly IReadOnlyDictionary<long, decimal> Table = new Dictionary<long, decimal>
|
||||
{
|
||||
[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;
|
||||
}
|
||||
|
||||
/// <summary>Port of the wage/fine maths of legacy Invoice.cfc addBillingInfo.</summary>
|
||||
public static class BillingCalculator
|
||||
{
|
||||
private static decimal Round3(decimal v) => Math.Round(v, 3, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <summary>Net weight: gross minus tare.</summary>
|
||||
public static decimal NetWeight(decimal gross, decimal tare) => gross - tare;
|
||||
|
||||
/// <summary>round(wage * LNW / 1000, 3).</summary>
|
||||
public static decimal Wage(decimal wagePerTon, decimal lnw) => Round3(wagePerTon * lnw / 1000m);
|
||||
|
||||
/// <summary>
|
||||
/// CASE WHEN (LNW - DNW) > allowance * LNW THEN round(((LNW - DNW) - allowance * LNW) * fine / 1000, 3) ELSE 0 END.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Page JS checkDate: discharge date must not be before load date.</summary>
|
||||
public static bool IsDischargeAfterLoad(DateTime load, DateTime discharge) => discharge.Date >= load.Date;
|
||||
|
||||
/// <summary>Page JS checkNumber: sent weight between 0 and 50000.</summary>
|
||||
public static bool IsSentWeightInRange(decimal lnw) => lnw >= 0 && lnw <= 50000;
|
||||
}
|
||||
|
||||
public static class GrainsWeightRules
|
||||
{
|
||||
/// <summary>The page masks weights as 99999 and legacy rejected anything shorter than 5 characters.</summary>
|
||||
public static bool IsValidWeight(string? w) =>
|
||||
w is { Length: 5 } && w.All(char.IsAsciiDigit);
|
||||
|
||||
/// <summary>Legacy EVENTS.REMARKS text of ADD_WEIGHTS.</summary>
|
||||
public static string EventRemarks(string gross, string empty) =>
|
||||
$"الوزن القائم: {gross} الوزن الفارغ: {empty}";
|
||||
}
|
||||
|
||||
public static class ReportMath
|
||||
{
|
||||
/// <summary>Percentage with 1 decimal (legacy NumberFormat '__._').</summary>
|
||||
public static decimal Percent1(decimal part, decimal whole) =>
|
||||
whole == 0 ? 0m : Math.Round(part * 100m / whole, 1, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <summary>Percentage with 2 decimals (legacy SQL round(x*100, 2)).</summary>
|
||||
public static decimal Percent2(decimal part, decimal whole) =>
|
||||
whole == 0 ? 0m : Math.Round(part * 100m / whole, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
using FluentValidation;
|
||||
using NTP.Domain.Grains.Orders;
|
||||
|
||||
namespace NTP.Application.Grains.Orders;
|
||||
|
||||
public sealed class CreateTenderOrderValidator : AbstractValidator<CreateTenderOrderRequest>
|
||||
{
|
||||
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<SetQuotaRequest>
|
||||
{
|
||||
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<AddBillingRequest>
|
||||
{
|
||||
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<SaveWeightsRequest>
|
||||
{
|
||||
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<SaveCompanyDestinationsRequest>
|
||||
{
|
||||
public SaveCompanyDestinationsValidator()
|
||||
{
|
||||
RuleFor(x => x.LocationIds).NotNull();
|
||||
RuleForEach(x => x.LocationIds).GreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
using FluentValidation;
|
||||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Grains.Orders;
|
||||
|
||||
public interface IQuotaService
|
||||
{
|
||||
Task<PagedResult<QuotaDto>> GetListAsync(DateTime date, PageRequest page, CancellationToken ct);
|
||||
Task<OrdersResult> SetQuotaAsync(SetQuotaRequest request, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of grains.cfc getQuotaList / editQuota (quotaGrid.cfm).</summary>
|
||||
public sealed class QuotaService(
|
||||
IQuotaRepository repository,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user,
|
||||
IValidator<SetQuotaRequest> validator) : IQuotaService
|
||||
{
|
||||
public async Task<PagedResult<QuotaDto>> 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<QuotaDto>(items, result.Page, result.PageSize, result.TotalCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public async Task<OrdersResult> 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,172 @@
|
|||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Security;
|
||||
using System.Text;
|
||||
|
||||
namespace NTP.Application.Grains.Orders;
|
||||
|
||||
/// <summary>A titled block of a report: optional title lines, a header row, data rows and an optional totals row.</summary>
|
||||
public sealed record ExportTable(
|
||||
IReadOnlyList<string> TitleLines,
|
||||
IReadOnlyList<string> Headers,
|
||||
IReadOnlyList<IReadOnlyList<object?>> Rows,
|
||||
IReadOnlyList<object?>? TotalsRow = null);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<ExportTable> 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;
|
||||
}
|
||||
|
||||
/// <summary>RFC 4180 quoting; also neutralises spreadsheet formula injection (leading = + - @).</summary>
|
||||
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<ExportTable> tables, bool rightToLeft)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true))
|
||||
{
|
||||
Add(zip, "[Content_Types].xml",
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>
|
||||
""");
|
||||
Add(zip, "_rels/.rels",
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>
|
||||
""");
|
||||
Add(zip, "xl/workbook.xml",
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Report" sheetId="1" r:id="rId1"/></sheets></workbook>
|
||||
""");
|
||||
Add(zip, "xl/_rels/workbook.xml.rels",
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>
|
||||
""");
|
||||
Add(zip, "xl/styles.xml",
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs></styleSheet>
|
||||
""");
|
||||
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<ExportTable> tables, bool rtl)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
|
||||
sb.Append("<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
|
||||
sb.Append("<sheetViews><sheetView workbookViewId=\"0\"").Append(rtl ? " rightToLeft=\"1\"" : "").Append("/></sheetViews>");
|
||||
sb.Append("<sheetData>");
|
||||
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<object?>().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("</sheetData></worksheet>");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static void Row(StringBuilder sb, int r, IReadOnlyList<object?> cells, bool bold)
|
||||
{
|
||||
sb.Append("<row r=\"").Append(r).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("<c r=\"").Append(refName).Append('"').Append(style).Append("><v>")
|
||||
.Append(Convert.ToString(v, CultureInfo.InvariantCulture)).Append("</v></c>");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append("<c r=\"").Append(refName).Append('"').Append(style).Append(" t=\"inlineStr\"><is><t xml:space=\"preserve\">")
|
||||
.Append(Escape(FormatCell(v))).Append("</t></is></c>");
|
||||
}
|
||||
}
|
||||
sb.Append("</row>");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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<PagedResult<TenderOrderDto>> SearchAsync(TenderOrderQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<OrdersResult> CreateAsync(CreateTenderOrderRequest request, CancellationToken ct);
|
||||
Task<OrdersResult> DeleteAsync(long id, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of tenderOrder.cfc (getTenderOrders, createTenderOrder, deleteTenderOrder).</summary>
|
||||
public sealed class TenderOrderService(
|
||||
ITenderOrderRepository repository,
|
||||
IOrderLookupRepository lookups,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user,
|
||||
IValidator<CreateTenderOrderRequest> createValidator) : ITenderOrderService
|
||||
{
|
||||
public async Task<PagedResult<TenderOrderDto>> 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<TenderOrderDto>(items, result.Page, result.PageSize, result.TotalCount);
|
||||
}
|
||||
|
||||
public async Task<OrdersResult> 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<OrdersResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "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.
|
||||
/// </summary>
|
||||
public interface IMobilePublishService
|
||||
{
|
||||
Task<OrdersResult> SetVisibilityAsync(long orderId, bool show, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class MobilePublishService(ITenderOrderRepository repository, ICurrentUser user) : IMobilePublishService
|
||||
{
|
||||
public async Task<OrdersResult> 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<IReadOnlyList<LookupOptionDto>> CargoTypesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<LookupOptionDto>> LoadingLocationsAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<LookupOptionDto>> DestinationsAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<LookupOptionDto>> BillingDestinationsAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<LookupOptionDto>> PackedDestinationsAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<CompanyOptionDto>> CompaniesAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class OrderLookupService(IOrderLookupRepository repository) : IOrderLookupService
|
||||
{
|
||||
public Task<IReadOnlyList<LookupOptionDto>> CargoTypesAsync(CancellationToken ct) => repository.GetCargoTypesAsync(ct);
|
||||
public Task<IReadOnlyList<LookupOptionDto>> LoadingLocationsAsync(CancellationToken ct) => repository.GetLocationsAsync("EN", ct);
|
||||
public Task<IReadOnlyList<LookupOptionDto>> DestinationsAsync(CancellationToken ct) => repository.GetLocationsAsync("EX", ct);
|
||||
public Task<IReadOnlyList<LookupOptionDto>> BillingDestinationsAsync(CancellationToken ct) => repository.GetBillingDestinationsAsync(ct);
|
||||
public Task<IReadOnlyList<LookupOptionDto>> PackedDestinationsAsync(CancellationToken ct) => repository.GetPackedDestinationsAsync(ct);
|
||||
public Task<IReadOnlyList<CompanyOptionDto>> CompaniesAsync(CancellationToken ct) => repository.GetCompaniesAsync(ct);
|
||||
}
|
||||
|
|
@ -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<PermitWeightsDto> GetAsync(long pn, CancellationToken ct);
|
||||
Task<OrdersResult> SaveAsync(SaveWeightsRequest request, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of grains.cfc permitAutoComplete / saveGrainsWeights (addGrainsWeights.cfm).</summary>
|
||||
public sealed class GrainsWeightService(
|
||||
IGrainsWeightRepository repository,
|
||||
IEventLogger events,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user,
|
||||
IValidator<SaveWeightsRequest> validator) : IGrainsWeightService
|
||||
{
|
||||
public async Task<PermitWeightsDto> 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<OrdersResult> 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<string, object?> { ["REMARKS"] = GrainsWeightRules.EventRemarks(request.GrossWeight, request.EmptyWeight) }), token);
|
||||
|
||||
return new OrdersResult(OrdersErrors.Success, permit.Id);
|
||||
}, ct);
|
||||
}
|
||||
}
|
||||
|
||||
public interface ICompanyDestinationService
|
||||
{
|
||||
Task<CompanyDestinationsDto> GetAsync(long scac, CancellationToken ct);
|
||||
Task<OrdersResult> SaveAsync(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of grains.cfc getCompDest / saveCompDest (compdest.cfm) over GRAINS_COMPANIES_LOCATION.</summary>
|
||||
public sealed class CompanyDestinationService(
|
||||
ICompanyDestinationRepository repository,
|
||||
IOrderLookupRepository lookups,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user,
|
||||
IValidator<SaveCompanyDestinationsRequest> validator) : ICompanyDestinationService
|
||||
{
|
||||
public async Task<CompanyDestinationsDto> GetAsync(long scac, CancellationToken ct) =>
|
||||
new(scac, await repository.GetLocationIdsAsync(scac, ct));
|
||||
|
||||
public async Task<OrdersResult> 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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<IReadOnlyList<LookupItem>> GetGrainsLocationsAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LookupItem>> GetExitLocationsAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LookupItem>> GetPermitFilterDestinationsAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LookupItem>> GetCargoTypesAsync(CancellationToken ct = default);
|
||||
Task<LocationGroupsDto> GetLocationGroupsAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<CompanyOption>> GetCompaniesAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<long>> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> SaveCompanyDestinationsAsync(long scac, SaveCompanyDestinationsRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> AssignByPnAsync(AssignByPnRequest request, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<string>> GetOrderDatesAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<AllowedDestinationDto>> GetAllowedDestinationsAsync(string pn, string orderDate, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<AllowedCargoDto>> GetAllowedCargoAsync(long permitId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<OrderChoiceDto>> GetOrdersForPermitAsync(string pn, string orderDate, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> ManualInputAsync(ManualInputRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>assignDestination: picks the best open tender order for the truck. Business outcomes are returned, not thrown.</summary>
|
||||
Task<AssignDestinationResult> AssignDestinationAsync(string tn, long locationId, string userId, CancellationToken ct = default);
|
||||
Task<DestinationSearchResult> SearchDestinationAsync(string tn, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<OrderActivationRow>> GetActivationAsync(CancellationToken ct = default);
|
||||
Task<PermitOperationResult> ActivateOrdersAsync(ActivateOrdersRequest request, CancellationToken ct = default);
|
||||
Task<int> 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<IReadOnlyList<LookupItem>> GetGrainsLocationsAsync(CancellationToken ct = default) => repo.GetGrainsLocationsAsync(ct);
|
||||
public Task<IReadOnlyList<LookupItem>> GetExitLocationsAsync(CancellationToken ct = default) => repo.GetLocationsByTypeAsync("EX", ct);
|
||||
public Task<IReadOnlyList<LookupItem>> GetPermitFilterDestinationsAsync(CancellationToken ct = default) => repo.GetPermitFilterDestinationsAsync(ct);
|
||||
public Task<IReadOnlyList<LookupItem>> GetCargoTypesAsync(CancellationToken ct = default) => repo.GetCargoTypesAsync(ct);
|
||||
public Task<LocationGroupsDto> GetLocationGroupsAsync(CancellationToken ct = default) => repo.GetLocationGroupsAsync(ct);
|
||||
public Task<IReadOnlyList<CompanyOption>> GetCompaniesAsync(CancellationToken ct = default) => repo.GetCompaniesAsync(ct);
|
||||
public Task<IReadOnlyList<long>> GetCompanyDestinationsAsync(long scac, CancellationToken ct = default) => repo.GetCompanyLocationsAsync(scac, ct);
|
||||
|
||||
public async Task<PermitOperationResult> SaveCompanyDestinationsAsync(long scac, SaveCompanyDestinationsRequest r, CancellationToken ct = default)
|
||||
{
|
||||
if (scac == options.BadiyaScac)
|
||||
throw new BusinessException("COMPANY_NOT_ALLOWED", "لا يمكن تحديد وجهات للأفراد من هذه الشاشة");
|
||||
await uow.ExecuteInTransactionAsync(async token =>
|
||||
{
|
||||
await repo.ReplaceCompanyLocationsAsync(scac, r.Destinations.Distinct().ToList(), user.UserId, token);
|
||||
return true;
|
||||
}, ct);
|
||||
return PermitOperationResult.Ok(PermitOperationResult.DefaultOk);
|
||||
}
|
||||
|
||||
public async Task<PermitOperationResult> AssignByPnAsync(AssignByPnRequest r, CancellationToken ct = default)
|
||||
{
|
||||
new AssignByPnValidator().ValidateAndThrow(r);
|
||||
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<IReadOnlyList<string>> GetOrderDatesAsync(CancellationToken ct = default) =>
|
||||
(await repo.GetOrderDatesAsync(ct)).Select(d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<AllowedDestinationDto>> 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<IReadOnlyList<AllowedCargoDto>> 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<IReadOnlyList<OrderChoiceDto>> 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<PermitOperationResult> 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<AssignDestinationResult> 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<long> 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);
|
||||
}
|
||||
|
||||
/// <summary>setDestToPermit: writes origin/destination/cargo/order on the permit and the ASSIGNDEST (or MANASGNDST) event.</summary>
|
||||
private async Task<string> 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<DestinationSearchResult> 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<IReadOnlyList<OrderActivationRow>> GetActivationAsync(CancellationToken ct = default) =>
|
||||
repo.GetActivationRowsAsync(Window(), ct);
|
||||
|
||||
public async Task<PermitOperationResult> 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<int> 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]
|
||||
};
|
||||
}
|
||||
|
|
@ -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<PermitOperationResult> DistributeAsync(DistributeRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> ReleaseAsync(ReleasePermitRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> ProcessOpenPermitAsync(OpenPermitRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> ProcessOpenPermitWithDestinationAsync(OpenPermitWithDestinationRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> ProcessCompanyOpenPermitsAsync(CompanyOpenPermitsRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> DistributeSingleTruckAsync(string tn, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<DistributionSummaryRow>> GetSummaryAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<DistributionPivotRow>> GetPivotAsync(CancellationToken ct = default);
|
||||
Task<TruckDistributionDto> SearchTruckAsync(string tn, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<BlacklistedDistributionDto>> GetBlacklistedAsync(string tn, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> CheckTripsAsync(CheckTripsRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> RevokeAllRequestedAsync(long scrnBelow, CancellationToken ct = default);
|
||||
|
||||
/// <summary>jobs/checkForGabanEvents.cfm: permits whose loading window passed without an ASSIGNDEST go back to OPEN.</summary>
|
||||
Task<int> RevertUnloadedPermitsAsync(string actor, CancellationToken ct = default);
|
||||
|
||||
// auto call
|
||||
Task<PermitOperationResult> SendAutoCallFileAsync(AutoCallRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> TriggerIvrAsync(CancellationToken ct = default);
|
||||
bool IsValidDialerApiKey(string? key);
|
||||
Task<AutoCallCallbackResult> HandleDialerCallbackAsync(AutoCallResponse response, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Per-user position in the company queue between two "distribute companies" runs (legacy session.QueueStart).</summary>
|
||||
internal static class DistributionCursor
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, long> Positions = new(StringComparer.OrdinalIgnoreCase);
|
||||
public static long Get(string user) => Positions.GetValueOrDefault(user, 1);
|
||||
public static void Set(string user, long value) => Positions[user] = value;
|
||||
}
|
||||
|
||||
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<PermitOperationResult> 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<IReadOnlyDictionary<string, object?>>();
|
||||
var companyNotes = new Dictionary<string, object?>();
|
||||
|
||||
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<string, object?>
|
||||
{
|
||||
["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<string, object?> { ["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<string, object?> { ["companies"] = companyCounter, ["owners"] = ownerCounter, ["available"] = queueAvailable });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ releasePermit
|
||||
|
||||
public async Task<PermitOperationResult> 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<ReleaseOutcome> 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<PermitOperationResult> 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<PermitOperationResult> 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<string, object?>
|
||||
{
|
||||
["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<string, object?> { ["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<PermitOperationResult> 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<PermitOperationResult> 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<IReadOnlyList<DistributionSummaryRow>> GetSummaryAsync(CancellationToken ct = default) => repo.GetDistributedSummaryAsync(ct);
|
||||
|
||||
public Task<IReadOnlyList<DistributionPivotRow>> GetPivotAsync(CancellationToken ct = default) => repo.GetDistributionPivotAsync(ct);
|
||||
|
||||
public async Task<TruckDistributionDto> 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<long> 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<IReadOnlyList<BlacklistedDistributionDto>> GetBlacklistedAsync(string tn, CancellationToken ct = default) =>
|
||||
repo.GetBlacklistedDistributionsAsync(tn.Trim(), ct);
|
||||
|
||||
public async Task<PermitOperationResult> 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<PermitOperationResult> 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<int> 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<PermitOperationResult> 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<string, object?> { ["rows"] = rows.Count })
|
||||
: PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي");
|
||||
}
|
||||
|
||||
public async Task<PermitOperationResult> TriggerIvrAsync(CancellationToken ct = default) =>
|
||||
await autoCall.TriggerIvrAsync(ct)
|
||||
? PermitOperationResult.Ok(PermitOperationResult.DefaultOk)
|
||||
: PermitOperationResult.Fail("AUTOCALL_UNREACHABLE", "خلل بالاتصال بنظام الاتصال الاّلي");
|
||||
|
||||
/// <summary>writeCallingDriverFile: CSV consumed by the auto dialer.</summary>
|
||||
internal static byte[] BuildCallingFile(IReadOnlyList<AutoCallDriverRow> rows)
|
||||
{
|
||||
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);
|
||||
|
||||
/// <summary>autoCallResponse.cfc autoDail: CONFIRMED -> phone accept, POSTPONED -> phone reject for N days, NO_ANSWER -> postpone one day.</summary>
|
||||
public async Task<AutoCallCallbackResult> HandleDialerCallbackAsync(AutoCallResponse r, CancellationToken ct = default)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
namespace NTP.Application.Grains.Permits;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class GrainsPermitsOptions
|
||||
{
|
||||
public const string SectionName = "Grains:Permits";
|
||||
|
||||
/// <summary>SCAC of the "owners / individuals" pseudo company (legacy application.GN_BadiyaSCAC; hard-coded 327 elsewhere in grains.cfc).</summary>
|
||||
public long BadiyaScac { get; set; } = 327;
|
||||
|
||||
/// <summary>Stakeholder id of trucking companies (legacy session.stkid = 62): they only see their own permits.</summary>
|
||||
public long CompanyStakeholderId { get; set; } = 62;
|
||||
|
||||
/// <summary>Operation window of shift 1/2 as [firstHour, lastHour] relative to the order date (legacy grnsOprationShft_1/2). UNVERIFIED defaults.</summary>
|
||||
public int[] OperationShift1 { get; set; } = [6, 18];
|
||||
public int[] OperationShift2 { get; set; } = [18, 30];
|
||||
|
||||
/// <summary>Distribution shifts [start, end] used to compute blacklist expiry (legacy grnsdtrbutnshft_N). UNVERIFIED defaults.</summary>
|
||||
public int[] DistributionShift1 { get; set; } = [6, 18];
|
||||
public int[] DistributionShift2 { get; set; } = [18, 30];
|
||||
public int[] DistributionShift3 { get; set; } = [30, 42];
|
||||
|
||||
/// <summary>Statuses a truck/trailer/driver registration must have to be usable on a permit (legacy GN_ALLOWEDSTATUSES). UNVERIFIED.</summary>
|
||||
public string[] AllowedStatuses { get; set; } = ["OPEN", "ACCPT"];
|
||||
|
||||
/// <summary>Initial value of the in-memory "absence" feature flag (legacy application.GNABSENCEFEATURE). UNVERIFIED.</summary>
|
||||
public bool AbsenceFeatureEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>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).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Outbound TCS (petroleum permit web service, legacy application.PetWS) integration.</summary>
|
||||
public sealed class TcsOptions
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>Endpoint of CreatePermitWS (legacy application.PetWS, ApplicationVariables.xml).</summary>
|
||||
public string PermitServiceUrl { get; set; } = "http://192.168.1.90:8080/FDfolioWS/services/CreatePermitWS";
|
||||
|
||||
public int TimeoutSeconds { get; set; } = 60;
|
||||
}
|
||||
|
||||
/// <summary>Outbound IVR / auto-dialer integration (GrainsFactoryWeb.autoCallService / autoCallService2, autoCallResponse.cfc).</summary>
|
||||
public sealed class AutoCallOptions
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>Legacy application.autoCallerIP: receives {"TYPE":"TEST","FILE":"<base64 csv>"}.</summary>
|
||||
public string SendUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Legacy IVR web service (http://aqtcs.nafith.net/IVR/callivr.cfc) - callAPI.</summary>
|
||||
public string IvrUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Expected X-Api-Key of the dialer's callback (legacy application.nafethApiKey). Empty = callback disabled.</summary>
|
||||
public string ApiKey { get; set; } = string.Empty;
|
||||
|
||||
public int TimeoutSeconds { get; set; } = 30;
|
||||
}
|
||||
|
||||
/// <summary>Mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage).</summary>
|
||||
public sealed class NotificationOptions
|
||||
{
|
||||
public bool Enabled { get; set; }
|
||||
public string Url { get; set; } = string.Empty;
|
||||
public int TimeoutSeconds { get; set; } = 15;
|
||||
}
|
||||
|
||||
/// <summary>External weighbridge database (legacy datasource GrainsWeighbridge, table CARGO).</summary>
|
||||
public sealed class WeighbridgeSourceOptions
|
||||
{
|
||||
public string ConnectionString { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Scheduled jobs. Every job is disabled by default; set Enabled=true per job to run it inside the API process.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Supplies the bound "Grains:Permits" settings (implemented in Infrastructure; registered by the *Service naming convention).</summary>
|
||||
public interface IGrainsPermitsSettingsService
|
||||
{
|
||||
GrainsPermitsOptions Value { get; }
|
||||
}
|
||||
|
|
@ -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<LookupItem> Packed { get; set; } = [];
|
||||
public IReadOnlyList<LookupItem> Bulk { get; set; } = [];
|
||||
public IReadOnlyList<LookupItem> BulkGallab { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class CompanyOption
|
||||
{
|
||||
public long Scac { get; set; }
|
||||
public string? CompanyCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Destinations, tender orders and company locations (assignDestination, setDestToPermit, getCompDest, ActivateOrder ...).</summary>
|
||||
public interface IDestinationRepository
|
||||
{
|
||||
// lookups
|
||||
Task<IReadOnlyList<LookupItem>> GetGrainsLocationsAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LookupItem>> GetLocationsByTypeAsync(string type, CancellationToken ct = default);
|
||||
|
||||
/// <summary>GNPermits.cfm destination filter: LOCATIONS domain GN, type EX, ordered by NAME, including inactive ones (old permits still point to them).</summary>
|
||||
Task<IReadOnlyList<LookupItem>> GetPermitFilterDestinationsAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LookupItem>> GetCargoTypesAsync(CancellationToken ct = default);
|
||||
Task<LocationGroupsDto> GetLocationGroupsAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<CompanyOption>> GetCompaniesAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<long>> GetCompanyLocationsAsync(long scac, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LookupItem>> GetCompanyLocationItemsAsync(long scac, CancellationToken ct = default);
|
||||
Task ReplaceCompanyLocationsAsync(long scac, IReadOnlyList<long> locations, string userId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<long>> GetTruckDestinationsAsync(string tn, CancellationToken ct = default);
|
||||
Task<string?> GetLocationNameAsync(long id, CancellationToken ct = default);
|
||||
Task<string?> GetCargoTypeNameAsync(long id, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<DateTime>> GetOrderDatesAsync(CancellationToken ct = default);
|
||||
|
||||
// orders
|
||||
Task<OrderForPermitRow?> GetOrderAsync(long orderId, CancellationToken ct = default);
|
||||
Task<OrderDetailsDto?> GetOrderDetailsAsync(long orderId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>LOCATIONS.NAME (domain GN) of a location id given as text, or null.</summary>
|
||||
Task<string?> GetGrainsLocationNameAsync(string locationId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<AllowedDestinationDto>> GetAllowedDestinationsAsync(string pn, DateTime orderDate, IReadOnlyList<long> allowed,
|
||||
bool companyBranch, bool packed, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<AllowedCargoDto>> GetAllowedCargoAsync(PermitRow permit, long badiyaScac, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<OrderChoiceDto>> GetOrdersForPermitDateAsync(string pn, DateTime orderDate, CancellationToken ct = default);
|
||||
Task<OrderForPermitRow?> GetManualOrderAsync(long orderId, CancellationToken ct = default);
|
||||
|
||||
// assignment
|
||||
Task<IReadOnlyList<TruckPermitForDestination>> GetTruckPermitsForAssignmentAsync(string tn, CancellationToken ct = default);
|
||||
Task<string?> GetLastAsrnAsync(string tn, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<TenderOrderCandidate>> GetTenderOrderCandidatesAsync(string tn, IReadOnlyList<long> locations,
|
||||
long[]? cargoGroup, long? location, ShiftWindow window, CancellationToken ct = default);
|
||||
Task<long> CountAssignedTrucksAsync(long orderId, CancellationToken ct = default);
|
||||
Task SetPermitDestinationAsync(long permitId, long originId, long destinationId, long cargoType, long orderId, string userId,
|
||||
CancellationToken ct = default);
|
||||
Task<bool> 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<IReadOnlyList<OrderActivationRow>> GetActivationRowsAsync(ShiftWindow window, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<CurrentOrderRow>> GetCurrentWindowOrdersAsync(ShiftWindow window, CancellationToken ct = default);
|
||||
Task SetOrdersStatusAsync(IReadOnlyList<long> ids, string status, string userId, CancellationToken ct = default);
|
||||
|
||||
// activateGrainsDestination job
|
||||
Task<int> ActivatePendingCompanyDestinationsAsync(string actor, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -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; }
|
||||
}
|
||||
|
||||
/// <summary>Distribution of OPEN permits to tender orders: grains.cfc distributePackedBulk, releasePermit, procssOpenPermit*, ...</summary>
|
||||
public interface IDistributionRepository
|
||||
{
|
||||
// distributePackedBulk
|
||||
Task<OrderTotalsRow> GetOrderTotalsAsync(string distributionCode, string queueType, bool packed, CancellationToken ct = default);
|
||||
Task<OrderUsedRow?> GetUsedOrdersAsync(string distributionCode, string queueType, bool packed, CancellationToken ct = default);
|
||||
Task PrepareDataAsync(string cargoType, long badiyaScac, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<QueueSharePick>> GetCompanyShareAsync(string code, string? type, bool gallabCompany, long start, long queueAvailable,
|
||||
CancellationToken ct = default);
|
||||
Task<IReadOnlyList<QueuePermitPick>> GetCompanyQueuePermitsAsync(IReadOnlyList<QueueSharePick> 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<OwnerNotificationRow?> GetOwnerDistributionDataAsync(string tn, long badiyaScac, CancellationToken ct = default);
|
||||
|
||||
// releasePermit
|
||||
Task<PermitRow?> GetOpenPermitWithFirmsAsync(string pn, long scac, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<long>> GetAllowedLocationsForReleaseAsync(PermitRow permit, long scac, long badiyaScac, CancellationToken ct = default);
|
||||
Task<NextOrderPick?> GetNextOrderAsync(IReadOnlyList<long> locations, string cargoCode, string? queueType, CancellationToken ct = default);
|
||||
Task 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<PermitRow?> GetFirstOpenPermitByTnAsync(string tn, string? cargoType, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<NextOrderPick>> GetNextOrdersForTruckAsync(string tn, CancellationToken ct = default);
|
||||
Task<bool> IsLocationAllowedForCompanyAsync(long scac, long location, CancellationToken ct = default);
|
||||
Task SetRequestedAsync(long permitId, CancellationToken ct = default);
|
||||
Task<OrderForPermitRow?> GetOrderForManualAsync(long orderId, CancellationToken ct = default);
|
||||
Task<long?> PickQueueIdAsync(long scac, string code, string? type, CancellationToken ct = default);
|
||||
Task SetRequestedManualAsync(long permitId, long orderId, long queueId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<PermitRow>> GetOpenCompanyPermitsAsync(long badiyaScac, CancellationToken ct = default);
|
||||
Task<NextOrderPick?> GetAnyNextOrderAsync(CancellationToken ct = default);
|
||||
|
||||
// grids / inquiries
|
||||
Task<IReadOnlyList<DistributionSummaryRow>> GetDistributedSummaryAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<DistributionPivotRow>> GetDistributionPivotAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<(long Id, string? Status, long? Company, long? Scrn)>> GetTruckPermitStatusesAsync(string tn, CancellationToken ct = default);
|
||||
Task<string?> GetTruckLatestStatusCaptionAsync(string tn, CancellationToken ct = default);
|
||||
Task<long?> GetTruckLatestCompanyAsync(string tn, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<OpenOrderBrief>> GetActiveOrdersInWindowAsync(ShiftWindow window, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<(long Id, string? Name)>> GetLocationNamesAsync(IReadOnlyList<long> ids, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<BlacklistedDistributionDto>> GetBlacklistedDistributionsAsync(string tn, CancellationToken ct = default);
|
||||
Task<long> GetTripCountAsync(string tn, CancellationToken ct = default);
|
||||
|
||||
// admin / maintenance
|
||||
Task<IReadOnlyList<PermitRow>> GetRequestedPermitsBelowOrderAsync(long scrnBelow, long badiyaScac, CancellationToken ct = default);
|
||||
Task ResetPermitToOpenAsync(long permitId, string userId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<GabanPermitRow>> GetUnloadedPermitsAsync(int shiftOneFirstHour, CancellationToken ct = default);
|
||||
Task SetStatusOpenAsync(IReadOnlyList<long> ids, CancellationToken ct = default);
|
||||
|
||||
// auto call
|
||||
Task<IReadOnlyList<AutoCallDriverRow>> GetCallingDriverRowsAsync(AutoCallRequest filter, DateTime? tenderDate, CancellationToken ct = default);
|
||||
Task<long?> GetPermitIdByPnAsync(string pn, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Grains.Permits;
|
||||
|
||||
/// <summary>Criteria after the service has applied the caller's company restriction.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Permits: lists, details, order lifecycle (grains.cfc getGNPermits ... submitOrder, Accept, revoke ...).</summary>
|
||||
public interface IPermitRepository
|
||||
{
|
||||
// ---- lists / detail
|
||||
Task<PagedResult<PermitListItem>> SearchAsync(PermitSearchCriteria c, PageRequest page, CancellationToken ct = default);
|
||||
Task<PagedResult<GatePermitItem>> SearchGateListAsync(GatePermitQuery q, string domain, long? companyCode, bool restrictToCompany,
|
||||
PageRequest page, CancellationToken ct = default);
|
||||
Task<PermitRow?> GetAsync(long id, CancellationToken ct = default);
|
||||
Task<PermitRow?> GetByPnAsync(string pn, CancellationToken ct = default);
|
||||
Task<PermitInfoRow?> GetInfoAsync(long id, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<PermitEventDto>> GetEventsAsync(long permitId, CancellationToken ct = default);
|
||||
|
||||
// ---- truck / trailer / driver lookups (domain GN)
|
||||
Task<TruckInfoRow?> GetTruckInfoAsync(string tn, long? companyCode, CancellationToken ct = default);
|
||||
Task<TruckInfoRow?> GetTrailerInfoAsync(string trn, long? companyCode, CancellationToken ct = default);
|
||||
Task<long?> GetTrailerScacAsync(string trn, CancellationToken ct = default);
|
||||
Task<DriverInfoRow?> GetDriverInfoAsync(string nnpn, CancellationToken ct = default);
|
||||
Task<TruckRegistrationRow?> GetTruckRegistrationAsync(string tn, CancellationToken ct = default);
|
||||
Task<bool> DriverIsRegisteredAsync(string nnpn, CancellationToken ct = default);
|
||||
Task<string?> GetTruckStatusAsync(long scac, string tn, CancellationToken ct = default);
|
||||
Task<string?> GetTrailerStatusAsync(string trn, CancellationToken ct = default);
|
||||
Task<string?> GetDriverStatusAsync(string nnpn, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<OwnershipRow>> GetMotTruckAsync(long scac, string tn, CancellationToken ct = default);
|
||||
Task<ActiveConflictRow?> FindActiveConflictAsync(string column, string value, long excludePermitId, CancellationToken ct = default);
|
||||
Task<PermitOrderRow?> 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<ActiveConflictRow?> FindOpenConflictForReactivationAsync(PermitRow permit, CancellationToken ct = default);
|
||||
Task<PermitRow?> FindClosablePermitAsync(string pn, CancellationToken ct = default);
|
||||
|
||||
// ---- stored weights
|
||||
Task<StoredWeightsDto?> GetStoredWeightsAsync(string pn, long badiyaScac, CancellationToken ct = default);
|
||||
Task<long?> 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);
|
||||
}
|
||||
|
||||
/// <summary>Phone confirmation / rejection data access (addPhoneAcceptEvent / addPhoneRejectEvent / BL_addToBlacklist).</summary>
|
||||
public interface IPhoneEventRepository
|
||||
{
|
||||
Task<bool> HasClosedDistributionAsync(long permitId, long orderId, CancellationToken ct = default);
|
||||
Task CloseDistributionAsync(long permitId, long orderId, string notes, CancellationToken ct = default);
|
||||
Task<string?> GetTruckPhoneAsync(string tn, CancellationToken ct = default);
|
||||
Task<long> 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<double> GetOrderDateDiffDaysAsync(long orderId, CancellationToken ct = default);
|
||||
Task<DistributionLogRow?> 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<bool> HasPhoneEventTodayAsync(long permitId, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -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; }
|
||||
}
|
||||
|
||||
/// <summary>Everything updateGNForm writes onto the QUED permit when the TCS permit is created.</summary>
|
||||
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!;
|
||||
}
|
||||
|
||||
/// <summary>Queue (turns) and TCS permit creation: CreateQueue.cfm, queueGrid.cfm, createPermit.cfm, ws.cfc createPermitRecord.</summary>
|
||||
public interface IQueueRepository
|
||||
{
|
||||
Task<PagedResult<QueueItem>> ListAsync(QueueSearchQuery q, PageRequest page, CancellationToken ct = default);
|
||||
Task<long?> GetActiveTruckScacAsync(string tn, CancellationToken ct = default);
|
||||
Task<bool> HasActivePermitAsync(string tn, string tt, bool includeRequestedPlanned, CancellationToken ct = default);
|
||||
Task<long> NextTrackingSequenceAsync(bool owner, CancellationToken ct = default);
|
||||
Task<long> NextTripCounterAsync(string tt, long badiyaScac, CancellationToken ct = default);
|
||||
Task<long> GetTenderCountAsync(CancellationToken ct = default);
|
||||
Task<long> InsertPermitAsync(string pn, string? tn, long scac, string status, string tt, long? tripCounter, CancellationToken ct = default);
|
||||
Task<string?> GetTrailerNumberAsync(string tn, string[] allowedStatuses, CancellationToken ct = default);
|
||||
|
||||
// fleet turn check (checkTrucks)
|
||||
Task<long> CountFleetAsync(long scac, CancellationToken ct = default);
|
||||
Task<long> CountActiveValidationsAsync(long scac, CancellationToken ct = default);
|
||||
Task<bool> 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<IReadOnlyList<CompanyShareRow>> GetCompanyQueueSharesAsync(string code, long excludeScac, CancellationToken ct = default);
|
||||
Task<long> CountOpenPermitsAsync(long scac, string tt, CancellationToken ct = default);
|
||||
|
||||
// TCS permit
|
||||
Task<DestinationQuotaPick?> PickRandomQuotaDestinationAsync(CancellationToken ct = default);
|
||||
Task<TcsFormDataDto?> GetFormDataAsync(long permitId, string domain, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RoutingTemplateDto>> GetRoutingTemplatesAsync(long origin, long destination, string shipmentMode, string firms,
|
||||
string domain, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LookupItem>> GetOriginAddressesAsync(long routing, string domain, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RoutingTemplateDto>> GetPhRoutesAsync(CancellationToken ct = default);
|
||||
Task<PhRouteRow?> GetPhRouteAsync(long routing, CancellationToken ct = default);
|
||||
Task<string?> GetClearingAgentNameAsync(long can, CancellationToken ct = default);
|
||||
Task<string> GetPetroleumErrorTextAsync(IReadOnlyList<string> codes, CancellationToken ct = default);
|
||||
Task UpdateTcsPermitAsync(long permitId, TcsPermitUpdate u, CancellationToken ct = default);
|
||||
Task<DateTime?> GetPermitCreationDateAsync(long permitId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RoutingLegRow>> 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);
|
||||
}
|
||||
|
|
@ -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; }
|
||||
}
|
||||
|
||||
/// <summary>Weighbridge events and raw weighbridge data (ws.cfc addWeightBridgeEvent, EN/EX_WeightBridge, getWeighbridgeEvents job).</summary>
|
||||
public interface IWeighbridgeRepository
|
||||
{
|
||||
Task<TruckPermitBriefDto?> GetPermitByTruckAndStatusAsync(string tn, string status, CancellationToken ct = default);
|
||||
Task<decimal?> GetLatestLoadingTareAsync(long permitId, CancellationToken ct = default);
|
||||
Task<WeighbridgePermitRow?> 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<string?> GetLocationTypeAsync(long locationId, string domain, CancellationToken ct = default);
|
||||
Task<WaybridgeEventDto?> GetWaybridgeEventAsync(string tn, string? locationType, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LocationTruckCountDto>> GetLocationTruckCountsAsync(CancellationToken ct = default);
|
||||
|
||||
// raw data job
|
||||
Task<IReadOnlyDictionary<long, DateTime?>> GetLastRawTimesAsync(long[] locationIds, CancellationToken ct = default);
|
||||
Task InsertRawRowAsync(ExternalCargoRow row, string normalizedTruckNo, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<WeighbridgeRawRow>> GetUnprocessedRawRowsAsync(bool aqaba, CancellationToken ct = default);
|
||||
Task<RawPermitMatch?> FindPermitForRawAsync(string tn, string[] statuses, CancellationToken ct = default);
|
||||
Task<RawPermitMatch?> 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);
|
||||
}
|
||||
|
|
@ -0,0 +1,618 @@
|
|||
namespace NTP.Application.Grains.Permits;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// Shared result type
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Result of a write operation. <c>Message</c> is the legacy Arabic text; <c>Success=false</c> is a business outcome
|
||||
/// that legacy returned as a normal response (not an exception), e.g. "no destination available".
|
||||
/// </summary>
|
||||
public sealed record PermitOperationResult(bool Success, string Message, string? Code = null, long? PermitId = null,
|
||||
IReadOnlyDictionary<string, object?>? Data = null)
|
||||
{
|
||||
public static PermitOperationResult Ok(string message, long? permitId = null, IReadOnlyDictionary<string, object?>? 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
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>getGNPermits filters (strFilter keys). Dates: creationDate = yyyy-MM-dd, tenderOrder = dd/MM/yyyy.</summary>
|
||||
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; }
|
||||
/// <summary>Calculated by the service: which action buttons the caller may use on this row.</summary>
|
||||
public IReadOnlyList<string> Actions { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>getGNList (permitsGrid.cfm): gate/clearance list.</summary>
|
||||
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<string> Actions { get; set; } = [];
|
||||
public IReadOnlyList<PermitEventDto> 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; }
|
||||
}
|
||||
|
||||
/// <summary>AddToQueue (CreateQueue.cfm): create an OPEN permit record (turn) for a truck.</summary>
|
||||
public sealed record AddToQueueRequest(string Tn, string Tt, bool CheckStatuses = false);
|
||||
|
||||
public sealed record SeedPermitsRequest(IReadOnlyList<SeedPermitItem> Items);
|
||||
|
||||
public sealed record SeedPermitItem(long Scac, string NextStatus, string Tt, int Count);
|
||||
|
||||
/// <summary>createPermit (createPermit.cfm): the TCS "grain permit" form.</summary>
|
||||
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<long> 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<string> 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);
|
||||
|
||||
/// <summary>ws.cfc addWeightBridgeEvent: weighbridge integration reading (EN/EX) at a location.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A row read from the external weighbridge database (table CARGO).</summary>
|
||||
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; }
|
||||
/// <summary>Officer of the receiving weighing (discharge gross), else of the first weighing found; legacy printed qry.doneby.</summary>
|
||||
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<PermitEventDto> 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; }
|
||||
}
|
||||
|
||||
/// <summary>Body of the dialer's callback (autoDail): referenceId = PN, key = CONFIRMED | POSTPONED | NO_ANSWER.</summary>
|
||||
public sealed record AutoCallResponse(string? ReferenceId, string? Key, string? Value);
|
||||
|
||||
public sealed record AutoCallCallbackResult(string Code, string Message);
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
using NTP.Application.Abstractions;
|
||||
|
||||
namespace NTP.Application.Grains.Permits;
|
||||
|
||||
/// <summary>Writes legacy-style GN events (EVENTS row with PERMITID, domain 'GN', updated type 'NTP').</summary>
|
||||
public static class PermitEventLog
|
||||
{
|
||||
public const string Domain = "GN";
|
||||
|
||||
/// <summary>addEvent('PERMITID', id, prev, curr, user, role?, 'GN', location, 'NTP', remarks, weight) for the signed-in user.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Same, performed by a named actor (SYSTEM for jobs / dialer callbacks, W{location} for weighbridges).</summary>
|
||||
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<string, object?>? Remarks(string? remarks) =>
|
||||
string.IsNullOrEmpty(remarks) ? null : new Dictionary<string, object?> { ["REMARKS"] = remarks };
|
||||
}
|
||||
|
|
@ -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<PagedResult<PermitListItem>> SearchAsync(PermitSearchQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<PagedResult<GatePermitItem>> SearchGateListAsync(GatePermitQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<PermitDetailDto> GetAsync(long id, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<PermitEventDto>> GetEventsAsync(long id, CancellationToken ct = default);
|
||||
|
||||
Task<TruckInfoDto?> GetTruckInfoAsync(string tn, bool validate, CancellationToken ct = default);
|
||||
Task<TrailerInfoDto?> GetTrailerInfoAsync(string trn, CancellationToken ct = default);
|
||||
Task<DriverInfoDto?> GetDriverInfoAsync(string nnpn, CancellationToken ct = default);
|
||||
|
||||
Task<PermitOperationResult> SubmitAsync(long id, SubmitOrderRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> UpdateAsync(long id, UpdateOrderRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> AcceptAsync(long id, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> RevokeAsync(long id, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> RevokeAcceptedAsync(long id, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> ConvertToResdAsync(long id, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> CancelOrderAsync(long id, ReasonRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> RevokePermitAsync(long id, ReasonRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> ReactivateAsync(long id, CancellationToken ct = default);
|
||||
|
||||
/// <summary>GrainsFactory.cancelGrainsPermit: a released permit goes back to ACCPT (used by integrations).</summary>
|
||||
Task<PermitOperationResult> CancelGrainsPermitAsync(long id, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> CloseManualAsync(ClosePermitRequest request, CancellationToken ct = default);
|
||||
|
||||
Task<PermitOperationResult> PhoneAcceptAsync(long id, PhoneAcceptRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> PhoneRejectAsync(long id, PhoneRejectRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Phone accept performed by an actor other than the signed-in user (auto dialer callback = SYSTEM).</summary>
|
||||
Task<PermitOperationResult> PhoneAcceptCoreAsync(long permitId, string? remarks, string doneBy, CancellationToken ct);
|
||||
|
||||
/// <summary>Phone reject performed by an actor other than the signed-in user (auto dialer callback = SYSTEM).</summary>
|
||||
Task<PermitOperationResult> PhoneRejectCoreAsync(long permitId, string reason, int expiryDays, string doneBy, CancellationToken ct,
|
||||
string category = "PHONEDECLINE");
|
||||
|
||||
Task<string> ValidateReferencesAsync(string tn, string trn, string nnpn, long scac, CancellationToken ct = default);
|
||||
|
||||
Task<PermitOperationResult> SaveWeightsAsync(SaveWeightsRequest request, CancellationToken ct = default);
|
||||
Task<StoredWeightsDto> LookupWeightsAsync(string pn, CancellationToken ct = default);
|
||||
|
||||
AbsenceFeatureDto GetAbsenceFeature();
|
||||
Task<PermitOperationResult> ToggleAbsenceFeatureAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<PagedResult<PermitListItem>> 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<PermitListItem>([], 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<PagedResult<GatePermitItem>> 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<PermitDetailDto> 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<IReadOnlyList<PermitEventDto>> 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<TruckInfoDto?> 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<TrailerInfoDto?> 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<DriverInfoDto?> 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<PermitOperationResult> 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<PermitOperationResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Ownership / fleet rules shared by submitOrder and updateOrder (messages kept verbatim).</summary>
|
||||
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<PermitOperationResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>validatePermitReferences: returns an Arabic error text or empty when everything is registered and in an allowed status.</summary>
|
||||
public async Task<string> 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<PermitOperationResult> 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<PermitOperationResult> 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<PermitOperationResult> 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<PermitOperationResult> 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<PermitOperationResult> 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<PermitOperationResult> 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<PermitOperationResult> 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<PermitOperationResult> 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<PermitOperationResult> PhoneAcceptAsync(long id, PhoneAcceptRequest r, CancellationToken ct = default) =>
|
||||
PhoneAcceptCoreAsync(id, r.Remarks, user.UserId, ct);
|
||||
|
||||
public Task<PermitOperationResult> PhoneRejectAsync(long id, PhoneRejectRequest r, CancellationToken ct = default)
|
||||
{
|
||||
new PhoneRejectValidator().ValidateAndThrow(r);
|
||||
return PhoneRejectCoreAsync(id, r.Reason.Trim(), r.ExpiryDays, user.UserId, ct);
|
||||
}
|
||||
|
||||
/// <summary>addPhoneAcceptEvent. Also used by the dialer callback (autoCall) with doneBy = SYSTEM.</summary>
|
||||
public async Task<PermitOperationResult> 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<string, object?>
|
||||
{
|
||||
["TN"] = permit.Tn, ["MOBILE"] = phone ?? string.Empty, ["PN"] = permit.Pn,
|
||||
["ORDERDATE"] = orderDetails?.OrderDate, ["TT"] = orderDetails?.CtCaption
|
||||
}, ct);
|
||||
|
||||
return PermitOperationResult.Ok(PermitOperationResult.DefaultOk, permitId);
|
||||
}
|
||||
|
||||
/// <summary>addPhoneRejectEvent (+ BL_addToBlacklist). Also used by the dialer callback with doneBy = SYSTEM.</summary>
|
||||
public async Task<PermitOperationResult> 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<string, object?>
|
||||
{
|
||||
["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<string, object?> Data(long blId, DateTime expiry) =>
|
||||
new Dictionary<string, object?> { ["blacklistId"] = blId, ["expiryDate"] = expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture) };
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ weights / feature flag
|
||||
|
||||
public async Task<PermitOperationResult> 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<StoredWeightsDto> 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<PermitOperationResult> 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<string, object?> { ["enabled"] = enabled });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ helpers
|
||||
|
||||
private IReadOnlyList<string> ActionsFor(string? status, long? companyCode) =>
|
||||
PermitActionRules.For(status, companyCode, user.IsCompany(options), user.IsInAnyRole(GrainsRoles.Operators.Split(',')),
|
||||
user.IsInAnyRole(GrainsRoles.ConvertToResd.Split(',')), user.IsInAnyRole("SU", "GTO"), 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));
|
||||
|
||||
/// <summary>TENDERORDER filter = "dd/MM/yyyy,shift".</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,150 @@
|
|||
using NTP.Application.Abstractions;
|
||||
using NTP.Domain.Grains.Permits;
|
||||
|
||||
namespace NTP.Application.Grains.Permits;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class GrainsRoles
|
||||
{
|
||||
/// <summary>Back-office operators: distribution, phone confirmation, manual operations, queue creation.</summary>
|
||||
public const string Operators = "SU,GPO,GNSU,GNCO,GTO";
|
||||
|
||||
/// <summary>Weighbridge / gate users plus operators.</summary>
|
||||
public const string Weighbridge = "SU,GPO,GNSU,GNCO,GTO,GATEIN,GATEOUT,THRU";
|
||||
|
||||
/// <summary>ConvertToResd button: legacy checks role SU or GPO only.</summary>
|
||||
public const string ConvertToResd = "SU,GPO";
|
||||
|
||||
/// <summary>Supervisors: configuration of destinations, activation of orders, absence feature.</summary>
|
||||
public const string Supervisors = "SU,GPO,GNSU,GTO";
|
||||
}
|
||||
|
||||
/// <summary>Helpers that replace legacy session.* lookups.</summary>
|
||||
public static class PermitUserContext
|
||||
{
|
||||
/// <summary>session.stkid = 62: a trucking company user (sees and changes only its own permits).</summary>
|
||||
public static bool IsCompany(this ICurrentUser user, GrainsPermitsOptions options) =>
|
||||
user.StkId == options.CompanyStakeholderId;
|
||||
|
||||
/// <summary>session.companyCodeNO = mid(CompanyCode, 4, 6) * 1; null when the user has no company code.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>session.locationid as a nullable string for EVENTS.LOCATIONID.</summary>
|
||||
public static string? LocationText(this ICurrentUser user) => user.LocationId?.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Which action buttons the caller may use on a permit (createGnOrder.cfm / GNPermits grid rules).</summary>
|
||||
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<string> For(string? status, long? companyCode, bool isCompany, bool isOperator, bool isConvertRole,
|
||||
bool isReactivator, long badiyaScac)
|
||||
{
|
||||
var a = new List<string> { 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Process-wide switch of the "absence" feature (legacy application.GNABSENCEFEATURE, in-memory).</summary>
|
||||
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)
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>TCS petroleum permit web service (legacy application.PetWS): createPermit / getFopDetail.</summary>
|
||||
public interface ITcsPermitGatewayService
|
||||
{
|
||||
Task<TcsPermitResult> CreatePermitAsync(TcsPermitRequest request, CancellationToken ct = default);
|
||||
Task<TcsFopDetail> GetFopDetailAsync(string fop, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Mobile notifications (legacy NTP.components.MobileNotifications.PrepareNotificationMessage).</summary>
|
||||
public interface IMobileNotificationGatewayService
|
||||
{
|
||||
Task SendAsync(string template, IReadOnlyDictionary<string, object?> payload, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Auto dialer / IVR (GrainsFactoryWeb.autoCallService2 / autoCallService).</summary>
|
||||
public interface IAutoCallGatewayService
|
||||
{
|
||||
/// <summary>POSTs {"TYPE":"TEST","FILE":base64} to the configured dialer URL; false when not reachable / not 200.</summary>
|
||||
Task<bool> SendCallFileAsync(byte[] csv, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Calls the IVR web service (callAPI).</summary>
|
||||
Task<bool> TriggerIvrAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Reads new rows from the external weighbridge database (legacy datasource GrainsWeighbridge).</summary>
|
||||
public interface IWeighbridgeSourceService
|
||||
{
|
||||
bool IsConfigured { get; }
|
||||
Task<IReadOnlyList<ExternalCargoRow>> ReadNewAsync(long locationId, DateTime? after, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,210 @@
|
|||
using FluentValidation;
|
||||
using NTP.Domain.Grains.Permits;
|
||||
|
||||
namespace NTP.Application.Grains.Permits;
|
||||
|
||||
/// <summary>Request validators ported from the Required/Float/Integer checks of the legacy pages (validateFields).</summary>
|
||||
public sealed class SubmitOrderValidator : AbstractValidator<SubmitOrderRequest>
|
||||
{
|
||||
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<UpdateOrderRequest>
|
||||
{
|
||||
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<ReasonRequest>
|
||||
{
|
||||
public ReasonValidator()
|
||||
{
|
||||
RuleFor(x => x.Reason).NotEmpty().MaximumLength(500).WithErrorCode("REASON_REQUIRED");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PhoneRejectValidator : AbstractValidator<PhoneRejectRequest>
|
||||
{
|
||||
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<ClosePermitRequest>
|
||||
{
|
||||
public ClosePermitValidator()
|
||||
{
|
||||
RuleFor(x => x.Pn).NotEmpty().Matches("^[0-9]{1,12}$").WithErrorCode("PN_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SaveWeightsValidator : AbstractValidator<SaveWeightsRequest>
|
||||
{
|
||||
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<AddToQueueRequest>
|
||||
{
|
||||
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<ManualInputRequest>
|
||||
{
|
||||
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<AssignByPnRequest>
|
||||
{
|
||||
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<WeighbridgeReadingRequest>
|
||||
{
|
||||
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<WeighbridgeWeightsRequest>
|
||||
{
|
||||
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<ManualWeighbridgeRequest>
|
||||
{
|
||||
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<WeighbridgeEventRequest>
|
||||
{
|
||||
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<DistributeRequest>
|
||||
{
|
||||
public DistributeValidator()
|
||||
{
|
||||
RuleFor(x => x.Category).Must(c => DistributionCategory.Parse(c) is not null)
|
||||
.WithMessage("نوع التوزيع غير صحيح").WithErrorCode("CATEGORY_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class OpenPermitWithDestinationValidator : AbstractValidator<OpenPermitWithDestinationRequest>
|
||||
{
|
||||
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<CompanyOpenPermitsRequest>
|
||||
{
|
||||
public CompanyOpenPermitsValidator()
|
||||
{
|
||||
RuleFor(x => x.Count).InclusiveBetween(1, 5000);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class CreateTcsPermitValidator : AbstractValidator<CreateTcsPermitRequest>
|
||||
{
|
||||
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("يجب إدخال رقم تصريح التفريغ");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Date helpers: legacy screens send dates as yyyy/mm/dd, dd/mm/yyyy or dd\mm\yyyy.</summary>
|
||||
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);
|
||||
}
|
||||
|
|
@ -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<PagedResult<QueueItem>> ListAsync(QueueSearchQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> AddToQueueAsync(AddToQueueRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>AddToQueue called from Accept (inside the caller's transaction); returns the legacy message.</summary>
|
||||
Task<string> AddToQueueInternalAsync(string tn, string tt, string actor, bool checkStatuses, CancellationToken ct = default);
|
||||
|
||||
/// <summary>ws.cfc createPermitRecord: creates an OPEN (or other initial status) permit record / turn.</summary>
|
||||
Task<PermitOperationResult> CreatePermitRecordAsync(string? tn, long? scac, string nextStatus, string tt, bool checkStatuses,
|
||||
string actor, CancellationToken ct = default);
|
||||
|
||||
Task<string?> GetTrailerNumberAsync(string tn, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> CheckTrucksAsync(long tn, long scac, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> SeedPermitsAsync(SeedPermitsRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>jobs/parseGrainsPermits.cfm: tops every company's OPEN permits up to its queue share. Returns created count.</summary>
|
||||
Task<int> FillCompanySharesAsync(CancellationToken ct = default);
|
||||
|
||||
// ---- TCS permit (createPermit.cfm)
|
||||
Task<TcsFormDataDto?> GetTcsFormDataAsync(long permitId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RoutingTemplateDto>> GetRoutingTemplatesAsync(long origin, long destination, string shipmentMode, string firms,
|
||||
CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LookupItem>> GetOriginAddressesAsync(long routing, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RoutingTemplateDto>> GetPhRoutesAsync(CancellationToken ct = default);
|
||||
Task<string?> GetClearingAgentNameAsync(long can, CancellationToken ct = default);
|
||||
Task<TcsFopDetail> GetFopDetailAsync(string fop, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> 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<PagedResult<QueueItem>> 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<PermitOperationResult> 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<string> AddToQueueInternalAsync(string tn, string tt, string actor, bool checkStatuses, CancellationToken ct = default) =>
|
||||
(await AddToQueueCoreAsync(tn.Trim(), tt, actor, checkStatuses, ct)).Message;
|
||||
|
||||
private async Task<PermitOperationResult> 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<PermitOperationResult> 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<string, object?> { ["pn"] = pn });
|
||||
}
|
||||
|
||||
public Task<string?> GetTrailerNumberAsync(string tn, CancellationToken ct = default) =>
|
||||
repo.GetTrailerNumberAsync(tn.Trim(), options.AllowedStatuses, ct);
|
||||
|
||||
public async Task<PermitOperationResult> 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<PermitOperationResult> 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<int> 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<TcsFormDataDto?> GetTcsFormDataAsync(long permitId, CancellationToken ct = default) =>
|
||||
repo.GetFormDataAsync(permitId, user.Domain, ct);
|
||||
|
||||
public Task<IReadOnlyList<RoutingTemplateDto>> GetRoutingTemplatesAsync(long origin, long destination, string shipmentMode, string firms,
|
||||
CancellationToken ct = default) =>
|
||||
repo.GetRoutingTemplatesAsync(origin, destination, shipmentMode, firms, user.Domain, ct);
|
||||
|
||||
public Task<IReadOnlyList<LookupItem>> GetOriginAddressesAsync(long routing, CancellationToken ct = default) =>
|
||||
repo.GetOriginAddressesAsync(routing, user.Domain, ct);
|
||||
|
||||
public Task<IReadOnlyList<RoutingTemplateDto>> GetPhRoutesAsync(CancellationToken ct = default) => repo.GetPhRoutesAsync(ct);
|
||||
|
||||
public Task<string?> GetClearingAgentNameAsync(long can, CancellationToken ct = default) => repo.GetClearingAgentNameAsync(can, ct);
|
||||
|
||||
public Task<TcsFopDetail> GetFopDetailAsync(string fop, CancellationToken ct = default) => tcs.GetFopDetailAsync(fop.Trim(), ct);
|
||||
|
||||
public async Task<PermitOperationResult> 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<string, object?> { ["pn"] = result.PermitNumber, ["destination"] = dest.DestName });
|
||||
}
|
||||
|
||||
/// <summary>insertPermitStop: one PERMITSTOPS row per leg of the routing template.</summary>
|
||||
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();
|
||||
}
|
||||
|
|
@ -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<AcceptPrintDto?> GetAcceptPrintAsync(long permitId, CancellationToken ct = default);
|
||||
Task<PrintHeaderRow?> GetPrintHeaderAsync(long permitId, bool withLocations, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<PrintWeightEvent>> GetLatestWeightEventsAsync(long permitId, CancellationToken ct = default);
|
||||
Task<PrintWeightEvent?> GetLatestEventWithLocationAsync(long permitId, string eventType, CancellationToken ct = default);
|
||||
Task<PermitDetailsPrintDto?> GetDetailsAsync(long permitId, CancellationToken ct = default);
|
||||
Task<long?> GetCompanyCodeAsync(long permitId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IWeighbridgeService
|
||||
{
|
||||
/// <summary>EN_WeightBridge: first weighing at the entry booth (LNW 0, LTW, LGW) followed by an automatic destination assignment.</summary>
|
||||
Task<WeighbridgeResult> EnterAsync(WeighbridgeReadingRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>EX_WeightBridge: second weighing (DNW = weight - last LTW, DTW, DGW).</summary>
|
||||
Task<WeighbridgeResult> ExitAsync(WeighbridgeReadingRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>WeightBridge.cfm / grains.addWeightBridgeEvent: manual entry of both weights through the integration rules (EN then EX).</summary>
|
||||
Task<PermitOperationResult> ManualAsync(ManualWeighbridgeRequest request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>loadingWeightBridge.cfm (ws.addLoadingWeightEvent) / dischargeWeightBridge.cfm (ws.addDischargeWeightEvent).</summary>
|
||||
Task<PermitOperationResult> LoadingWeightsAsync(WeighbridgeWeightsRequest request, CancellationToken ct = default);
|
||||
Task<PermitOperationResult> DischargeWeightsAsync(WeighbridgeWeightsRequest request, CancellationToken ct = default);
|
||||
|
||||
Task<TruckPermitBriefDto?> GetTruckPermitAsync(string tn, string status, CancellationToken ct = default);
|
||||
Task<WaybridgeEventDto?> GetTruckWaybridgeEventAsync(string tn, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LocationTruckCountDto>> GetLocationTruckCountsAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>jobs/getWeighbridgeEvents.cfm (aqaba=false) and getAqabaWeighbridgeEvents.cfm (aqaba=true). Returns processed raw rows.</summary>
|
||||
Task<int> SyncAsync(bool aqaba, CancellationToken ct = default);
|
||||
|
||||
// printing
|
||||
Task<AcceptPrintDto> GetAcceptPrintAsync(long permitId, CancellationToken ct = default);
|
||||
Task<PrintInDto> GetPrintInAsync(long permitId, CancellationToken ct = default);
|
||||
Task<PrintOutDto> GetPrintOutAsync(long permitId, CancellationToken ct = default);
|
||||
Task<PermitDetailsPrintDto> GetPermitDetailsAsync(long permitId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Weighbridge operations, print data and the weighbridge-sync jobs of the Grains permits slice.</summary>
|
||||
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<WeighbridgeResult> 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<WeighbridgeResult> 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<PermitOperationResult> 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<string, object?> { ["en"] = en.Msg, ["ex"] = ex.Msg })
|
||||
: PermitOperationResult.Fail("WEIGHBRIDGE_REJECTED", text);
|
||||
}
|
||||
|
||||
public Task<PermitOperationResult> LoadingWeightsAsync(WeighbridgeWeightsRequest r, CancellationToken ct = default) =>
|
||||
WeightsAsync(r, PermitStatus.Released, loading: true, ct);
|
||||
|
||||
public Task<PermitOperationResult> DischargeWeightsAsync(WeighbridgeWeightsRequest r, CancellationToken ct = default) =>
|
||||
WeightsAsync(r, PermitStatus.ArrivedControl, loading: false, ct);
|
||||
|
||||
private async Task<PermitOperationResult> 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<TruckPermitBriefDto?> GetTruckPermitAsync(string tn, string status, CancellationToken ct = default) =>
|
||||
repo.GetPermitByTruckAndStatusAsync(tn.Trim(), status, ct);
|
||||
|
||||
public async Task<WaybridgeEventDto?> 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<IReadOnlyList<LocationTruckCountDto>> GetLocationTruckCountsAsync(CancellationToken ct = default) =>
|
||||
repo.GetLocationTruckCountsAsync(ct);
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ job
|
||||
|
||||
public async Task<int> 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<bool> 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<AcceptPrintDto> 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<PrintInDto> 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<PrintOutDto> 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<PermitDetailsPrintDto> 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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<PagedResult<BlacklistGridRowDto>> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<BlacklistAddedDto> AddAsync(AddBlacklistRequest request, CancellationToken ct);
|
||||
Task<RegistryResult> CancelAsync(long id, CancelBlacklistRequest request, CancellationToken ct);
|
||||
/// <summary>jobs\changeBlacklistStatus.cfm: expires OPEN entries whose expiry date has passed.</summary>
|
||||
Task<int> ExpireDueAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of grains.cfc getBlackListGrid / BL_addToBlacklist / deleteFromBlackList and the expiry job.</summary>
|
||||
public sealed class BlacklistService(
|
||||
IBlacklistRepository repository,
|
||||
IRegistrySettingsService settings,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user) : IBlacklistService
|
||||
{
|
||||
private static readonly string[] CancelRoles = ["GNSU", "GNCO", "GTO"];
|
||||
|
||||
public async Task<PagedResult<BlacklistGridRowDto>> 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<BlacklistAddedDto> 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<RegistryResult> 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<int> ExpireDueAsync(CancellationToken ct) => repository.ExpireDueAsync(ct);
|
||||
}
|
||||
|
|
@ -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<PagedResult<DriverGridRowDto>> SearchAsync(DriverListQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<DriverDetailDto> GetAsync(long id, CancellationToken ct);
|
||||
Task<RegistryResult> CreateAsync(SaveDriverRequest request, CancellationToken ct);
|
||||
Task<RegistryResult> AcceptAsync(long id, CancellationToken ct);
|
||||
Task<RegistryResult> RevokeAsync(long id, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of register.cfc saveDriverDetails / getDriverInfo / getDriverGrid / revokeDriver / acceptDriver.</summary>
|
||||
public sealed class DriverRegistryService(
|
||||
IRegistryRepository repository,
|
||||
IRegistryAccessService access,
|
||||
IRegistryAttachmentService attachments,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user) : IDriverRegistryService
|
||||
{
|
||||
public async Task<PagedResult<DriverGridRowDto>> 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<DriverDetailDto> 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<RegistryResult> 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<RegistryResult> 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<RegistryResult> 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,170 @@
|
|||
using NTP.Application.Common;
|
||||
using NTP.Domain.Grains.Registry;
|
||||
|
||||
namespace NTP.Application.Grains.Registry;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>Grains:Registry</c> with safe defaults.
|
||||
/// </summary>
|
||||
public interface IRegistrySettingsService
|
||||
{
|
||||
long BadiyaScac { get; }
|
||||
/// <summary>GN_ALLOWEDSTATUSES (default OPEN,ACCPT).</summary>
|
||||
IReadOnlyList<string> AllowedTruckStatuses { get; }
|
||||
IReadOnlyList<string> BadiyaOwnershipCodes { get; }
|
||||
IReadOnlyList<string> OthersOwnershipCodes { get; }
|
||||
/// <summary>"start,end" hours of distribution shift <paramref name="shift"/> (default 0,24).</summary>
|
||||
(int Start, int End) ShiftHours(int shift);
|
||||
string TempUploadPath { get; }
|
||||
string UploadedFilesPath { get; }
|
||||
long MaxUploadBytes { get; }
|
||||
IReadOnlyList<string> AllowedUploadExtensions { get; }
|
||||
}
|
||||
|
||||
/// <summary>File system part of the attachments (temp upload, promotion to the permanent folder, reading).</summary>
|
||||
public interface IRegistryFileStoreService
|
||||
{
|
||||
/// <summary>Saves an uploaded file in the temp folder; returns the temp id.</summary>
|
||||
Task<RegistryTempFileDto> SaveTempAsync(Stream content, string originalName, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Original name recorded for a temp id, or null when the temp file does not exist.</summary>
|
||||
Task<string?> GetTempNameAsync(string tempId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Moves a temp file into <paramref name="folder"/> under <paramref name="storedName"/> (legacy cffile rename).</summary>
|
||||
Task PromoteAsync(string tempId, string folder, string storedName, CancellationToken ct = default);
|
||||
|
||||
Task<Stream?> OpenAsync(string folder, string storedName, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IRegistryRepository
|
||||
{
|
||||
// ----- authorization (legacy application.objAuth.isActAuthorized(actionId, session.lstGID))
|
||||
Task<bool> HasActionAsync(string roleCode, int actionId, CancellationToken ct = default);
|
||||
|
||||
// ----- lookups
|
||||
Task<IReadOnlyList<TenderCompanyDto>> GetTenderCompaniesAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<TruckKindDto>> GetTruckKindsAsync(IReadOnlyList<string> kinds, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RegistryLocationDto>> GetDestinationLocationsAsync(string gnType, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RegistryNationalityDto>> GetDriverNationalitiesAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RegistryLocationDto>> GetLocationsByIdsAsync(IReadOnlyList<long> ids, CancellationToken ct = default);
|
||||
|
||||
// ----- grids
|
||||
Task<PagedResult<TruckGridRowDto>> SearchTrucksAsync(RegistryScope scope, TruckListQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<PagedResult<TrailerGridRowDto>> SearchTrailersAsync(RegistryScope scope, TrailerListQuery query, PageRequest page, CancellationToken ct = default);
|
||||
Task<PagedResult<DriverGridRowDto>> SearchDriversAsync(RegistryScope scope, DriverListQuery query, PageRequest page, CancellationToken ct = default);
|
||||
/// <summary>getAllTrnOnthisTn: trailers connected to a truck (or just the given trailer).</summary>
|
||||
Task<IReadOnlyList<TrailerGridRowDto>> ListTrailersOfTruckAsync(RegistryScope scope, long? truckId, long? trailerId, CancellationToken ct = default);
|
||||
|
||||
// ----- trucks
|
||||
Task<TruckDetailDto?> GetTruckDetailAsync(long id, CancellationToken ct = default);
|
||||
Task<NtpTruck?> GetTruckAsync(long id, CancellationToken ct = default);
|
||||
Task<NtpTrailer?> GetLatestTrailerOfTruckAsync(long truckId, CancellationToken ct = default);
|
||||
/// <summary>validateUniqueTN: an active (REGREQST/OPEN/ACCPT) truck with the number exists.</summary>
|
||||
Task<bool> ActiveTruckExistsAsync(string tn, CancellationToken ct = default);
|
||||
Task<long> 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<bool> TruckHasGnPermitAsync(string tn, CancellationToken ct = default);
|
||||
|
||||
// ----- destinations (NTP_COMPANY_DISTINATION)
|
||||
Task<IReadOnlyList<long>> GetActiveDestinationIdsAsync(string tn, CancellationToken ct = default);
|
||||
Task<PendingDestinationDto?> GetPendingDestinationAsync(string tn, CancellationToken ct = default);
|
||||
Task InsertDestinationAsync(string tn, long destination, string userId, CancellationToken ct = default);
|
||||
|
||||
// ----- trailers
|
||||
Task<TrailerDetailDto?> GetTrailerDetailAsync(long id, CancellationToken ct = default);
|
||||
Task<NtpTrailer?> GetTrailerAsync(long id, CancellationToken ct = default);
|
||||
Task<bool> ActiveTrailerExistsAsync(string tn, CancellationToken ct = default);
|
||||
Task<bool> TruckHasNonRevokedTrailerAsync(long truckId, CancellationToken ct = default);
|
||||
Task<long> 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<DriverDetailDto?> GetDriverDetailAsync(long id, CancellationToken ct = default);
|
||||
Task<NtpDriver?> GetDriverAsync(long id, CancellationToken ct = default);
|
||||
/// <summary>validateUniqueNNPN: a driver with this NNPN in an active status exists (optionally ignoring one id).</summary>
|
||||
Task<bool> ActiveDriverExistsAsync(string nnpn, long? excludeId, CancellationToken ct = default);
|
||||
Task<long> 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<IReadOnlyList<GrainsFile>> GetFilesAsync(long entityId, string attachmentType, CancellationToken ct = default);
|
||||
Task<GrainsFile?> FindFileAsync(string attachmentType, string fileName, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IBlacklistRepository
|
||||
{
|
||||
Task<PagedResult<BlacklistGridRowDto>> SearchAsync(BlacklistQuery query, PageRequest page, CancellationToken ct = default);
|
||||
/// <summary>shift of the tender order connected to the permit (grainstenderorder.shift), null when there is none.</summary>
|
||||
Task<int?> GetPermitShiftAsync(long permitId, CancellationToken ct = default);
|
||||
/// <summary>permits.id for a permit number (PN), null when unknown.</summary>
|
||||
Task<long?> FindPermitIdByNumberAsync(string pn, CancellationToken ct = default);
|
||||
Task<long> InsertAsync(string category, string entityType, string entityId, string createdBy, DateTime expiry, string remarks, CancellationToken ct = default);
|
||||
Task<GrainsBlacklistEntry?> GetAsync(long id, CancellationToken ct = default);
|
||||
Task CancelAsync(long id, string user, string remarks, CancellationToken ct = default);
|
||||
/// <summary>TRUCK_DISTRIBUTION_LOG rows of a cancelled entry (PENDING / RVKD) -> DELETED.</summary>
|
||||
Task DeleteDistributionLogAsync(long blacklistId, string remarks, CancellationToken ct = default);
|
||||
/// <summary>Job: OPEN entries whose EXPIRYDATE has passed -> EXPIRED (by SYSTEM). Returns the count.</summary>
|
||||
Task<int> ExpireDueAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Weighbridge exceptions, grains weights, fleet turns, location counts and the permit-screen lookups of grains.cfc.</summary>
|
||||
public interface IRegistryOpsRepository
|
||||
{
|
||||
Task<long?> 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<long?> 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<int> CountActiveFleetAsync(long scac, CancellationToken ct = default);
|
||||
Task<int> CountActiveTurnRowsAsync(long scac, CancellationToken ct = default);
|
||||
Task<bool> 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<bool> IsValidBadiyaTruckAsync(string tn, long badiyaScac, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LocationTruckCountDto>> GetLocationTruckCountsAsync(CancellationToken ct = default);
|
||||
|
||||
// permit-screen lookups (grains.cfc)
|
||||
Task<DriverFromPermitDto?> GetDriverFromPermitsAsync(string nnpn, string domain, CancellationToken ct = default);
|
||||
Task<TruckFromPermitDto?> GetTruckFromPermitsAsync(string tn, string domain, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<TrailerInUseDto>> GetTrailerInUseAsync(string trn, long? exceptPermitId, string domain, CancellationToken ct = default);
|
||||
Task<PermitByTruckDto?> GetPermitByTruckAsync(string tn, string status, CancellationToken ct = default);
|
||||
Task<string?> GetTrailerNumberOfTruckAsync(string tn, IReadOnlyList<string> allowedStatuses, CancellationToken ct = default);
|
||||
|
||||
Task<(string? ChasesNumber, string? Axials, DateTime? RegDate)?> GetTruckInfoAsync(string tn, RegistryScope scope, CancellationToken ct = default);
|
||||
Task<long?> 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<string?> GetMotOwnershipCodeAsync(string tn, long scac, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<string>> GetMotTruckTypesAsync(string tn, long scac, CancellationToken ct = default);
|
||||
Task<int> CountMotTrailerRowsAsync(string trn, long scac, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>Port of ws.cfc createPermitRecord and the job that registers the queue for new 327 trucks.</summary>
|
||||
public interface IRegistryQueuePermitRepository
|
||||
{
|
||||
Task<bool> IsOpenOrAcceptedGnTruckAsync(string tn, CancellationToken ct = default);
|
||||
Task<bool> HasActivePermitAsync(string tn, string tt, bool checkAllStatuses, CancellationToken ct = default);
|
||||
Task<long> NextTrackingNumberAsync(bool badiya, CancellationToken ct = default);
|
||||
Task<long> NextTripCounterAsync(string tt, long badiyaScac, CancellationToken ct = default);
|
||||
Task<long> GetMaxTenderIdAsync(CancellationToken ct = default);
|
||||
Task<long> InsertPermitAsync(string pn, string tn, long scac, string status, string tt, long? tripCounter, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<string>> GetBadiyaTrucksWithoutPermitsAsync(long badiyaScac, CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -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
|
||||
{
|
||||
/// <summary>Legacy session.companyCodeNO: numeric part of the user's company code (mid(code,4,6)), null when not numeric.</summary>
|
||||
long? CompanyCodeNo { get; }
|
||||
bool IsBadiyaCompany { get; }
|
||||
/// <summary>Company users (session.stkid eq 62) only see / touch their own company's records.</summary>
|
||||
bool IsCompanyUser { get; }
|
||||
RegistryScope Scope { get; }
|
||||
Task<bool> HasActionAsync(int actionId, CancellationToken ct = default);
|
||||
/// <summary>Throws <see cref="ForbiddenException"/> unless the user has the action (or <paramref name="orBadiya"/> and the user belongs to 327).</summary>
|
||||
Task RequireActionAsync(int actionId, bool orBadiya = false, CancellationToken ct = default);
|
||||
/// <summary>Adding / editing a truck, trailer or driver is decided by the permission table only (GRAINS_SCREEN_PERMISSIONS); throws Forbidden otherwise.</summary>
|
||||
Task RequireAuthorityAsync(string permissionKey, CancellationToken ct = default);
|
||||
/// <summary>Company users may only access records of their own company.</summary>
|
||||
void EnsureCompanyAccess(long? recordTcscac);
|
||||
Task<RegistryPermissionsDto> 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"));
|
||||
|
||||
/// <summary>ColdFusion: <c>isnumeric(mid(code,4,6))</c> then <c>mid(code,4,6)*1</c>.</summary>
|
||||
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<bool> 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<RegistryPermissionsDto> 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")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
using NTP.Application.Common;
|
||||
using NTP.Domain.Grains.Registry;
|
||||
|
||||
namespace NTP.Application.Grains.Registry;
|
||||
|
||||
public interface IRegistryAttachmentService
|
||||
{
|
||||
Task<RegistryTempFileDto> UploadTempAsync(Stream content, string fileName, long length, CancellationToken ct = default);
|
||||
/// <summary>Verifies every temp id exists (so a save fails before anything is written). Returns the distinct ids.</summary>
|
||||
Task<IReadOnlyList<string>> EnsureTempFilesAsync(IEnumerable<string>? tempIds, CancellationToken ct = default);
|
||||
/// <summary>Saves GRAINS_FILES rows and moves the temp files to the permanent folder (legacy genFileName + cffile rename).</summary>
|
||||
Task AttachAsync(string kind, long entityId, IReadOnlyList<string> tempIds, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<RegistryAttachmentDto>> ListAsync(string kind, long entityId, CancellationToken ct = default);
|
||||
Task<RegistryDownload> 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<RegistryTempFileDto> 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<IReadOnlyList<string>> EnsureTempFilesAsync(IEnumerable<string>? 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<string> 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<IReadOnlyList<RegistryAttachmentDto>> 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<RegistryDownload> 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"
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,433 @@
|
|||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace NTP.Application.Grains.Registry;
|
||||
|
||||
// ------------------------------------------------------------------ shared / lookups
|
||||
|
||||
/// <summary>Who the caller is, as far as the registry rules care (legacy session.stkid / companycodeno / userrolecode).</summary>
|
||||
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; }
|
||||
/// <summary>Action 107: pick / see destinations (truck form, company 327 only).</summary>
|
||||
public bool CanManageDestinations { get; set; }
|
||||
/// <summary>Roles GTO, GOO, GNAC may export the truck report (legacy report icon).</summary>
|
||||
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
|
||||
{
|
||||
/// <summary>TRUCKKINDS.TRUCKKINDCODE: S (single), T (tractor head), HTR (half trailer), TR (trailer).</summary>
|
||||
public string Kind { get; set; } = string.Empty;
|
||||
/// <summary>TRUCKKINDS.ID: stored in AXIALS.</summary>
|
||||
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
|
||||
{
|
||||
/// <summary>gn_type PCKD (legacy "مشول").</summary>
|
||||
public IReadOnlyList<RegistryLocationDto> Packed { get; set; } = [];
|
||||
/// <summary>gn_type BULK (legacy "سائب").</summary>
|
||||
public IReadOnlyList<RegistryLocationDto> Bulk { get; set; } = [];
|
||||
/// <summary>gn_type BULK_GALLAB (legacy "سائب - قلابات").</summary>
|
||||
public IReadOnlyList<RegistryLocationDto> BulkGallab { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class RegistryAttachmentDto
|
||||
{
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
public string OriginalName { get; set; } = string.Empty;
|
||||
/// <summary>truck | trailer | driver (route segment of the download endpoint).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Result of a write: <c>message</c> is shown verbatim by the front end (legacy Arabic MSG).</summary>
|
||||
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;
|
||||
/// <summary>TN (truck) or TRN (trailer) - what the row represents.</summary>
|
||||
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; }
|
||||
/// <summary>For trailer rows: the connected truck id (NTP_TRAILERS.TN_ID).</summary>
|
||||
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; }
|
||||
/// <summary>Permit number for PERMIT entries, the raw number for driver/truck/trailer entries.</summary>
|
||||
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; }
|
||||
/// <summary>S when AXIALS < 7, otherwise T (legacy form radio).</summary>
|
||||
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; }
|
||||
/// <summary>Active destination location ids (only for users who may see destinations: action 107 or role GOO).</summary>
|
||||
public IReadOnlyList<long>? DestinationIds { get; set; }
|
||||
public PendingDestinationDto? PendingDestination { get; set; }
|
||||
public IReadOnlyList<RegistryAttachmentDto> 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; }
|
||||
/// <summary>TR when AXIALS < 12, otherwise HTR (legacy form radio).</summary>
|
||||
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<RegistryAttachmentDto> 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; }
|
||||
/// <summary>Owning company (used for the company-user scope check only).</summary>
|
||||
[JsonIgnore]
|
||||
public long? Tcscac { get; set; }
|
||||
public IReadOnlyList<RegistryAttachmentDto> Attachments { get; set; } = [];
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ requests
|
||||
|
||||
/// <summary>Destinations picked on the truck form (location ids per group).</summary>
|
||||
public sealed class TruckDestinationsRequest
|
||||
{
|
||||
public List<long> Packed { get; set; } = [];
|
||||
public List<long> Bulk { get; set; } = [];
|
||||
public List<long> BulkGallab { get; set; } = [];
|
||||
|
||||
public IReadOnlyList<long> 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; }
|
||||
/// <summary>Temp ids returned by POST files/temp.</summary>
|
||||
public List<string>? AttachmentIds { get; set; }
|
||||
/// <summary>Only honoured for users with action 107. On update: null = leave destinations untouched.</summary>
|
||||
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; }
|
||||
/// <summary>The truck to connect the trailer to (legacy TNID). Optional.</summary>
|
||||
public long? TruckId { get; set; }
|
||||
public List<string>? 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<string>? AttachmentIds { get; set; }
|
||||
}
|
||||
|
||||
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
|
||||
public sealed class AddBlacklistRequest
|
||||
{
|
||||
/// <summary>PERMIT (default, the only value the legacy page sends), DRIVERNUMBER, TRUCKNUMBER, TRAILERNUMBER.</summary>
|
||||
public string? EntityType { get; set; }
|
||||
/// <summary>Permit number (PN), or the permit id when <see cref="IsId"/>; the number for the other entity types.</summary>
|
||||
public string? EntityNum { get; set; }
|
||||
public bool IsId { get; set; }
|
||||
public string? Category { get; set; }
|
||||
/// <summary>Number of days (legacy EXPIRYDATE select: 1,2,3,4,5,10,14,30).</summary>
|
||||
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; }
|
||||
}
|
||||
|
|
@ -0,0 +1,142 @@
|
|||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Grains.Registry;
|
||||
|
||||
public interface IRegistryLookupService
|
||||
{
|
||||
Task<RegistryPermissionsDto> PermissionsAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<TenderCompanyDto>> CompaniesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<TruckKindDto>> TruckKindsAsync(IReadOnlyList<string> kinds, CancellationToken ct);
|
||||
Task<RegistryDestinationOptionsDto> DestinationsAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<RegistryNationalityDto>> DriverNationalitiesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<RegistryLocationDto>> WeighbridgeLocationsAsync(CancellationToken ct);
|
||||
|
||||
// grains.cfc permit-screen lookups
|
||||
Task<DriverFromPermitDto?> DriverFromPermitsAsync(string nnpn, CancellationToken ct);
|
||||
Task<TruckFromPermitDto?> TruckFromPermitsAsync(string tn, CancellationToken ct);
|
||||
Task<IReadOnlyList<TrailerInUseDto>> TrailerInUseAsync(string trn, long? exceptPermitId, CancellationToken ct);
|
||||
Task<PermitByTruckDto?> PermitByTruckAsync(string tn, string status, CancellationToken ct);
|
||||
Task<TrailerOfTruckDto> TrailerNumberOfTruckAsync(string tn, CancellationToken ct);
|
||||
Task<TruckInfoForPermitDto> TruckInfoAsync(string tn, bool validate, CancellationToken ct);
|
||||
Task<TrailerInfoForPermitDto> TrailerInfoAsync(string trn, CancellationToken ct);
|
||||
Task<DriverInfoForPermitDto> DriverInfoAsync(string nnpn, CancellationToken ct);
|
||||
|
||||
// MOT (register.cfc validateTNMOT / validateTRNMOT / validateOwnerTN)
|
||||
Task<string> ValidateTruckMotAsync(string tn, long scac, string? truckType, CancellationToken ct);
|
||||
Task<string> ValidateTrailerMotAsync(string trn, long scac, CancellationToken ct);
|
||||
Task<string> ValidateOwnerAsync(long companyScac, string tn, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class RegistryLookupService(
|
||||
IRegistryRepository repository,
|
||||
IRegistryOpsRepository ops,
|
||||
IRegistryAccessService access,
|
||||
IRegistrySettingsService settings,
|
||||
ICurrentUser user) : IRegistryLookupService
|
||||
{
|
||||
public Task<RegistryPermissionsDto> PermissionsAsync(CancellationToken ct) => access.GetPermissionsAsync(ct);
|
||||
|
||||
public Task<IReadOnlyList<TenderCompanyDto>> CompaniesAsync(CancellationToken ct) => repository.GetTenderCompaniesAsync(ct);
|
||||
|
||||
public Task<IReadOnlyList<TruckKindDto>> TruckKindsAsync(IReadOnlyList<string> kinds, CancellationToken ct) =>
|
||||
repository.GetTruckKindsAsync(kinds.Select(k => k.Trim()).Where(k => k.Length > 0).Distinct().Take(10).ToList(), ct);
|
||||
|
||||
public async Task<RegistryDestinationOptionsDto> 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<IReadOnlyList<RegistryNationalityDto>> DriverNationalitiesAsync(CancellationToken ct) => repository.GetDriverNationalitiesAsync(ct);
|
||||
|
||||
public Task<IReadOnlyList<RegistryLocationDto>> WeighbridgeLocationsAsync(CancellationToken ct) =>
|
||||
repository.GetLocationsByIdsAsync(RegistryOpsService.WeighbridgeLocationIds, ct);
|
||||
|
||||
public Task<DriverFromPermitDto?> DriverFromPermitsAsync(string nnpn, CancellationToken ct) =>
|
||||
ops.GetDriverFromPermitsAsync(nnpn.Trim(), user.Domain, ct);
|
||||
|
||||
public Task<TruckFromPermitDto?> TruckFromPermitsAsync(string tn, CancellationToken ct) =>
|
||||
string.IsNullOrWhiteSpace(tn) ? Task.FromResult<TruckFromPermitDto?>(null) : ops.GetTruckFromPermitsAsync(tn.Trim(), user.Domain, ct);
|
||||
|
||||
public Task<IReadOnlyList<TrailerInUseDto>> TrailerInUseAsync(string trn, long? exceptPermitId, CancellationToken ct) =>
|
||||
ops.GetTrailerInUseAsync(trn.Trim(), exceptPermitId is > 0 ? exceptPermitId : null, user.Domain, ct);
|
||||
|
||||
public Task<PermitByTruckDto?> PermitByTruckAsync(string tn, string status, CancellationToken ct) =>
|
||||
ops.GetPermitByTruckAsync(tn.Trim(), status.Trim(), ct);
|
||||
|
||||
public async Task<TrailerOfTruckDto> TrailerNumberOfTruckAsync(string tn, CancellationToken ct) =>
|
||||
new() { TrailerNumber = await ops.GetTrailerNumberOfTruckAsync(tn.Trim(), settings.AllowedTruckStatuses, ct) };
|
||||
|
||||
// ------------------------------------------------------------------ getTNinfo
|
||||
|
||||
public async Task<TruckInfoForPermitDto> 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<TrailerInfoForPermitDto> 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<DriverInfoForPermitDto> 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<string> 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<string> ValidateTrailerMotAsync(string trn, long scac, CancellationToken ct) =>
|
||||
RegistryRules.MotTrailerValidation(await ops.CountMotTrailerRowsAsync(trn.Trim(), scac, ct));
|
||||
|
||||
public async Task<string> 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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<RegistryResult> SaveWeighbridgeControlAsync(SaveWeighbridgeControlRequest request, CancellationToken ct);
|
||||
Task<RegistryResult> SaveGrainsWeightsAsync(SaveGrainsWeightsRequest request, CancellationToken ct);
|
||||
Task<FleetCheckResult> CheckTrucksAsync(FleetCheckRequest request, CancellationToken ct);
|
||||
Task<bool> ValidateNtpTruckAsync(string tn, CancellationToken ct);
|
||||
Task<IReadOnlyList<LocationTruckCountDto>> LocationTruckCountsAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Port of register.cfc saveWeighbridgesControlInfo and grains.cfc saveGrainsWeights / checkTrucks / validateNtpTrucks / getlocTruckNum.
|
||||
/// </summary>
|
||||
public sealed class RegistryOpsService(
|
||||
IRegistryOpsRepository repository,
|
||||
IEventLogger events,
|
||||
IRegistrySettingsService settings,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user) : IRegistryOpsService
|
||||
{
|
||||
/// <summary>The weighbridge exception screen only offers these locations (WeighbridgesControl.cfm: ID in(215,220,225)).</summary>
|
||||
public static readonly long[] WeighbridgeLocationIds = [215, 220, 225];
|
||||
|
||||
public async Task<RegistryResult> 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<RegistryResult> 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: <cfif len(EMPTY_WEIGHT) lt 5 or len(EMPTY_WEIGHT) lt 5> (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<string, object?> { ["REMARKS"] = remarks }), token);
|
||||
return true;
|
||||
}, ct);
|
||||
|
||||
return new RegistryResult(RegistryMessages.Done, permit.Id);
|
||||
}
|
||||
|
||||
public async Task<FleetCheckResult> 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<bool> ValidateNtpTruckAsync(string tn, CancellationToken ct) =>
|
||||
repository.IsValidBadiyaTruckAsync(tn.Trim(), settings.BadiyaScac, ct);
|
||||
|
||||
public Task<IReadOnlyList<LocationTruckCountDto>> LocationTruckCountsAsync(CancellationToken ct) =>
|
||||
repository.GetLocationTruckCountsAsync(ct);
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
using NTP.Application.Abstractions;
|
||||
using NTP.Domain.Grains.Registry;
|
||||
|
||||
namespace NTP.Application.Grains.Registry;
|
||||
|
||||
public interface IRegistryQueuePermitService
|
||||
{
|
||||
/// <summary>
|
||||
/// 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".
|
||||
/// </summary>
|
||||
Task<string> CreatePermitRecordAsync(string tn, long scac, string nextStatus, string tt, bool checkStatuses, CancellationToken ct = default);
|
||||
|
||||
/// <summary>jobs\RegisterGrainsQueueForNewTrucks.cfm: PCKD + BULK queue permits for 327 trucks that have none. Returns the truck count.</summary>
|
||||
Task<int> RegisterQueueForNewTrucksAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public sealed class RegistryQueuePermitService(
|
||||
IRegistryQueuePermitRepository repository,
|
||||
IEventLogger events,
|
||||
IUnitOfWork unitOfWork,
|
||||
IRegistrySettingsService settings) : IRegistryQueuePermitService
|
||||
{
|
||||
public async Task<string> 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<int> RegisterQueueForNewTrucksAsync(CancellationToken ct = default)
|
||||
{
|
||||
var trucks = await repository.GetBadiyaTrucksWithoutPermitsAsync(settings.BadiyaScac, ct);
|
||||
foreach (var tn in trucks)
|
||||
{
|
||||
var truck = tn.Trim();
|
||||
await unitOfWork.ExecuteInTransactionAsync<bool>(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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,266 @@
|
|||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using NTP.Domain.Grains.Registry;
|
||||
|
||||
namespace NTP.Application.Grains.Registry;
|
||||
|
||||
/// <summary>Stable error codes of the registry slice (ProblemDetails extension "code").</summary>
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>Legacy Arabic user messages (register.cfc / grains.cfc), kept verbatim.</summary>
|
||||
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} غير موجودة";
|
||||
}
|
||||
|
||||
/// <summary>Legacy status captions (register.cfc OPEN_caption ...).</summary>
|
||||
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
|
||||
|
||||
/// <summary>The accept button is hidden for ACCPT and RVKD records (registerGrains*.cfm, regesterDriver.cfm).</summary>
|
||||
public static bool CanAccept(string? status) =>
|
||||
!string.Equals(status, RegistryStatus.Accpt, StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(status, RegistryStatus.Rvkd, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The revoke button is hidden for RVKD records.</summary>
|
||||
public static bool CanRevoke(string? status) =>
|
||||
!string.Equals(status, RegistryStatus.Rvkd, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The edit button is hidden for RVKD records.</summary>
|
||||
public static bool CanEdit(string? status) =>
|
||||
!string.Equals(status, RegistryStatus.Rvkd, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Status written by editTrucksDetails: company 327 keeps REGREQST (and otherwise leaves the status alone,
|
||||
/// returns null), every other company is set to OPEN.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>formchek.js validateSpecialChars: true when the text contains a forbidden special character.</summary>
|
||||
public static bool HasSpecialChars(string? text) => !string.IsNullOrEmpty(text) && SpecialCharsRegex.IsMatch(text);
|
||||
|
||||
/// <summary>Manufacture year 1960 .. current year + 1 (isyearWithinRange).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Truck kind radio of the legacy truck form: AXIALS < 7 -> S (single) else T (tractor head).</summary>
|
||||
public static string? TruckKindOfAxials(long? axials) => axials is null ? null : axials < 7 ? "S" : "T";
|
||||
|
||||
/// <summary>Trailer kind radio of the legacy trailer form: AXIALS < 12 -> TR else HTR (half trailer).</summary>
|
||||
public static string? TrailerKindOfAxials(long? axials) => axials is null ? null : axials < 12 ? "TR" : "HTR";
|
||||
|
||||
/// <summary>numberFormat(value, '000..') of ColdFusion: left pad with zeros, never truncates.</summary>
|
||||
public static string PadNumber(long value, int width) => value.ToString(CultureInfo.InvariantCulture).PadLeft(width, '0');
|
||||
|
||||
// ---------------------------------------------------------------- attachments
|
||||
|
||||
/// <summary>
|
||||
/// Legacy pages refuse to save when fewer than 2 files are attached (license + identity):
|
||||
/// trailer of company 327, every driver. <paramref name="alreadyStored"/> counts files of the record already saved (edit).
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// BL_addToBlacklist expiry: <c>trunc(sysdate - (24 + shiftStart)/24) + days + shiftEnd/24</c>
|
||||
/// (shift hours come from application['grnsdtrbutnshft_N'] = "start,end").
|
||||
/// </summary>
|
||||
public static DateTime BlacklistExpiry(DateTime now, int days, int shiftStartHour, int shiftEndHour) =>
|
||||
now.AddHours(-(24 + shiftStartHour)).Date.AddDays(days).AddHours(shiftEndHour);
|
||||
|
||||
/// <summary>Remarks text stored with the entry (legacy appends the automatic release date, mm/dd/yyyy HH:mm).</summary>
|
||||
public static string BlacklistRemarks(string? remarks, DateTime expiry) =>
|
||||
$"{remarks}، سيتم فك الانتظار بشكل تلقائي بتاريخ {expiry.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)}";
|
||||
|
||||
/// <summary>Parses the legacy "start,end" application setting; falls back to the defaults.</summary>
|
||||
public static (int Start, int End) ParseShiftHours(string? setting, int defaultStart = 0, int defaultEnd = 24)
|
||||
{
|
||||
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)
|
||||
|
||||
/// <summary>validateOwnerTN: empty string = ok, otherwise the legacy Arabic error.</summary>
|
||||
public static string ValidateOwnership(
|
||||
string? ownershipCode, long companyScac, long badiyaScac,
|
||||
IReadOnlyCollection<string> badiyaOwnership, IReadOnlyCollection<string> 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";
|
||||
|
||||
/// <summary>validateTNMOT result: '' ok, 'not_registered' (no MOT record), 'wrongCT' (type not general cargo / all).</summary>
|
||||
public static string MotTruckValidation(IReadOnlyCollection<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>validateTRNMOT result: '' ok or 'not_registered'.</summary>
|
||||
public static string MotTrailerValidation(int matchingRows) => matchingRows == 0 ? MotNotRegistered : string.Empty;
|
||||
|
||||
// ---------------------------------------------------------------- fleet turns (grains.cfc checkTrucks)
|
||||
|
||||
public enum FleetAction { Allow, Duplicate, RecordTurn, RecordTurnAndReset }
|
||||
|
||||
/// <summary>
|
||||
/// checkTrucks: every company must use all its trucks before reusing one. <paramref name="turns"/> = 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).
|
||||
/// </summary>
|
||||
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)
|
||||
|
||||
/// <summary>Port of generatePermitNumber (the permit created for a registered truck). Empty for unknown types.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,200 @@
|
|||
using FluentValidation;
|
||||
using FluentValidation.Results;
|
||||
|
||||
namespace NTP.Application.Grains.Registry;
|
||||
|
||||
/// <summary>
|
||||
/// 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,
|
||||
/// <see cref="ThrowIfAny"/> raises a FluentValidation <see cref="ValidationException"/> (HTTP 400 with per-field errors).
|
||||
/// </summary>
|
||||
public static class RegistryValidation
|
||||
{
|
||||
public static void ThrowIfAny(IReadOnlyList<ValidationFailure> failures)
|
||||
{
|
||||
if (failures.Count > 0) throw new ValidationException(failures);
|
||||
}
|
||||
|
||||
private static void Required(List<ValidationFailure> 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<ValidationFailure> 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<ValidationFailure> f, string field, string? value)
|
||||
{
|
||||
if (RegistryRules.HasSpecialChars(value)) f.Add(new ValidationFailure(field, RegistryMessages.SpecialChars));
|
||||
}
|
||||
|
||||
private static void Digits(List<ValidationFailure> 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)
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="tcscac"/> = 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).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ValidationFailure> ValidateTruck(SaveTruckRequest r, long? tcscac, bool isUpdate, long badiyaScac, int currentYear)
|
||||
{
|
||||
var f = new List<ValidationFailure>();
|
||||
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<ValidationFailure> ValidateTrailer(SaveTrailerRequest r, long? tcscac, bool isUpdate, long badiyaScac)
|
||||
{
|
||||
var f = new List<ValidationFailure>();
|
||||
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<ValidationFailure> ValidateDriver(SaveDriverRequest r)
|
||||
{
|
||||
var f = new List<ValidationFailure>();
|
||||
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<ValidationFailure> ValidateBlacklist(AddBlacklistRequest r)
|
||||
{
|
||||
var f = new List<ValidationFailure>();
|
||||
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<ValidationFailure> ValidateCancelBlacklist(CancelBlacklistRequest r)
|
||||
{
|
||||
var f = new List<ValidationFailure>();
|
||||
Required(f, nameof(r.Remarks), r.Remarks);
|
||||
MaxLen(f, nameof(r.Remarks), r.Remarks, 400);
|
||||
return f;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ weighbridge control (WeighbridgesControl.cfm)
|
||||
|
||||
public static IReadOnlyList<ValidationFailure> ValidateWeighbridge(SaveWeighbridgeControlRequest r)
|
||||
{
|
||||
var f = new List<ValidationFailure>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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<PagedResult<TrailerGridRowDto>> SearchAsync(TrailerListQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<TrailerDetailDto> GetAsync(long id, CancellationToken ct);
|
||||
Task<RegistryResult> CreateAsync(SaveTrailerRequest request, CancellationToken ct);
|
||||
Task<RegistryResult> UpdateAsync(long id, SaveTrailerRequest request, CancellationToken ct);
|
||||
Task<RegistryResult> AcceptAsync(long id, CancellationToken ct);
|
||||
Task<RegistryResult> RevokeAsync(long id, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of register.cfc saveTrailerDetails / editTrailerDetails / getTrailerInfo / getTrailerGrid / revokeTrailer / acceptTrailer.</summary>
|
||||
public sealed class TrailerRegistryService(
|
||||
IRegistryRepository repository,
|
||||
IRegistryAccessService access,
|
||||
IRegistryAttachmentService attachments,
|
||||
IRegistryQueuePermitService queuePermits,
|
||||
IRegistrySettingsService settings,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user) : ITrailerRegistryService
|
||||
{
|
||||
public async Task<PagedResult<TrailerGridRowDto>> 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<TrailerDetailDto> 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<RegistryResult> 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<RegistryResult> 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<RegistryResult> 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<RegistryResult> 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();
|
||||
}
|
||||
|
|
@ -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<PagedResult<TruckGridRowDto>> SearchAsync(TruckListQuery query, PageRequest page, CancellationToken ct);
|
||||
Task<TruckDetailDto> GetAsync(long id, CancellationToken ct);
|
||||
Task<IReadOnlyList<TrailerGridRowDto>> TrailersAsync(long? truckId, long? trailerId, CancellationToken ct);
|
||||
Task<RegistryResult> CreateAsync(SaveTruckRequest request, CancellationToken ct);
|
||||
Task<RegistryResult> UpdateAsync(long id, SaveTruckRequest request, CancellationToken ct);
|
||||
Task<RegistryResult> AcceptAsync(long id, CancellationToken ct);
|
||||
Task<RegistryResult> RevokeAsync(long id, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Port of register.cfc saveTrucksDetails / editTrucksDetails / getTruckInfo / getTruckGrid / revokeTruck / acceptTruck.</summary>
|
||||
public sealed class TruckRegistryService(
|
||||
IRegistryRepository repository,
|
||||
IRegistryAccessService access,
|
||||
IRegistryAttachmentService attachments,
|
||||
IRegistryQueuePermitService queuePermits,
|
||||
IRegistrySettingsService settings,
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUser user) : ITruckRegistryService
|
||||
{
|
||||
public async Task<PagedResult<TruckGridRowDto>> 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<TruckDetailDto> 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<IReadOnlyList<TrailerGridRowDto>> 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<RegistryResult> 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<RegistryResult> 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<RegistryResult> 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<RegistryResult> 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();
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
namespace NTP.Application.Grains.Reports;
|
||||
|
||||
/// <summary>Caller facts the legacy report SQL depends on (session.userrolecode / locationid / stkid / companycodeno).</summary>
|
||||
public sealed record ReportScope(string UserId, string RoleCode, long? LocationId, long? StkId, long? CompanyCodeNo);
|
||||
|
||||
/// <summary>Raw SQL rows (keys are the upper-case Oracle aliases; read them case-insensitively).</summary>
|
||||
public interface IReportsRepository
|
||||
{
|
||||
Task<IReadOnlyList<LookupItem>> CompaniesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<LookupItem>> CargoTypesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<LookupItem>> DestinationsAsync(IReadOnlyList<string> gnTypes, CancellationToken ct);
|
||||
|
||||
Task<IReadOnlyList<TripsPerCompanyRow>> TripsPerCompanyAsync(DateOnly from, DateOnly to, CancellationToken ct);
|
||||
Task<IReadOnlyList<long>> FrequencyAsync(DateOnly from, DateOnly to, string? scac, string? cargoType, CancellationToken ct);
|
||||
Task<IReadOnlyList<DetailsRow>> DetailsAsync(DateOnly from, DateOnly to, CancellationToken ct);
|
||||
Task<IReadOnlyList<WeighbridgeEventRaw>> WeighbridgeEventsAsync(DateOnly from, DateOnly to, long? locationId, CancellationToken ct);
|
||||
|
||||
/// <summary>Table reports by key (see <see cref="ReportKeys"/>). Returns the raw rows; the service shapes them.</summary>
|
||||
Task<IReadOnlyList<IDictionary<string, object?>>> TableAsync(string key, ReportFilter filter, ReportScope scope, CancellationToken ct);
|
||||
|
||||
Task<IReadOnlyList<MotMultiTripsRow>> 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<IReadOnlyList<LookupItem>> CompaniesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<LookupItem>> CargoTypesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<LookupItem>> DestinationsAsync(string? shipmentMode, CancellationToken ct);
|
||||
|
||||
Task<NumOfTripsAndTrucksReport> NumOfTripsAndTrucksAsync(DateOnly from, DateOnly to, CancellationToken ct);
|
||||
Task<QuotaReport> QuotaAsync(DateOnly from, DateOnly to, CancellationToken ct);
|
||||
Task<FrequencyReport> FrequencyAsync(DateOnly from, DateOnly to, string? scac, string? cargoType, CancellationToken ct);
|
||||
Task<DetailsReport> DetailsAsync(DateOnly from, DateOnly to, CancellationToken ct);
|
||||
Task<MotMultiTripsReport> MotMultiTripsAsync(CancellationToken ct);
|
||||
|
||||
Task<ReportTable> BuildTableAsync(string key, ReportFilter filter, CancellationToken ct);
|
||||
Task<ReportPage> PageAsync(string key, ReportFilter filter, int page, int pageSize, CancellationToken ct);
|
||||
Task<(byte[] Content, string FileName)> ExportAsync(string key, ReportFilter filter, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Excel in/out (ClosedXML in Infrastructure).</summary>
|
||||
public interface IReportExcelService
|
||||
{
|
||||
/// <summary>Builds an RTL workbook: title, filter lines, header row, rows, footer (printed by / date / count).</summary>
|
||||
byte[] Build(ReportTable table, string printedBy, DateTime printedAt, bool arabic);
|
||||
|
||||
/// <summary>Reads the first worksheet as rows of strings (used when the approvals file is .xlsx instead of .csv).</summary>
|
||||
List<string[]> ReadFirstSheet(Stream stream);
|
||||
}
|
||||
|
|
@ -0,0 +1,192 @@
|
|||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace NTP.Application.Grains.Reports;
|
||||
|
||||
/// <summary>Port of ParseFile.cfc CSVToQuery (RFC-4180 style: delimiter ',', qualifier '"', doubled qualifier escapes).</summary>
|
||||
public static class CsvReader
|
||||
{
|
||||
public static List<string[]> Parse(string text, char delimiter = ',', char qualifier = '"')
|
||||
{
|
||||
var rows = new List<string[]>();
|
||||
var row = new List<string>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>ReadFiles\parseIrbidFile.cfm / WB\cfc\ParseIrbidFile.cfc: line based weighbridge file of the Irbid/Gaban silo.</summary>
|
||||
public static class IrbidFileParser
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static List<IrbidRecord> Parse(IEnumerable<string> lines, string fileName)
|
||||
{
|
||||
var name = FileKey(fileName);
|
||||
var result = new List<IrbidRecord>();
|
||||
var vals = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>ListFirst(ListLast(fileName,'\'),'.') then (readOriginaldata / ParseIrbidFile) strip digits for the stored file name.</summary>
|
||||
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());
|
||||
}
|
||||
|
||||
/// <summary>Event timestamp sent to the WS: F4 date (yyyy-mm-dd..) + F3 time -> yyyyMMddHHmmss, "" when either is empty.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>ReadFiles\Reading\reafFilesIntoTemp.cfm: "Rsifeh" file: count line, then (id line, CSV data line) pairs.</summary>
|
||||
public static class RsifehFileParser
|
||||
{
|
||||
public static List<RsifehRecord> Parse(IEnumerable<string> 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<RsifehRecord>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>CF list semantic: comma delimited, double-quoted items may contain commas.</summary>
|
||||
private static List<string> SplitList(string line) => CsvReader.Parse(line).FirstOrDefault()?.ToList() ?? [];
|
||||
}
|
||||
|
|
@ -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
|
||||
{
|
||||
/// <summary>grains.cfc addPhoneAcceptEvent (DB part). Notification push is not ported.</summary>
|
||||
Task<PhoneActionResult> AcceptAsync(long permitId, string? remarks, string userId, CancellationToken ct);
|
||||
/// <summary>grains.cfc addPhoneRejectEvent (blacklist, queue counters, permit back to OPEN, PHRJCT event).</summary>
|
||||
Task<PhoneActionResult> RejectAsync(long permitId, int delayDays, string remarks, string userId, CancellationToken ct);
|
||||
}
|
||||
|
||||
public interface IPhoneApprovalImportService
|
||||
{
|
||||
Task<PhoneImportResult> ImportAsync(Stream file, string fileName, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class PhoneApprovalImportService(
|
||||
IPhoneApprovalRepository repo, IReportExcelService excel, IUnitOfWork uow, ICurrentUser user) : IPhoneApprovalImportService
|
||||
{
|
||||
public async Task<PhoneImportResult> ImportAsync(Stream file, string fileName, CancellationToken ct)
|
||||
{
|
||||
List<string[]> 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<PhoneImportRowResult>();
|
||||
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<bool> 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<int> StageRsifehAsync(IReadOnlyList<RsifehRecord> rows, CancellationToken ct);
|
||||
Task<int> PromoteNewRsifehAsync(string fileName, CancellationToken ct);
|
||||
|
||||
// WEIGHBRIDGE_RAW_DATA -> permits/events (jobs/getWeighbridgeEvents.cfm second half)
|
||||
Task<IReadOnlyList<RawWeighbridgeRow>> UnmatchedRawAsync(CancellationToken ct);
|
||||
Task<RawPermit?> FindPermitForRawAsync(string truckNo, CancellationToken ct);
|
||||
Task<RawPermit?> 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<FileImportResult> ImportIrbidAsync(Stream content, string fileName, CancellationToken ct);
|
||||
Task<FileImportResult> ImportOriginalAsync(Stream content, string fileName, bool replaceExisting, CancellationToken ct);
|
||||
Task<FileImportResult> ImportRsifehAsync(Stream content, string fileName, CancellationToken ct);
|
||||
/// <summary>One pass over the configured directory (what the directory watcher does for each new file).</summary>
|
||||
Task<WeighbridgeScanResult> ScanDirectoryAsync(string directory, string? archiveDirectory, CancellationToken ct);
|
||||
Task<RawSyncResult> SyncRawDataAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class WeighbridgeFileService(
|
||||
IWeighbridgeFileRepository repo, IWsService ws, IUnitOfWork uow) : IWeighbridgeFileService
|
||||
{
|
||||
/// <summary>Weighbridge location of the Irbid/Gaban file (legacy hard-coded '225' / user 'W225').</summary>
|
||||
public const long IrbidLocationId = 225;
|
||||
|
||||
private static async Task<List<string>> 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<FileImportResult> 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<string>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>true when the web-service call did not throw (the legacy never inspected errorcode). No event date -> legacy returned an empty struct (success).</summary>
|
||||
private async Task<bool> CallWs(IrbidRecord r, string eDate, List<string> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>readOriginaldata.cfm: loads a snapshot file straight into TEMP_WAYBRIDGE_IRBID (optionally replacing the table, as legacy did).</summary>
|
||||
public async Task<FileImportResult> 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<FileImportResult> 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<WeighbridgeScanResult> ScanDirectoryAsync(string directory, string? archiveDirectory, CancellationToken ct)
|
||||
{
|
||||
var results = new List<FileImportResult>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public async Task<RawSyncResult> 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,214 @@
|
|||
namespace NTP.Application.Grains.Reports;
|
||||
|
||||
/// <summary>Value/label pair for report filter drop-downs.</summary>
|
||||
public sealed record LookupItem(string Value, string Label);
|
||||
|
||||
/// <summary>Legacy GN permit codes used by the reports (legacy literals, kept in one place).</summary>
|
||||
public static class GrainsReportConstants
|
||||
{
|
||||
/// <summary>application.GN_BadiyaSCAC (individuals / "Badiya" company code, hard-coded '327' in reports.cfc).</summary>
|
||||
public const string BadiyaScac = "327";
|
||||
/// <summary>Statuses counted as "completed trips" by every trips report.</summary>
|
||||
public static readonly string[] TripStatuses = ["CLOSE", "RESD", "ACCPT", "ACTRL"];
|
||||
public const int MaxTripsBucket = 15;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ typed trips reports
|
||||
|
||||
/// <summary>One row of reports.cfc getNumOfTripsAndTrucks (numbers instead of the legacy to_char strings).</summary>
|
||||
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<TripsPerCompanyRow> 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);
|
||||
|
||||
/// <summary>Trucks by number of trips (1..15) and the derived figures used by freq / distribution / dashboard.</summary>
|
||||
public sealed record FrequencyReport(
|
||||
DateOnly From, DateOnly To,
|
||||
IReadOnlyList<long> Trucks, // index 0 => trucks that made 1 trip
|
||||
IReadOnlyList<long> Trips, // Trucks[i] * (i+1)
|
||||
IReadOnlyList<decimal> TripsPct, // Trips[i] / TotalTrips * 100
|
||||
long TotalTrucks, long TotalTrips,
|
||||
IReadOnlyList<TripGroupLine> 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<DetailsRow> Rows, decimal TotalTrips, int TruckCount);
|
||||
public sealed record DetailsReport(DateOnly From, DateOnly To, IReadOnlyList<DetailsGroup> Groups);
|
||||
|
||||
// ------------------------------------------------------------------ weighbridge events (Reports\weightbridgeEvents.cfm)
|
||||
|
||||
/// <summary>Raw join row of reports.cfc getWieghtBridgeEvents (EVENTS may be null: legacy outer join).</summary>
|
||||
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");
|
||||
|
||||
/// <summary>
|
||||
/// A tabular report: rows are dictionaries keyed by <see cref="ReportColumn.Key"/> (camelCase). Used by the grid, the
|
||||
/// Excel export and the print view alike. <c>Extra</c> carries report-specific blocks (e.g. summary tables).
|
||||
/// </summary>
|
||||
public sealed class ReportTable
|
||||
{
|
||||
public string Key { get; init; } = "";
|
||||
public string TitleAr { get; init; } = "";
|
||||
public string TitleEn { get; init; } = "";
|
||||
public IReadOnlyList<ReportColumn> Columns { get; init; } = [];
|
||||
public IReadOnlyList<IReadOnlyDictionary<string, object?>> Rows { get; init; } = [];
|
||||
public IReadOnlyList<string> FilterLines { get; init; } = [];
|
||||
public IReadOnlyDictionary<string, object?>? Extra { get; init; }
|
||||
}
|
||||
|
||||
public sealed record ReportPage(
|
||||
IReadOnlyList<IReadOnlyDictionary<string, object?>> Items, int Page, int PageSize, long TotalCount,
|
||||
IReadOnlyList<ReportColumn> Columns, IReadOnlyDictionary<string, object?>? Extra);
|
||||
|
||||
/// <summary>Filters of the table reports (only the members a given report uses are read).</summary>
|
||||
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
|
||||
|
||||
/// <summary>Row of the GRAINSPERMITS view aggregate (MotDAO.getGrainsquery).</summary>
|
||||
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<long> Trucks, IReadOnlyList<long> Trips, long TrucksTotal, long TripsTotal);
|
||||
public sealed record MotRegTypeBlock(string RegType, IReadOnlyList<MotMonthLine> Months, IReadOnlyList<long> AvgTrucksPerTrips, long AvgTrucksTotal, long TripsSum);
|
||||
public sealed record MotMultiTripsReport(
|
||||
int BucketCount, int MonthCount,
|
||||
MotRegTypeBlock Individuals, MotRegTypeBlock Companies,
|
||||
IReadOnlyList<long> ChartCompanies, IReadOnlyList<long> ChartIndividuals,
|
||||
IReadOnlyList<decimal> ChartCompaniesPct, IReadOnlyList<decimal> 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<PhoneImportRowResult> 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<string> Errors);
|
||||
|
||||
public sealed record WeighbridgeScanResult(int Files, IReadOnlyList<FileImportResult> Results);
|
||||
|
||||
/// <summary>Result of syncing WEIGHBRIDGE_RAW_DATA into permits/events (jobs/getWeighbridgeEvents.cfm second half).</summary>
|
||||
public sealed record RawSyncResult(int Candidates, int Matched, int NoPermit, int Failed);
|
||||
|
|
@ -0,0 +1,187 @@
|
|||
using System.Globalization;
|
||||
|
||||
namespace NTP.Application.Grains.Reports;
|
||||
|
||||
/// <summary>Pure calculations of Reports\TripsReports\*.cfm and the dashboard (no I/O, unit tested).</summary>
|
||||
public static class TripsReportMath
|
||||
{
|
||||
private static decimal Pct(decimal part, decimal whole) => whole == 0 ? 0 : Math.Round(part / whole * 100m, 2);
|
||||
|
||||
/// <summary>numOfTripsAndTrucksRpt.cfm: companies (everyone except Badiya) are summed, Badiya is its own row.</summary>
|
||||
public static NumOfTripsAndTrucksReport NumOfTrips(DateOnly from, DateOnly to, IReadOnlyList<TripsPerCompanyRow> 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));
|
||||
}
|
||||
|
||||
/// <summary>QuotaRpt.cfm: companies vs individuals (Badiya). Percentages are 2-decimal here (legacy showed whole numbers).</summary>
|
||||
public static QuotaReport Quota(DateOnly from, DateOnly to, IReadOnlyList<TripsPerCompanyRow> 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)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// freqOfTripRpt.cfm / TripsDistributionRpt.cfm / grainsDashboards.cfm. <paramref name="trucksByTrips"/> has 15 entries:
|
||||
/// number of trucks that made 1..15 trips (nulls from SUM() must already be 0).
|
||||
/// </summary>
|
||||
public static FrequencyReport Frequency(DateOnly from, DateOnly to, IReadOnlyList<long> 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<TripGroupLine>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>DetailsRpt.cfm: rows grouped per company with a total line (trips sum + truck count).</summary>
|
||||
public static DetailsReport Details(DateOnly from, DateOnly to, IReadOnlyList<DetailsRow> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>weightbridgeEvents.cfm: collapses the event rows of a permit into one printable line.</summary>
|
||||
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<WeighbridgeEventRow> Pivot(IEnumerable<WeighbridgeEventRaw> raw)
|
||||
{
|
||||
var result = new List<WeighbridgeEventRow>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Order label helpers of grains.cfc getOrderDetails (used by the phone-accept remark).</summary>
|
||||
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 ?? ""
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>MOT multi-trips report (GNPermitsRpt.cfm / GrainsPermitsRpt.cfm): pivot of the GRAINSPERMITS view aggregate.</summary>
|
||||
public static class MotMultiTripsBuilder
|
||||
{
|
||||
public const int Buckets = 25;
|
||||
|
||||
public static MotMultiTripsReport Build(IReadOnlyList<MotMultiTripsRow> 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<MotMultiTripsRow> rows, int monthCount)
|
||||
{
|
||||
var sel = rows.Where(r => r.RegType == reg).ToList();
|
||||
var months = new List<MotMonthLine>();
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,362 @@
|
|||
using NTP.Application.Abstractions;
|
||||
using NTP.Application.Common;
|
||||
|
||||
namespace NTP.Application.Grains.Reports;
|
||||
|
||||
/// <summary>Reports, dashboards and Excel exports of the Grains module (legacy reports.cfc + Reports\*.cfm + *.cfr).</summary>
|
||||
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<IReadOnlyList<LookupItem>> CompaniesAsync(CancellationToken ct) => repo.CompaniesAsync(ct);
|
||||
public Task<IReadOnlyList<LookupItem>> CargoTypesAsync(CancellationToken ct) => repo.CargoTypesAsync(ct);
|
||||
|
||||
/// <summary>ownersTurn.cfm lists: BULK => gn_type in (BULK, BULK_GALLAB), anything else => PCKD (EX locations, status 1).</summary>
|
||||
public Task<IReadOnlyList<LookupItem>> 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<NumOfTripsAndTrucksReport> NumOfTripsAndTrucksAsync(DateOnly from, DateOnly to, CancellationToken ct)
|
||||
{
|
||||
CheckRange(from, to);
|
||||
return TripsReportMath.NumOfTrips(from, to, await repo.TripsPerCompanyAsync(from, to, ct));
|
||||
}
|
||||
|
||||
public async Task<QuotaReport> QuotaAsync(DateOnly from, DateOnly to, CancellationToken ct)
|
||||
{
|
||||
CheckRange(from, to);
|
||||
return TripsReportMath.Quota(from, to, await repo.TripsPerCompanyAsync(from, to, ct));
|
||||
}
|
||||
|
||||
public async Task<FrequencyReport> 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));
|
||||
}
|
||||
|
||||
/// <summary>Legacy: empty or "0" means "no filter".</summary>
|
||||
private static string? Zero(string? v) => string.IsNullOrWhiteSpace(v) || v.Trim() == "0" ? null : v.Trim();
|
||||
|
||||
public async Task<DetailsReport> DetailsAsync(DateOnly from, DateOnly to, CancellationToken ct)
|
||||
{
|
||||
CheckRange(from, to);
|
||||
return TripsReportMath.Details(from, to, await repo.DetailsAsync(from, to, ct));
|
||||
}
|
||||
|
||||
public async Task<MotMultiTripsReport> 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<ReportTable> 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);
|
||||
}
|
||||
|
||||
/// <summary>GRINS_INCAPABILITY: the legacy page refuses a "to" date after yesterday.</summary>
|
||||
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<string, object?> 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<IReadOnlyDictionary<string, object?>> Project(IReadOnlyList<IDictionary<string, object?>> raw, IReadOnlyList<ReportColumn> cols)
|
||||
=> raw.Select(r => (IReadOnlyDictionary<string, object?>)cols.ToDictionary(c => c.Key, c => Get(r, c.Key))).ToList();
|
||||
|
||||
private ReportTable Shape(string key, ReportFilter f, IReadOnlyList<IDictionary<string, object?>> raw)
|
||||
{
|
||||
var period = new List<string>();
|
||||
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<string> TenderFilterLines(ReportFilter f)
|
||||
{
|
||||
var l = new List<string>();
|
||||
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<string> lines,
|
||||
IReadOnlyList<IDictionary<string, object?>> raw, ReportColumn[] cols, Action<Dictionary<string, object?>>? 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<string, object?>)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);
|
||||
|
||||
/// <summary>GRINS_INCAPABILITY (shortage = loaded net - discharged net). Net falls back to gross - tare like the weighbridge report.</summary>
|
||||
private static ReportTable Incapability(IReadOnlyList<string> period, IReadOnlyList<IDictionary<string, object?>> 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<IReadOnlyDictionary<string, object?>>();
|
||||
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<string, object?>
|
||||
{
|
||||
["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<string, object?> { ["totalShortage"] = rows.Sum(x => Num(x["shortage"])) }
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>callRpt.cfm: IVR call list (Name, Phone, Code1.. sound-file names). "DayNight" derives from MOBILE_SHIFT.</summary>
|
||||
private static ReportTable CallList(IReadOnlyList<IDictionary<string, object?>> 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<IReadOnlyDictionary<string, object?>>();
|
||||
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 };
|
||||
}
|
||||
|
||||
/// <summary>grainsOrder.cfm: first block = individuals vs companies totals, second = per destination with percentages.</summary>
|
||||
private static ReportTable OrderDistribution(ReportFilter f, IReadOnlyList<IDictionary<string, object?>> 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<IReadOnlyDictionary<string, object?>>();
|
||||
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<string, object?>
|
||||
{
|
||||
["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<string, object?>
|
||||
{
|
||||
["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<ReportTable> 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<string, object?>)new Dictionary<string, object?>
|
||||
{
|
||||
["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<ReportPage> 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");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
using System.Globalization;
|
||||
|
||||
namespace NTP.Application.Grains.Reports;
|
||||
|
||||
/// <summary>Weighbridge transaction codes of ws.cfc addWeightBridgeEvent (errorcode 0..4).</summary>
|
||||
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 = "الموقع غير موجود على مسار الشاحنة";
|
||||
}
|
||||
|
||||
/// <summary>The decision table of ws.cfc addWeightBridgeEvent (pure: unit tested).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <paramref name="generic"/> = true (errorcode 4).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Accepts the legacy "yyyymmdd HH24miss" and the compact "yyyymmddHH24miss" (what grains.cfc sends).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>grains.cfc generatePermitNumber.</summary>
|
||||
public static class PermitNumber
|
||||
{
|
||||
private static string Pad(long n, int width) => n.ToString(CultureInfo.InvariantCulture).PadLeft(width, '0');
|
||||
|
||||
/// <summary>Returns null for a cargo type other than BULK/PCKD (legacy left PN empty).</summary>
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -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<string, object?>? Data = null);
|
||||
|
||||
/// <summary>ws.cfc addWeightBridgeEvent: errorcode "0".."4" + Arabic MSG (kept verbatim for the integrating systems).</summary>
|
||||
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<QueuedPermit?> FindQueuedAsync(string tn, CancellationToken ct);
|
||||
/// <summary>grains.cfc getNextTrackingNo: first of the next 7 days where quota is not exhausted (trackNo 0 when none).</summary>
|
||||
Task<(long TrackNo, string QueueDate)> NextTrackingNoAsync(CancellationToken ct);
|
||||
Task<long> InsertQueuedPermitAsync(string tn, string trnat, long pn, string queueDate, CancellationToken ct);
|
||||
|
||||
Task<IReadOnlyList<long>> OpenPermitIdsAsync(string tn, CancellationToken ct);
|
||||
Task<int> UpdateStatusByTnAsync(string tn, string fromStatus, string toStatus, string user, CancellationToken ct);
|
||||
|
||||
Task<string?> TruckCompanyIfRegisteredAsync(string tn, CancellationToken ct);
|
||||
Task<bool> HasActivePermitAsync(string tn, string tt, bool checkAllStatuses, CancellationToken ct);
|
||||
Task<long> NextQueueSequenceAsync(bool badiya, CancellationToken ct);
|
||||
Task<long> TripCounterAsync(string tt, CancellationToken ct);
|
||||
Task<long> TenderCountAsync(CancellationToken ct);
|
||||
Task<long> InsertPermitAsync(NewPermit p, CancellationToken ct);
|
||||
|
||||
Task<bool> PermitExistsAsync(long pid, CancellationToken ct);
|
||||
Task UpdatePermitStatusAsync(long pid, string status, string user, CancellationToken ct);
|
||||
Task<long?> PermitIdByPnAsync(string pn, CancellationToken ct);
|
||||
Task UpdateShipmentModeAsync(long pid, string cargoType, CancellationToken ct);
|
||||
|
||||
Task<WbPermit?> 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<WsResult> GetTrackNoAsync(GetTrackNoRequest r, string caller, CancellationToken ct);
|
||||
Task<WsResult> ChangeStatusToReqstAsync(ChangeStatusToReqstRequest r, string caller, CancellationToken ct);
|
||||
Task<WsResult> SaveShipmentInfoAsync(SaveShipmentInfoRequest r, string caller, CancellationToken ct);
|
||||
Task<WsResult> AddLoadingWeightEventAsync(LoadingWeightRequest r, string caller, CancellationToken ct);
|
||||
Task<WsResult> AddDischargeWeightEventAsync(LoadingWeightRequest r, string caller, CancellationToken ct);
|
||||
Task<WsResult> CreatePermitRecordAsync(CreatePermitRecordRequest r, string caller, CancellationToken ct);
|
||||
/// <summary>addWeightBridgeEventWS: logs the call to GN_TCS_INTEGRATION first, then runs the same logic.</summary>
|
||||
Task<WbEventResult> AddWeightBridgeEventWsAsync(WeighbridgeEventRequest r, string caller, string? remoteIp, CancellationToken ct);
|
||||
/// <summary>addWeightBridgeEvent (public, used by the screens and the file importers).</summary>
|
||||
Task<WbEventResult> AddWeightBridgeEventAsync(WeighbridgeEventRequest r, CancellationToken ct);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ validators
|
||||
|
||||
public sealed class GetTrackNoRequestValidator : AbstractValidator<GetTrackNoRequest>
|
||||
{
|
||||
public GetTrackNoRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.TN).NotEmpty().MaximumLength(20);
|
||||
RuleFor(x => x.TRNAT).NotEmpty().MaximumLength(20);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class WeighbridgeEventRequestValidator : AbstractValidator<WeighbridgeEventRequest>
|
||||
{
|
||||
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<LoadingWeightRequest>
|
||||
{
|
||||
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
|
||||
|
||||
/// <summary>
|
||||
/// Port of ws.cfc. The caller id replaces legacy session.userid (default "system"): JWT user id or the API-key name.
|
||||
/// </summary>
|
||||
public sealed class WsService(
|
||||
IWsRepository repo, IEventLogger events, IUnitOfWork uow,
|
||||
IValidator<GetTrackNoRequest> trackNoValidator,
|
||||
IValidator<WeighbridgeEventRequest> wbValidator,
|
||||
IValidator<LoadingWeightRequest> 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<WsResult> 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",
|
||||
$"الشاحنة لديها طلب أخر<br>رقم الدور {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<string, object?> { ["permitId"] = id, ["pn"] = trackNo, ["queueDate"] = queueDate });
|
||||
}, ct);
|
||||
}
|
||||
|
||||
public async Task<WsResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>Commented out in the legacy ws.cfc (PH domain, 'WEIGH' event); ported for completeness, see the controller gate.</summary>
|
||||
public async Task<WsResult> 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<WsResult> AddLoadingWeightEventAsync(LoadingWeightRequest r, string caller, CancellationToken ct) =>
|
||||
WeightEvents(r, caller, ("LTW", "LGW", "LNW"), "RESD", "ACTRL", ct);
|
||||
|
||||
public Task<WsResult> AddDischargeWeightEventAsync(LoadingWeightRequest r, string caller, CancellationToken ct) =>
|
||||
WeightEvents(r, caller, ("DTW", "DGW", "DNW"), "ACTRL", "CLOSE", ct);
|
||||
|
||||
private async Task<WsResult> 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<WsResult> 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<string, object?> { ["permitId"] = id, ["pn"] = pn });
|
||||
}, ct);
|
||||
}
|
||||
|
||||
public async Task<WbEventResult> 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<WbEventResult> 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
namespace NTP.Application.Lookups;
|
||||
|
||||
/// <summary>STATUS row (CODE, DESCRIPTION, DOMAIN, ISACTIVE).</summary>
|
||||
public sealed class StatusDto
|
||||
{
|
||||
public string Code { get; set; } = string.Empty;
|
||||
public string? Description { get; set; }
|
||||
public int? IsActive { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>LOCATIONS row (ID, NAME, TYPE, DOMAIN). Types seen: LOC, EX (exit/destination), EN (entry).</summary>
|
||||
public sealed class LocationDto
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Type { get; set; }
|
||||
public string? Domain { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>CARGOTYPE row (ID, NAME, DOMAIN).</summary>
|
||||
public sealed class CargoTypeDto
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Domain { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>COMPANIES row. Code is COMPANIES.DESCRIPTION (legacy "companyCode").</summary>
|
||||
public sealed class CompanyDto
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Code { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>NATIONALITY (LANGID = 0) row.</summary>
|
||||
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<IReadOnlyList<StatusDto>> GetStatusesAsync(string domain, bool? isActive, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<LocationDto>> GetLocationsAsync(string domain, string? type, bool includeInactive, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<CargoTypeDto>> GetCargoTypesAsync(string domain, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<CompanyDto>> GetCompaniesAsync(bool includeInactive, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<NationalityDto>> GetNationalitiesAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<CityDto>> GetCitiesAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
using NTP.Application.Abstractions;
|
||||
|
||||
namespace NTP.Application.Lookups;
|
||||
|
||||
public interface ILookupService
|
||||
{
|
||||
Task<IReadOnlyList<StatusDto>> StatusesAsync(string? domain, bool? isActive, CancellationToken ct);
|
||||
Task<IReadOnlyList<LocationDto>> LocationsAsync(string? domain, string? type, bool includeInactive, CancellationToken ct);
|
||||
Task<IReadOnlyList<CargoTypeDto>> CargoTypesAsync(string? domain, CancellationToken ct);
|
||||
Task<IReadOnlyList<CompanyDto>> CompaniesAsync(bool includeInactive, CancellationToken ct);
|
||||
Task<IReadOnlyList<NationalityDto>> NationalitiesAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<CityDto>> CitiesAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Generic lookups. Domain defaults to the caller's domain (legacy session.domain).</summary>
|
||||
public sealed class LookupService(ILookupRepository repository, ICurrentUser user) : ILookupService
|
||||
{
|
||||
private string DomainOrCurrent(string? domain) =>
|
||||
string.IsNullOrWhiteSpace(domain) ? user.Domain : domain.Trim().ToUpperInvariant();
|
||||
|
||||
public Task<IReadOnlyList<StatusDto>> StatusesAsync(string? domain, bool? isActive, CancellationToken ct) =>
|
||||
repository.GetStatusesAsync(DomainOrCurrent(domain), isActive, ct);
|
||||
|
||||
public Task<IReadOnlyList<LocationDto>> LocationsAsync(string? domain, string? type, bool includeInactive, CancellationToken ct) =>
|
||||
repository.GetLocationsAsync(DomainOrCurrent(domain), string.IsNullOrWhiteSpace(type) ? null : type.Trim().ToUpperInvariant(), includeInactive, ct);
|
||||
|
||||
public Task<IReadOnlyList<CargoTypeDto>> CargoTypesAsync(string? domain, CancellationToken ct) =>
|
||||
repository.GetCargoTypesAsync(DomainOrCurrent(domain), ct);
|
||||
|
||||
public Task<IReadOnlyList<CompanyDto>> CompaniesAsync(bool includeInactive, CancellationToken ct) =>
|
||||
repository.GetCompaniesAsync(includeInactive, ct);
|
||||
|
||||
public Task<IReadOnlyList<NationalityDto>> NationalitiesAsync(CancellationToken ct) => repository.GetNationalitiesAsync(ct);
|
||||
|
||||
public Task<IReadOnlyList<CityDto>> CitiesAsync(CancellationToken ct) => repository.GetCitiesAsync(ct);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue