train gate pass, Telebirr and Wafi

This commit is contained in:
hagiye
2026-07-01 16:23:52 +03:00
parent 38db9a4177
commit 14a00af341
41 changed files with 2807 additions and 151 deletions

View File

@@ -9,6 +9,8 @@ import {
RingProgress,
Stack,
Text,
Textarea,
TextInput,
ThemeIcon,
Title,
} from "@mantine/core";
@@ -88,6 +90,10 @@ export default function TrainScheduleV2DetailPage() {
const [previewResult, setPreviewResult] = useState<TrainSchedulePreviewResponse | null>(null);
const [containerPlacements, setContainerPlacements] = useState<ContainerPlacement[]>([]);
const [maintenanceOpen, setMaintenanceOpen] = useState(false);
const [gatepassSecuredAt, setGatepassSecuredAt] = useState("");
const [gatepassReference, setGatepassReference] = useState("");
const [gatepassFileUrl, setGatepassFileUrl] = useState("");
const [gatepassNotes, setGatepassNotes] = useState("");
const autoPreviewedRef = useRef(false);
const detailQuery = useQuery(
@@ -98,6 +104,42 @@ export default function TrainScheduleV2DetailPage() {
);
const schedule = detailQuery.data;
const freightType: FreightType | undefined = schedule?.freightType as FreightType | undefined;
const isDjiboutiPort = (value?: string | null) =>
["DJIBOUTI", "DORALEH", "DMP", "DCT", "NAGAD"].some((token) =>
(value ?? "").toUpperCase().includes(token),
);
const gatepassApplies = Boolean(
schedule &&
((schedule.direction === "IMPORT" &&
isDjiboutiPort(`${schedule.originStation?.code ?? ""} ${schedule.originStation?.label ?? ""}`)) ||
(schedule.direction === "EXPORT" &&
isDjiboutiPort(`${schedule.destinationStation?.code ?? ""} ${schedule.destinationStation?.label ?? ""}`))),
);
const gatepassQuery = useQuery({
queryKey: ["train-scheduling", "gatepass", scheduleId],
queryFn: () => trainSchedulingService.getImportDjiboutiOperation(scheduleId as string),
enabled: Boolean(scheduleId && gatepassApplies),
});
const secureGatepass = useMutation({
mutationFn: () =>
trainSchedulingService.grantImportDjiboutiGatepass(scheduleId as string, {
securedAt: gatepassSecuredAt ? new Date(gatepassSecuredAt).toISOString() : undefined,
reference: gatepassReference.trim() || undefined,
fileUrl: gatepassFileUrl.trim() || undefined,
notes: gatepassNotes.trim() || undefined,
}),
onSuccess: () => {
toast({ title: "Gate pass secured" });
void gatepassQuery.refetch();
},
onError: (error) => {
toast({
title: "Gate pass failed",
description: parseError(error, "Could not secure gate pass"),
variant: "destructive",
});
},
});
const eligibleFilters = useMemo(
() =>
@@ -133,6 +175,16 @@ export default function TrainScheduleV2DetailPage() {
: trainSchedulingService.downloadImportDjiboutiLoadListDocument(id),
});
useEffect(() => {
const operation = gatepassQuery.data;
if (!operation) return;
const secured = operation.gatepassSecuredAt ?? operation.gatepassGrantedAt;
setGatepassSecuredAt(secured ? new Date(secured).toISOString().slice(0, 16) : "");
setGatepassReference(operation.documents?.GATE_PASS?.reference ?? "");
setGatepassFileUrl(operation.documents?.GATE_PASS?.fileUrl ?? "");
setGatepassNotes(operation.documents?.GATE_PASS?.notes ?? operation.notes ?? "");
}, [gatepassQuery.data]);
const assignedIds = useMemo(
() => (schedule?.bookings ?? []).map((b) => b.id),
[schedule?.bookings],
@@ -899,6 +951,83 @@ export default function TrainScheduleV2DetailPage() {
]}
/>
{gatepassApplies ? (
<Paper radius="xl" p="lg" withBorder>
<Stack gap="md">
<Group justify="space-between" align="flex-start" wrap="wrap">
<Group gap="md" align="flex-start" wrap="nowrap">
<ThemeIcon
size={44}
radius="md"
variant="light"
color={gatepassQuery.data?.gatepassStatus === "SECURED" ? "edr-green" : "orange"}
>
<FileText size={22} />
</ThemeIcon>
<Stack gap={4}>
<Group gap="sm">
<Title order={4} fw={700}>
Djibouti Port gate pass
</Title>
<Badge
color={gatepassQuery.data?.gatepassStatus === "SECURED" ? "green" : "orange"}
variant="light"
>
{gatepassQuery.data?.gatepassStatus ?? "NOT_SECURED"}
</Badge>
</Group>
<Text size="sm" c="dimmed">
{schedule.direction === "IMPORT"
? "Secure before dispatch from Djibouti."
: "Secure after dispatch before Djibouti Port entry / unloading."}
</Text>
</Stack>
</Group>
{gatepassQuery.isLoading ? <Loader size="sm" /> : null}
</Group>
<Group align="flex-end" grow>
<TextInput
label="Secured date"
type="datetime-local"
value={gatepassSecuredAt}
onChange={(event) => setGatepassSecuredAt(event.currentTarget.value)}
/>
<TextInput
label="Document reference"
placeholder="Optional"
value={gatepassReference}
onChange={(event) => setGatepassReference(event.currentTarget.value)}
/>
<TextInput
label="Document URL"
placeholder="Optional upload/link"
value={gatepassFileUrl}
onChange={(event) => setGatepassFileUrl(event.currentTarget.value)}
/>
</Group>
<Textarea
label="Notes"
placeholder="Optional"
autosize
minRows={2}
value={gatepassNotes}
onChange={(event) => setGatepassNotes(event.currentTarget.value)}
/>
<Group justify="flex-end">
<Button
color="edr-green"
leftSection={<CheckCircle2 size={16} />}
loading={secureGatepass.isPending}
onClick={() => secureGatepass.mutate()}
>
Save as Secured
</Button>
</Group>
</Stack>
</Paper>
) : null}
<Paper radius="xl" p="lg">
<Stack gap="lg">
{/* Workflow header with ring progress */}

View File

@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import {
ActionIcon,
Badge,
@@ -28,6 +28,7 @@ import { useToast } from '@/hooks/use-toast';
import {
WAREHOUSE_INVOICE_STATUSES,
type WarehouseFeeInvoice,
type WarehouseGatewayPaymentMethod,
type WarehouseInvoiceStatus,
} from '@/types/warehouse';
import { openPdfBlob } from '@/components/warehouses/pdf';
@@ -162,15 +163,23 @@ function InvoiceDetailModal({ id, onClose }: { id: string | null; onClose: () =>
}),
);
const pay = useMutation(api.warehouses.payInvoice.mutationOptions());
const payOnline = useMutation(api.warehouses.payInvoiceOnline.mutationOptions());
const cancel = useMutation(api.warehouses.cancelInvoice.mutationOptions());
const gateClear = useMutation(api.warehouses.gateClearance.mutationOptions());
const [payAmount, setPayAmount] = useState<number | ''>('');
const [driverName, setDriverName] = useState('');
const [driverPhone, setDriverPhone] = useState('');
const [gatewayMethod, setGatewayMethod] = useState<WarehouseGatewayPaymentMethod>('TELEBIRR');
const [payerAccount, setPayerAccount] = useState('');
const canPay = inv && (inv.status === 'ISSUED' || inv.status === 'PARTIALLY_PAID');
const canGateClear = inv?.status === 'PAID' && Boolean(inv.inventoryId);
useEffect(() => {
setGatewayMethod(inv?.currency === 'USD' ? 'WAAFI' : 'TELEBIRR');
setPayerAccount('');
}, [inv?.id, inv?.currency]);
const downloadInvoicePdf = async (invoice: WarehouseFeeInvoice) => {
const blob = buildWarehouseInvoicePdf(invoice, 'INVOICE');
openPdfBlob(blob, `warehouse-invoice-${invoice.invoiceNumber}.pdf`);
@@ -280,6 +289,34 @@ function InvoiceDetailModal({ id, onClose }: { id: string | null; onClose: () =>
}
};
const handleOnlinePay = async () => {
if (!inv) return;
try {
const currentUrl = window.location.href;
const result = await payOnline.mutateAsync({
id: inv.id,
payload: {
method: gatewayMethod,
platform: 'web',
payerAccount: payerAccount.trim() || undefined,
returnUrl: currentUrl,
failureUrl: currentUrl,
},
});
const url = result.clientAction?.url;
if (url) {
window.location.href = url;
return;
}
toast({
title: 'Payment initiated',
description: 'No redirect URL was returned by the payment provider.',
});
} catch (e) {
toast({ variant: 'destructive', title: 'Payment failed', description: extractErrorMessage(e) });
}
};
const handleCancel = async () => {
if (!inv) return;
try {
@@ -337,7 +374,31 @@ function InvoiceDetailModal({ id, onClose }: { id: string | null; onClose: () =>
{canPay && (
<>
<Divider label="Record payment" labelPosition="left" />
<Divider label="Online payment" labelPosition="left" />
<Group align="flex-end">
<Select
label="Provider"
value={gatewayMethod}
onChange={(v) => setGatewayMethod((v as WarehouseGatewayPaymentMethod) ?? 'TELEBIRR')}
data={[
{ value: 'TELEBIRR', label: 'Telebirr' },
{ value: 'WAAFI', label: 'Waafi' },
]}
style={{ flex: 1 }}
/>
<TextInput
label="Wallet phone / account"
value={payerAccount}
onChange={(e) => setPayerAccount(e.currentTarget.value)}
placeholder="Optional"
style={{ flex: 1 }}
/>
<Button leftSection={<CreditCard size={16} />} loading={payOnline.isPending} onClick={handleOnlinePay}>
Pay with {gatewayMethod === 'WAAFI' ? 'Waafi' : 'Telebirr'}
</Button>
</Group>
<Divider label="Record manual payment" labelPosition="left" />
<Group align="flex-end">
<NumberInput
label="Amount"

View File

@@ -18,6 +18,8 @@ import {
} from '@mantine/core';
import { Info, Plus, Trash2 } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { PageContainer, PageHeader } from '@/components/page';
import { useToast } from '@/hooks/use-toast';
import {
@@ -29,7 +31,9 @@ import {
useDeleteFeeRule,
useFeeRules,
} from '@/hooks/useWarehouses';
import { api } from '@/services/api';
import { FEE_RULE_TYPES, type FeeRuleType } from '@/types/warehouse';
import { extractErrorMessage } from '@/components/warehouses/options';
const FREIGHT = [
{ value: 'CONTAINER', label: 'Container' },
@@ -38,6 +42,7 @@ const FREIGHT = [
const TRADE = [
{ value: 'IMPORT', label: 'Import' },
{ value: 'EXPORT', label: 'Export' },
{ value: 'BOTH', label: 'Import & Export' },
{ value: 'DOMESTIC', label: 'Domestic' },
];
const CURRENCIES = [
@@ -53,6 +58,23 @@ const numberValue = (value: string | number, fallback = 0) => {
};
const anyLabel = (value: string, label: string) => value.trim() || `Any ${label}`;
const dash = '-';
type CodeOptionSource = {
id?: string;
code?: string;
cargoTypeName?: string;
label?: string;
name?: string;
};
const codeOptions = (rows: unknown[]) =>
(rows as CodeOptionSource[])
.filter((row) => row.code)
.map((row) => ({
value: row.code as string,
label: `${row.cargoTypeName ?? row.label ?? row.name ?? row.code} (${row.code})`,
}));
const isUnknownTiersError = (error: unknown) => extractErrorMessage(error).includes('property tiers should not exist');
export default function WarehouseRulesPage() {
return (
@@ -319,6 +341,12 @@ function AllocationRules() {
function FeeRules() {
const { toast } = useToast();
const { data, isLoading } = useFeeRules();
const { data: cargoTypes = [], isLoading: cargoTypesLoading } = useQuery(
api.cargoTypes.list.queryOptions({ staleTime: Infinity }),
);
const { data: containerTypes = [], isLoading: containerTypesLoading } = useQuery(
api.containerTypes.list.queryOptions({ staleTime: Infinity }),
);
const create = useCreateFeeRule();
const remove = useDeleteFeeRule();
const [open, setOpen] = useState(false);
@@ -328,11 +356,56 @@ function FeeRules() {
freightType: '',
tradeDirection: '',
cargoTypeCode: '',
containerType: '',
freeDays: 3,
ratePerDay: 0,
tiers: [] as Array<{ fromDay: number; toDay: number | null; ratePerDay: number }>,
currency: 'USD',
});
const rules = data ?? [];
const cargoTypeOptions = codeOptions(cargoTypes);
const containerTypeOptions = codeOptions(containerTypes);
const isBulkRule = form.freightType === 'BULK';
const isContainerRule = form.freightType === 'CONTAINER';
const resetForm = () =>
setForm({
name: '',
ruleType: 'DEMURRAGE_FEE',
freightType: '',
tradeDirection: '',
cargoTypeCode: '',
containerType: '',
freeDays: 3,
ratePerDay: 0,
tiers: [],
currency: 'USD',
});
const addTier = () =>
setForm((f) => {
const last = f.tiers[f.tiers.length - 1];
const fromDay = last?.toDay ? last.toDay + 1 : f.tiers.length ? last.fromDay + 1 : f.freeDays + 1;
return {
...f,
tiers: [...f.tiers, { fromDay, toDay: fromDay, ratePerDay: f.ratePerDay || 0 }],
};
});
const updateTier = (
index: number,
patch: Partial<{ fromDay: number; toDay: number | null; ratePerDay: number }>,
) =>
setForm((f) => ({
...f,
tiers: f.tiers.map((tier, i) => (i === index ? { ...tier, ...patch } : tier)),
}));
const removeTier = (index: number) =>
setForm((f) => ({
...f,
tiers: f.tiers.filter((_, i) => i !== index),
}));
const submit = async () => {
if (!form.name.trim()) {
@@ -340,18 +413,68 @@ function FeeRules() {
return;
}
await create.mutateAsync({
const tiers = form.tiers.map((tier) => ({
fromDay: tier.fromDay,
toDay: tier.toDay || null,
ratePerDay: tier.ratePerDay,
}));
for (const [index, tier] of tiers.entries()) {
if (!Number.isInteger(tier.fromDay) || tier.fromDay < 1) {
toast({ variant: 'destructive', title: `Tier ${index + 1}: from day must be at least 1` });
return;
}
if (tier.toDay != null && tier.toDay < tier.fromDay) {
toast({ variant: 'destructive', title: `Tier ${index + 1}: to day must be after from day` });
return;
}
if (tier.ratePerDay < 0) {
toast({ variant: 'destructive', title: `Tier ${index + 1}: amount must be zero or greater` });
return;
}
}
const payload = {
name: form.name.trim(),
ruleType: form.ruleType,
freightType: clean(form.freightType) ?? null,
tradeDirection: clean(form.tradeDirection) ?? null,
cargoTypeCode: clean(form.cargoTypeCode) ?? null,
cargoTypeCode: isBulkRule ? (clean(form.cargoTypeCode) ?? null) : null,
containerType: isContainerRule ? (clean(form.containerType) ?? null) : null,
freeDays: form.freeDays,
ratePerDay: form.ratePerDay,
currency: form.currency || 'USD',
} as never);
toast({ title: 'Fee rule created' });
setOpen(false);
...(tiers.length ? { tiers } : {}),
};
try {
await create.mutateAsync(payload as never);
toast({ title: 'Fee rule created' });
setOpen(false);
resetForm();
} catch (error) {
if (tiers.length && isUnknownTiersError(error)) {
const legacyPayload: Omit<typeof payload, 'tiers'> = {
name: payload.name,
ruleType: payload.ruleType,
freightType: payload.freightType,
tradeDirection: payload.tradeDirection,
cargoTypeCode: payload.cargoTypeCode,
containerType: payload.containerType,
freeDays: payload.freeDays,
ratePerDay: payload.ratePerDay,
currency: payload.currency,
};
await create.mutateAsync(legacyPayload as never);
toast({
title: 'Fee rule created without tiers',
description: 'The connected API does not support progressive tiers yet. Deploy the warehouse fee tier migration/API to save tier rows.',
});
setOpen(false);
resetForm();
return;
}
toast({ variant: 'destructive', title: 'Create failed', description: extractErrorMessage(error) });
}
};
return (
@@ -370,7 +493,7 @@ function FeeRules() {
<Loader />
</Group>
) : (
<Table.ScrollContainer minWidth={900}>
<Table.ScrollContainer minWidth={1100}>
<Table striped highlightOnHover verticalSpacing="sm">
<Table.Thead>
<Table.Tr>
@@ -378,6 +501,9 @@ function FeeRules() {
<Table.Th>Name</Table.Th>
<Table.Th>Freight</Table.Th>
<Table.Th>Trade</Table.Th>
<Table.Th>Cargo</Table.Th>
<Table.Th>Container</Table.Th>
<Table.Th>Location scope</Table.Th>
<Table.Th>Free days</Table.Th>
<Table.Th>Rate / day</Table.Th>
<Table.Th>Active</Table.Th>
@@ -395,6 +521,20 @@ function FeeRules() {
<Table.Td>{rule.name}</Table.Td>
<Table.Td>{rule.freightType ?? dash}</Table.Td>
<Table.Td>{rule.tradeDirection ?? dash}</Table.Td>
<Table.Td>{rule.cargoTypeCode ?? dash}</Table.Td>
<Table.Td>{rule.containerType ?? dash}</Table.Td>
<Table.Td>
{[rule.facilityId, rule.warehouseId, rule.yardId, rule.zoneId].some(Boolean) ? (
<Stack gap={2}>
{rule.facilityId && <Text size="xs">Facility: {rule.facilityId}</Text>}
{rule.warehouseId && <Text size="xs">Warehouse: {rule.warehouseId}</Text>}
{rule.yardId && <Text size="xs">Yard: {rule.yardId}</Text>}
{rule.zoneId && <Text size="xs">Zone: {rule.zoneId}</Text>}
</Stack>
) : (
dash
)}
</Table.Td>
<Table.Td>{rule.freeDays}</Table.Td>
<Table.Td>
{Number(rule.ratePerDay).toLocaleString()} {rule.currency}
@@ -454,7 +594,14 @@ function FeeRules() {
label="Freight type"
data={FREIGHT}
value={form.freightType || null}
onChange={(value) => setForm((f) => ({ ...f, freightType: selectValue(value) }))}
onChange={(value) =>
setForm((f) => ({
...f,
freightType: selectValue(value),
cargoTypeCode: value === 'BULK' ? f.cargoTypeCode : '',
containerType: value === 'CONTAINER' ? f.containerType : '',
}))
}
clearable
/>
<Select
@@ -464,15 +611,31 @@ function FeeRules() {
onChange={(value) => setForm((f) => ({ ...f, tradeDirection: selectValue(value) }))}
clearable
/>
<TextInput
label="Cargo type code"
value={form.cargoTypeCode}
onChange={(e) => {
const value = e.currentTarget.value;
setForm((f) => ({ ...f, cargoTypeCode: value }));
}}
/>
{isBulkRule && (
<Select
label="Cargo type"
placeholder={cargoTypesLoading ? 'Loading cargo types...' : 'Any cargo'}
data={cargoTypeOptions}
value={form.cargoTypeCode || null}
onChange={(value) => setForm((f) => ({ ...f, cargoTypeCode: selectValue(value) }))}
searchable
clearable
disabled={cargoTypesLoading}
/>
)}
</Group>
{isContainerRule && (
<Select
label="Container type"
placeholder={containerTypesLoading ? 'Loading container types...' : 'Any container'}
data={containerTypeOptions}
value={form.containerType || null}
onChange={(value) => setForm((f) => ({ ...f, containerType: selectValue(value) }))}
searchable
clearable
disabled={containerTypesLoading}
/>
)}
<Group grow>
<NumberInput
label="Free days"
@@ -494,6 +657,51 @@ function FeeRules() {
allowDeselect={false}
/>
</Group>
<Stack gap="xs">
<Group justify="space-between">
<Text size="sm" fw={600}>
Progressive tariff tiers
</Text>
<Button variant="light" size="xs" leftSection={<Plus size={14} />} onClick={addTier}>
Add tier
</Button>
</Group>
{form.tiers.map((tier, index) => (
<Group key={index} grow align="end">
<NumberInput
label="From day"
min={1}
value={tier.fromDay}
onChange={(value) => updateTier(index, { fromDay: numberValue(value, 1) || 1 })}
/>
<NumberInput
label="To day"
min={tier.fromDay}
value={tier.toDay ?? ''}
placeholder="Open"
onChange={(value) =>
updateTier(index, {
toDay: value === '' ? null : numberValue(value, tier.fromDay),
})
}
/>
<NumberInput
label="Amount / day"
min={0}
value={tier.ratePerDay}
onChange={(value) => updateTier(index, { ratePerDay: numberValue(value) })}
/>
<ActionIcon variant="subtle" color="red" onClick={() => removeTier(index)} title="Remove tier">
<Trash2 size={16} />
</ActionIcon>
</Group>
))}
{form.tiers.length === 0 && (
<Text size="xs" c="dimmed">
No stepped tiers. The flat rate per day is used after the free days.
</Text>
)}
</Stack>
<Group justify="flex-end" mt="sm">
<Button variant="default" onClick={() => setOpen(false)}>
Cancel