From 1b3a8500ab3f18658f6cf3cea7732871b38573d4 Mon Sep 17 00:00:00 2001 From: Samer Salameh Date: Sun, 15 Nov 2026 12:24:04 +0300 Subject: [PATCH] DISP role: view tender-order permits of own company; permit edit dialog (trailer and driver only, validate on Enter) Co-Authored-By: Claude Sonnet 5.5 --- Jenkinsfile | 116 ++++++++++++++ db/disp-permits-screen.sql | 9 ++ deploy/prod/.env.example | 8 +- deploy/prod/docker-compose.yml | 5 +- .../Access/PermissionDefaults.cs | 2 +- .../Grains/Permits/PermitSupport.cs | 8 +- .../features/grains-permits/meta/permits.tsx | 2 +- web/src/features/grains-permits/pages.tsx | 147 +++++++++++------- web/src/features/grains-permits/strings.ts | 3 +- 9 files changed, 232 insertions(+), 68 deletions(-) create mode 100644 Jenkinsfile create mode 100644 db/disp-permits-screen.sql diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..17a38dc --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,116 @@ +// Build the NTP V2 image (API + web app), push it to the Docker registry, then have the production +// server pull that image and restart the container. Dockerfile: deploy/qa/Dockerfile (WEB_MODE=build:prod). +// +// Jenkins prerequisites +// - Agent with Docker and ssh/scp (label below), user allowed to run docker. +// - Credentials: +// docker-registry Username with password (push access to the registry) +// prod-ssh SSH username with private key (user on the production server, able to run docker) +// - On the production server: Docker + compose plugin, folder DEPLOY_DIR containing a filled-in .env +// (copy of deploy/prod/.env.example). The pipeline copies docker-compose.yml there on every deploy. +pipeline { + agent { label 'docker' } + + parameters { + string(name: 'REGISTRY', defaultValue: 'registry.nafith.net', description: 'Docker registry host[:port]') + string(name: 'IMAGE_REPO', defaultValue: 'ntpv2', description: 'Repository/name inside the registry') + string(name: 'PROD_HOST', defaultValue: 'prod-server.nafith.net', description: 'Production server host or IP') + string(name: 'DEPLOY_DIR', defaultValue: '/opt/ntpv2', description: 'Folder on the production server holding .env') + booleanParam(name: 'DEPLOY', defaultValue: true, description: 'Deploy to production after pushing the image') + } + + options { + timestamps() + disableConcurrentBuilds() + buildDiscarder(logRotator(numToKeepStr: '20')) + timeout(time: 45, unit: 'MINUTES') + } + + environment { + IMAGE = "${params.REGISTRY}/${params.IMAGE_REPO}" + TAG = "${env.BUILD_NUMBER}" + } + + stages { + stage('Checkout') { + steps { checkout scm } + } + + stage('Build image') { + // Compiles the .NET API and the React app inside the Dockerfile (no SDKs needed on the agent). + steps { + sh ''' + docker build \ + -f deploy/qa/Dockerfile \ + --build-arg WEB_MODE=build:prod \ + -t "$IMAGE:$TAG" -t "$IMAGE:latest" . + ''' + } + } + + stage('Push image') { + steps { + withCredentials([usernamePassword(credentialsId: 'docker-registry', usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS')]) { + sh ''' + echo "$REG_PASS" | docker login "$REGISTRY" -u "$REG_USER" --password-stdin + docker push "$IMAGE:$TAG" + docker push "$IMAGE:latest" + docker logout "$REGISTRY" + ''' + } + } + } + + stage('Deploy to production') { + when { expression { params.DEPLOY } } + steps { + // Manual gate; remove if every successful build should go straight to production. + input message: "Deploy ${env.IMAGE}:${env.TAG} to ${params.PROD_HOST}?", ok: 'Deploy' + withCredentials([ + sshUserPrivateKey(credentialsId: 'prod-ssh', keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER'), + usernamePassword(credentialsId: 'docker-registry', usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS') + ]) { + sh ''' + SSH_OPTS="-i $SSH_KEY -o StrictHostKeyChecking=accept-new" + TARGET="$SSH_USER@$PROD_HOST" + + scp $SSH_OPTS deploy/prod/docker-compose.yml "$TARGET:$DEPLOY_DIR/docker-compose.yml" + + # registry password goes over stdin so it never appears in a command line or the build log + echo "$REG_PASS" | ssh $SSH_OPTS "$TARGET" \ + "docker login '$REGISTRY' -u '$REG_USER' --password-stdin \ + && cd '$DEPLOY_DIR' \ + && export NTP_IMAGE='$IMAGE:$TAG' \ + && docker compose pull \ + && docker compose up -d --no-build \ + && docker image prune -f \ + && docker logout '$REGISTRY'" + ''' + } + } + } + + stage('Smoke test') { + when { expression { params.DEPLOY } } + steps { + withCredentials([sshUserPrivateKey(credentialsId: 'prod-ssh', keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER')]) { + // The container only listens on 127.0.0.1:8081 on the server, so check from there. + sh ''' + ssh -i "$SSH_KEY" -o StrictHostKeyChecking=accept-new "$SSH_USER@$PROD_HOST" \ + 'for i in $(seq 1 15); do + code=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:8081/) && [ "$code" -lt 500 ] && [ "$code" != 000 ] && exit 0 + sleep 4 + done + docker logs --tail 50 ntpv2-prod; exit 1' + ''' + } + } + } + } + + post { + success { echo "Deployed ${env.IMAGE}:${env.TAG}" } + failure { echo 'Pipeline failed - see the stage log above.' } + always { sh 'docker image prune -f || true' } + } +} diff --git a/db/disp-permits-screen.sql b/db/disp-permits-screen.sql new file mode 100644 index 0000000..20ee5a8 --- /dev/null +++ b/db/disp-permits-screen.sql @@ -0,0 +1,9 @@ +-- Role DISP (company dispatcher): view ارسالية عطاء التموين (grains.permits.list). +-- The API restricts a DISP user to the permits of his own company (user company code), like a company user. +-- Run once by a DBA on NAFITHTCS (safe to re-run). Needs db/grains-screen-permissions.sql applied first. +MERGE INTO GRAINS_SCREEN_PERMISSIONS t +USING (SELECT 'DISP' AS ROLECODE, 'grains.permits.list' AS RESOURCE_KEY FROM DUAL) s +ON (t.ROLECODE = s.ROLECODE AND t.RESOURCE_KEY = s.RESOURCE_KEY) +WHEN NOT MATCHED THEN INSERT (ROLECODE, RESOURCE_KEY) VALUES (s.ROLECODE, s.RESOURCE_KEY); + +COMMIT; diff --git a/deploy/prod/.env.example b/deploy/prod/.env.example index 4aa3363..c7acb04 100644 --- a/deploy/prod/.env.example +++ b/deploy/prod/.env.example @@ -1,10 +1,10 @@ # Copy to .env on the production server (git-ignored, chmod 600) and fill in. See docs/ENVIRONMENTS.md. # The API refuses to start while a connection string or Jwt__Key is missing, so fill these in before `docker compose up`. -ConnectionStrings__NAFITHTCS=User Id=ntp;Password=zaPRFN$do36;Data Source=10.20.1.7:1521/nafithmain;Min Pool Size=5;Max Pool Size=100;Connection Timeout=15;Statement Cache Size=50 -ConnectionStrings__NtpSchema=User Id=nafithtcs;Password=sLDDo83@fs;Data Source=10.20.1.7:1521/nafithmain;Min Pool Size=5;Max Pool Size=100;Connection Timeout=15;Statement Cache Size=50 +ConnectionStrings__NAFITHTCS=User Id=;Password=;Data Source=:1521/;Min Pool Size=5;Max Pool Size=100;Connection Timeout=15;Statement Cache Size=50 +ConnectionStrings__NtpSchema=User Id=;Password=;Data Source=:1521/;Min Pool Size=5;Max Pool Size=100;Connection Timeout=15;Statement Cache Size=50 # at least 32 random characters, a NEW value for production (openssl rand -base64 48) -Jwt__Key=ItSCgUNhyCt1ZuYaJigPr9HDgSNR3eo/3v6eXp8OSWI+6OEW55E417QmCbpNzqb/ +Jwt__Key= # origin users open in the browser, exactly as typed in the address bar -Cors__AllowedOrigins__0=https://ntpv2.nafith.net +Cors__AllowedOrigins__0=https:// # logins that may hold role SU (none by default in production), e.g. Auth__SuperUsers__0=login # NTP_PORT=8081 diff --git a/deploy/prod/docker-compose.yml b/deploy/prod/docker-compose.yml index 48e0962..7df4cb5 100644 --- a/deploy/prod/docker-compose.yml +++ b/deploy/prod/docker-compose.yml @@ -3,11 +3,12 @@ # Run from this folder after creating .env (copy .env.example): docker compose up -d --build services: ntp: - image: ntpv2:prod + # Jenkins sets NTP_IMAGE to /ntpv2:; the production server only pulls it (docker compose pull). + image: ${NTP_IMAGE:-ntpv2:prod} container_name: ntpv2-prod build: context: ../.. - dockerfile: deploy/prod/Dockerfile + dockerfile: deploy/qa/Dockerfile args: WEB_MODE: build:prod restart: unless-stopped diff --git a/src/NTP.Application/Access/PermissionDefaults.cs b/src/NTP.Application/Access/PermissionDefaults.cs index 68614e1..1530cb7 100644 --- a/src/NTP.Application/Access/PermissionDefaults.cs +++ b/src/NTP.Application/Access/PermissionDefaults.cs @@ -81,7 +81,7 @@ public static class PermissionDefaults { public static readonly IReadOnlyDictionary RolesByResource = new Dictionary(StringComparer.OrdinalIgnoreCase) { - [PermissionKeys.PermitsList] = ["GTO", "GGO", "GOO", "GPO"], // ارسالية عطاء التموين + [PermissionKeys.PermitsList] = ["GTO", "GGO", "GOO", "GPO", "DISP"], // ارسالية عطاء التموين (DISP: own company only) [PermissionKeys.RegistryTrucks] = ["GTO", "GOO", "GPO"], // شاشة القاطرات [PermissionKeys.RegistryTrailers] = ["GTO", "GOO", "GPO"], // شاشة المقطورات [PermissionKeys.RegistryDrivers] = ["GTO", "GOO", "GPO"], // شاشة السائقين المسجلين diff --git a/src/NTP.Application/Grains/Permits/PermitSupport.cs b/src/NTP.Application/Grains/Permits/PermitSupport.cs index 549f464..9d3f4c1 100644 --- a/src/NTP.Application/Grains/Permits/PermitSupport.cs +++ b/src/NTP.Application/Grains/Permits/PermitSupport.cs @@ -26,9 +26,13 @@ public static class GrainsRoles /// Helpers that replace legacy session.* lookups. public static class PermitUserContext { - /// session.stkid = 62: a trucking company user (sees and changes only its own permits). + /// Role code of a company dispatcher: sees and changes only the permits of its own company. + public const string DispatcherRole = "DISP"; + + /// session.stkid = 62 (a trucking company user) or a DISP dispatcher: sees and changes only its own company's permits. public static bool IsCompany(this ICurrentUser user, GrainsPermitsOptions options) => - user.StkId == options.CompanyStakeholderId; + user.StkId == options.CompanyStakeholderId + || string.Equals(user.RoleCode, DispatcherRole, StringComparison.OrdinalIgnoreCase); /// session.companyCodeNO = mid(CompanyCode, 4, 6) * 1; null when the user has no company code. public static long? CompanyCodeNo(this ICurrentUser user) => ParseCompanyCodeNo(user.CompanyCode); diff --git a/web/src/features/grains-permits/meta/permits.tsx b/web/src/features/grains-permits/meta/permits.tsx index 084f8b5..e91a8ab 100644 --- a/web/src/features/grains-permits/meta/permits.tsx +++ b/web/src/features/grains-permits/meta/permits.tsx @@ -41,7 +41,7 @@ export interface PermitGridHandlers { const actionLabels: Record = { view: { en: 'View', ar: 'مشاهدة' }, - submit: { en: 'Submit order', ar: 'تقديم الطلب' }, + submit: { en: 'Edit information', ar: 'تعديل المعلومات' }, edit: { en: 'Edit information', ar: 'تعديل المعلومات' }, accept: { en: 'Confirm turn', ar: 'تثبيت الدور' }, reject: { en: 'Revoke confirmation', ar: 'الغاء التثبيت' }, diff --git a/web/src/features/grains-permits/pages.tsx b/web/src/features/grains-permits/pages.tsx index 8341fe4..8b5c124 100644 --- a/web/src/features/grains-permits/pages.tsx +++ b/web/src/features/grains-permits/pages.tsx @@ -1,5 +1,5 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; -import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { Alert, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, GlobalStyles, MenuItem, Stack, Tab, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Tabs, TextField, Typography, @@ -10,7 +10,6 @@ import BadgeIcon from '@mui/icons-material/Badge'; import BlockIcon from '@mui/icons-material/Block'; import CancelOutlinedIcon from '@mui/icons-material/CancelOutlined'; import CheckCircleOutlinedIcon from '@mui/icons-material/CheckCircleOutlined'; -import CloseIcon from '@mui/icons-material/Close'; import EditIcon from '@mui/icons-material/Edit'; import HistoryIcon from '@mui/icons-material/History'; import LocalShippingIcon from '@mui/icons-material/LocalShipping'; @@ -45,7 +44,7 @@ import { useAuth } from '@/providers/AuthProvider'; import { useConfirm } from '@/providers/ConfirmProvider'; import { useToast } from '@/providers/ToastProvider'; import { - fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, fetchTruck, searchDestination, searchTruckDistribution, + fetchAllowedDestinations, fetchDriver, fetchOrdersForPermit, fetchTrailer, searchDestination, searchTruckDistribution, useActivateOrders, useActivation, useAddToQueue, useAssignByPn, useClosePermit, useDistribute, useDistributionPivot, useDistributionSummary, useLocationGroups, useManualInput, useOrderDates, usePermitAction, usePermitDetail, usePrintAccept, usePrintIn, usePrintOut, useProcessOpen, useProcessOpenWithDestination, @@ -170,7 +169,7 @@ function usePermitActions() { const ask = async (key: Parameters[0], danger = false) => confirm({ message: t(key), danger }); switch (action) { case 'view': navigate(`/grains/permits/${id}`); break; - case 'submit': case 'edit': navigate(`/grains/permits/${id}`); break; + case 'submit': case 'edit': navigate(`/grains/permits/${id}`, { state: { edit: true } }); break; // opens the edit form case 'accept': if (await ask('pm.confirm.accept')) accept.mutate({ id }); break; case 'reject': if (await ask('pm.confirm.revoke', true)) revoke.mutate({ id }); break; case 'revokeAccepted': if (await ask('pm.confirm.revokeAccepted', true)) revokeAccepted.mutate({ id }); break; @@ -273,18 +272,34 @@ export function PermitDetailPage() { const confirm = useConfirm(); const toast = useToast(); const [v, setV] = useState(emptyOrder); - const [info, setInfo] = useState<{ truck?: string; trailer?: string }>({}); - const [loaded, setLoaded] = useState(false); - const [editing, setEditing] = useState(false); // the edit / submit form opens from the header button + // The edit form is a dialog opened by the header button or by the row action (router state { edit: true }). + const location = useLocation(); + const [editing, setEditing] = useState(() => !!(location.state as { edit?: boolean } | null)?.edit); + // Looked-up data of the trailer / driver typed in the form. undefined = unchanged (the permit's own data), null = not found. + // 'pending' = the id was changed but not validated yet (validated when Enter is pressed). + const [trailerLook, setTrailerLook] = useState> | null | undefined | 'pending'>(undefined); + const [driverLook, setDriverLook] = useState> | null | undefined | 'pending'>(undefined); const d = detail.data; - if (d && !loaded) { - setLoaded(true); + const openEdit = () => { + if (!d) return; setV({ tn: d.truck?.tn ?? '', trn: d.trailer?.tn ?? '', nnpn: d.driver?.nnpn ?? '', name: d.driver?.name ?? '', dln: d.driver?.dln ?? '', dled: d.driver?.dled ?? '', opType: d.operationTypeCode ?? 'IMPT', }); - } + setTrailerLook(undefined); + setDriverLook(undefined); + setEditing(true); + }; + // opened straight from the list: fill the form once the permit has loaded + const [filled, setFilled] = useState(false); + if (d && editing && !filled) { setFilled(true); openEdit(); } + + const trnTyped = v.trn.trim(); + const nnpnTyped = v.nnpn.trim(); + const ownTrn = d?.trailer?.tn ?? ''; + const ownNnpn = d?.driver?.nnpn ?? ''; + if (detail.isLoading) return ; if (!d) return ; @@ -293,33 +308,44 @@ export function PermitDetailPage() { const editable = canSubmit || canEdit; const set = (k: keyof OrderValues) => (e: { target: { value: string } }) => setV((p) => ({ ...p, [k]: e.target.value })); - async function lookupTruck() { - if (!v.tn) return; - try { - const r = await fetchTruck(v.tn.trim()); - setInfo((p) => ({ ...p, truck: r ? `${r.chasesNumber ?? ''} ${r.axials ?? ''}`.trim() : t('pm.order.notRegistered') })); - } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } - } - async function lookupTrailer() { - if (!v.trn) return; - try { - const r = await fetchTrailer(v.trn.trim()); - setInfo((p) => ({ ...p, trailer: r ? `${r.chasesNumber ?? ''} ${r.axials ?? ''}`.trim() : t('pm.order.notRegistered') })); - } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } - } - async function lookupDriver() { - if (!v.nnpn) return; - try { - const r = await fetchDriver(v.nnpn.trim()); - if (r) setV((p) => ({ ...p, name: r.name ?? '', dln: r.dln ?? '', dled: r.dled ?? '' })); - else toast.warning(t('pm.order.driverMissing')); - } catch (e) { toast.error(e instanceof Error ? e.message : t('error.generic')); } - } + // what the form shows read-only for the typed trailer / driver + const trailerShown = trailerLook === 'pending' ? null : trailerLook === undefined ? d.trailer : trailerLook; + const driverShown = driverLook === 'pending' ? null : driverLook === undefined ? d.driver : driverLook; - const complete = !!(v.tn && v.trn && v.nnpn && v.name && v.dln && (canEdit && !canSubmit ? true : v.opType)); + // Changing the trailer number / driver id clears the related data; Enter validates it and fills the data in. + const changeTrailer = (e: { target: { value: string } }) => { + const x = e.target.value; + setV((p) => ({ ...p, trn: x })); + setTrailerLook(x.trim() === ownTrn ? undefined : 'pending'); + }; + const changeDriver = (e: { target: { value: string } }) => { + const x = e.target.value; + setV((p) => ({ ...p, nnpn: x })); + setDriverLook(x.trim() === ownNnpn ? undefined : 'pending'); + }; + async function checkTrailer() { + if (!trnTyped || trailerLook !== 'pending') return; + try { setTrailerLook((await fetchTrailer(trnTyped)) ?? null); } + catch (e) { setTrailerLook(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } + } + async function checkDriver() { + if (!nnpnTyped || driverLook !== 'pending') return; + try { setDriverLook((await fetchDriver(nnpnTyped)) ?? null); } + catch (e) { setDriverLook(null); toast.error(e instanceof Error ? e.message : t('error.generic')); } + } + const onEnter = (run: () => Promise) => (e: { key: string; preventDefault: () => void }) => { + if (e.key === 'Enter') { e.preventDefault(); void run(); } + }; + const fdate = (x: string | null | undefined) => (x ? formatDate(x, lang) || x : ''); + + const complete = !!(trnTyped && nnpnTyped && trailerShown && driverShown?.name && driverShown.dln && (canEdit && !canSubmit ? true : v.opType)); async function save() { - if (!complete || !(await confirm({ message: t(canSubmit ? 'pm.confirm.submit' : 'pm.confirm.update') }))) return; - const body = { tn: v.tn.trim(), trn: v.trn.trim(), nnpn: v.nnpn.trim(), dln: v.dln.trim(), dled: v.dled || null, name: v.name.trim() }; + if (!complete || !driverShown || !(await confirm({ message: t(canSubmit ? 'pm.confirm.submit' : 'pm.confirm.update') }))) return; + // the truck never changes here; the driver data is the looked-up (or the permit's own) data of the typed id + const body = { + tn: (d?.truck?.tn ?? v.tn).trim(), trn: trnTyped, nnpn: nnpnTyped, dln: (driverShown.dln ?? '').trim(), + dled: driverShown.dled || null, name: (driverShown.name ?? '').trim(), + }; const done = { onSuccess: () => setEditing(false) }; if (canSubmit) submit.mutate({ id, body: { ...body, opType: v.opType } }, done); else update.mutate({ id, body }, done); @@ -339,8 +365,8 @@ export function PermitDetailPage() { const headerActions = ( <> {editable && ( - )} {others.map((a) => ( @@ -402,32 +428,39 @@ export function PermitDetailPage() { - {editable && editing && ( - - - - void lookupTruck()} - helperText={info.truck} slotProps={ltr} /> - void lookupTrailer()} - helperText={info.trailer} slotProps={ltr} /> - void lookupDriver()} slotProps={ltr} /> - - - - {canSubmit && ( + setEditing(false)} fullWidth maxWidth="sm"> + {t(canSubmit ? 'pm.order.submitTitle' : 'pm.order.editTitle')} + + + {/* the truck is fixed; only the trailer number and the driver id can change, the rest follows from them */} + + {canSubmit && !d.operationTypeCode ? ( {lang === 'ar' ? 'محمل' : 'Loaded'} {lang === 'ar' ? 'فارغ' : 'Empty'} + ) : ( + )} + + + + + + + + + + - - - - - - )} + + + + + + diff --git a/web/src/features/grains-permits/strings.ts b/web/src/features/grains-permits/strings.ts index 45ac12d..0434ce0 100644 --- a/web/src/features/grains-permits/strings.ts +++ b/web/src/features/grains-permits/strings.ts @@ -58,7 +58,8 @@ export default defineStrings({ 'pm.detail.truck': { en: 'Truck', ar: 'القاطرة' }, 'pm.detail.trailer': { en: 'Trailer', ar: 'المقطورة' }, 'pm.detail.driver': { en: 'Driver', ar: 'السائق' }, - 'pm.order.submitTitle': { en: 'Submit the order', ar: 'تقديم الطلب' }, + 'pm.order.submitTitle': { en: 'Edit information', ar: 'تعديل المعلومات' }, + 'pm.order.pressEnter': { en: 'Press Enter to validate', ar: 'اضغط Enter للتحقق' }, 'pm.order.editTitle': { en: 'Edit information', ar: 'تعديل المعلومات' }, 'pm.order.pn': { en: 'Permit no.', ar: 'رقم الارسالية' }, 'pm.order.tn': { en: 'Truck no.', ar: 'رقم القاطرة' },