frist mile receive to warehouse and last mile truck arrival integration

This commit is contained in:
hagiye
2026-07-02 01:08:37 +03:00
parent 14a00af341
commit 129448e437
11 changed files with 299 additions and 30 deletions

View File

@@ -116,6 +116,7 @@ export default registerAs("database", (): TypeOrmModuleOptions => {
freightMigrationsGlob,
],
migrationsRun: true,
migrationsTransactionMode: "each",
// Schema changes via migrations only (synchronize breaks ITMLS backfill on existing rows).
synchronize: false,
logging: process.env.NODE_ENV === "development",

View File

@@ -94,7 +94,7 @@ export class CreateInvoices1821000000002 implements MigrationInterface {
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'pk_invoices'
WHERE contype = 'p'
AND conrelid = 'freight.invoices'::regclass
) THEN
ALTER TABLE freight.invoices ADD CONSTRAINT pk_invoices PRIMARY KEY (id);

View File

@@ -19,6 +19,31 @@ export class CentralizeWarehouseInvoices1829000000000 implements MigrationInterf
name = 'CentralizeWarehouseInvoices1829000000000';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_schema = 'freight'
AND table_name = 'invoices'
AND column_name = 'booking_id'
) THEN
ALTER TABLE freight.invoices ALTER COLUMN booking_id DROP NOT NULL;
END IF;
IF EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_schema = 'freight'
AND table_name = 'invoices'
AND column_name = 'amount'
) THEN
ALTER TABLE freight.invoices ALTER COLUMN amount DROP NOT NULL;
END IF;
END $$;
`);
// 1. Invoice headers. Keep the same id so items still link, and so any
// external reference to the invoice id stays valid.
await queryRunner.query(`

View File

@@ -129,6 +129,12 @@ export class LastMileService {
}
async create(dto: CreateLastMileDto): Promise<LastMile> {
const [existing] = await this.lastMileRepository.findAll({
where: { bookingId: dto.bookingId },
take: 1,
});
if (existing) return existing;
return this.lastMileRepository.create({
bookingId: dto.bookingId,
status: dto.status ?? 'READY_TO_TRANSIT',

View File

@@ -84,9 +84,11 @@ export class WarehouseInspectionService {
`SELECT inv.booking_id AS "bookingId",
b.reference AS "bookingReference",
b.trade_direction AS "tradeDirection",
b.last_mile_delivery_address AS "lastMileDeliveryAddress"
b.last_mile_delivery_address AS "lastMileDeliveryAddress",
COALESCE(st.includes_last_mile, false) AS "serviceIncludesLastMile"
FROM freight.warehouse_inventory inv
LEFT JOIN freight.bookings b ON b.id = inv.booking_id
LEFT JOIN freight.service_types st ON st.id = b.service_type_id
WHERE inv.id = $1 AND inv.deleted_at IS NULL
LIMIT 1`,
[inventoryId],
@@ -98,7 +100,10 @@ export class WarehouseInspectionService {
readyForPickupAt: new Date(),
});
if (row.bookingReference && row.lastMileDeliveryAddress) {
const hasLastMile =
Boolean(row.lastMileDeliveryAddress?.trim?.()) || Boolean(row.serviceIncludesLastMile);
if (row.bookingReference && hasLastMile) {
await this.lastMileService.acceptBooking(row.bookingReference);
}
}

View File

@@ -1061,9 +1061,11 @@ export class WarehouseInventoryService {
COALESCE(inv.grn_number, substring(inv.notes FROM 'GRN Number: ([^\\n\\r]+)')) AS "grnNumber",
ts.train_number AS "trainSchedule",
inv.inspection_status AS "inspectionStatus",
CASE WHEN b.last_mile_delivery_address IS NOT NULL
CASE WHEN NULLIF(TRIM(COALESCE(b.last_mile_delivery_address, '')), '') IS NOT NULL
OR COALESCE(st.includes_last_mile, false)
THEN 'DOOR_DELIVERY' ELSE 'TERMINAL_PICKUP' END AS "pickupOption",
(b.last_mile_delivery_address IS NOT NULL) AS "lastMileRequested",
(NULLIF(TRIM(COALESCE(b.last_mile_delivery_address, '')), '') IS NOT NULL
OR COALESCE(st.includes_last_mile, false)) AS "lastMileRequested",
b.customer_truck_plate_number AS "customerTruckPlateNumber",
b.customer_truck_driver_name AS "customerTruckDriverName",
b.customer_truck_type AS "customerTruckType",
@@ -1081,6 +1083,7 @@ export class WarehouseInventoryService {
LEFT JOIN freight.bookings b ON b.id = inv.booking_id AND b.deleted_at IS NULL
LEFT JOIN freight.companies company ON company.id = b.company_id
LEFT JOIN freight.cargo_types cgt ON cgt.id = b.cargo_type_id
LEFT JOIN freight.service_types st ON st.id = b.service_type_id
LEFT JOIN freight.yards oy ON oy.id = b.origin_yard_id
LEFT JOIN freight.yards dy ON dy.id = b.destination_yard_id
LEFT JOIN freight.train_schedule_bookings tsb ON tsb.booking_id = b.id AND tsb.deleted_at IS NULL
@@ -1666,13 +1669,17 @@ export class WarehouseInventoryService {
if (!bookingId) return;
const [booking] = await this.dataSource.query(
`SELECT reference,
last_mile_delivery_address AS "lastMileDeliveryAddress"
FROM freight.bookings
WHERE id = $1 AND deleted_at IS NULL
last_mile_delivery_address AS "lastMileDeliveryAddress",
COALESCE(st.includes_last_mile, false) AS "serviceIncludesLastMile"
FROM freight.bookings b
LEFT JOIN freight.service_types st ON st.id = b.service_type_id
WHERE b.id = $1 AND b.deleted_at IS NULL
LIMIT 1`,
[bookingId],
);
if (!booking?.reference || !booking.lastMileDeliveryAddress) return;
const hasLastMile =
Boolean(booking?.lastMileDeliveryAddress?.trim?.()) || Boolean(booking?.serviceIncludesLastMile);
if (!booking?.reference || !hasLastMile) return;
await this.lastMileService.acceptBooking(booking.reference);
}

View File

@@ -76,6 +76,8 @@ interface ReceiveInventoryModalProps {
/** When supplied the modal locks to a single booking (legacy single-receive). */
bookingId?: string;
bookingLabel?: string;
mode?: 'single' | 'bulk';
direction?: WarehouseFlowDirection;
onReceived?: () => void;
}
@@ -716,11 +718,15 @@ function EligibleTab({
location,
enabled,
onChanged,
focusedBookingId,
focusedBookingLabel,
}: {
direction: 'IMPORT' | 'EXPORT';
location: Location;
enabled: boolean;
onChanged?: () => void;
focusedBookingId?: string;
focusedBookingLabel?: string;
}) {
const { toast } = useToast();
const qc = useQueryClient();
@@ -730,7 +736,15 @@ function EligibleTab({
enabled,
}),
);
const rows = useMemo(() => allRows.filter((r) => r.direction === direction), [allRows, direction]);
const rows = useMemo(
() =>
allRows.filter(
(r) =>
r.direction === direction &&
(!focusedBookingId || r.id === focusedBookingId),
),
[allRows, direction, focusedBookingId],
);
const bulkReceive = useMutation(api.warehouses.bulkReceive.mutationOptions());
const requestFirstMile = useMutation({
mutationFn: (reference: string) => firstMileService.accept(reference),
@@ -856,6 +870,18 @@ function EligibleTab({
title: `${r.receivedCount} received at ${direction === 'EXPORT' ? 'facility' : 'warehouse'}`,
description: r.results.find((item) => item.grnNumber)?.grnNumber ?? (r.skippedCount ? `${r.skippedCount} skipped` : undefined),
});
const firstGrn = r.results.find((item) => item.inventoryId && item.grnNumber);
if (focusedBookingId && firstGrn?.inventoryId && firstGrn.grnNumber) {
const pdfWindow = window.open('', '_blank');
try {
const response = await warehouseService.downloadGrnDocument(firstGrn.inventoryId);
const opened = openPdfBlob(response.data, `grn-${firstGrn.grnNumber}.pdf`, pdfWindow);
toast({ title: opened ? 'GRN document opened' : 'GRN document downloaded' });
} catch (error) {
pdfWindow?.close();
toast({ variant: 'destructive', title: 'GRN document failed', description: extractErrorMessage(error) });
}
}
setSelected(new Set());
setTruckOpen(false);
setPendingReceiveIds([]);
@@ -1007,7 +1033,9 @@ function EligibleTab({
</Group>
) : statusFilteredRows.length === 0 ? (
<Text c="dimmed" ta="center" py="lg" size="sm">
No eligible PAID {direction.toLowerCase()} bookings to receive.
{focusedBookingLabel
? `${focusedBookingLabel} is not eligible for warehouse receiving yet.`
: `No eligible PAID ${direction.toLowerCase()} bookings to receive.`}
</Text>
) : (
<Table.ScrollContainer minWidth={1700}>
@@ -2369,6 +2397,8 @@ interface WarehouseFlowWorkbenchProps {
direction?: WarehouseFlowDirection;
enabled?: boolean;
onChanged?: () => void;
focusedBookingId?: string;
focusedBookingLabel?: string;
}
function WarehouseQueueTabs<TValue extends string>({
@@ -2588,10 +2618,14 @@ function ExportWarehouseTabs({
enabled,
location,
onChanged,
focusedBookingId,
focusedBookingLabel,
}: {
enabled: boolean;
location: Location;
onChanged?: () => void;
focusedBookingId?: string;
focusedBookingLabel?: string;
}) {
const [activeTab, setActiveTab] = useState<ExportWarehouseTab>('receive-queue');
const { data: eligibleRows = [] } = useQuery(
@@ -2650,7 +2684,14 @@ function ExportWarehouseTabs({
<WarehouseQueueTabs value={activeTab} onChange={setActiveTab} tabs={tabs} />
{activeTab === 'receive-queue' && (
<EligibleTab direction="EXPORT" location={location} enabled={enabled} onChanged={onChanged} />
<EligibleTab
direction="EXPORT"
location={location}
enabled={enabled}
onChanged={onChanged}
focusedBookingId={focusedBookingId}
focusedBookingLabel={focusedBookingLabel}
/>
)}
{activeTab === 'received' && (
<ExportReceivedTab enabled={enabled} onChanged={onChanged} />
@@ -2675,6 +2716,8 @@ export function WarehouseFlowWorkbench({
direction = 'BOTH',
enabled = true,
onChanged,
focusedBookingId,
focusedBookingLabel,
}: WarehouseFlowWorkbenchProps) {
const [location, setLocation] = useState<Location>({ warehouseId: '', yardId: '', zoneId: '' });
const [tab, setTab] = useState<Exclude<WarehouseFlowDirection, 'BOTH'>>(
@@ -2707,24 +2750,42 @@ export function WarehouseFlowWorkbench({
<ImportWarehouseTabs enabled={enabled} onChanged={onChanged} />
</Tabs.Panel>
<Tabs.Panel value="EXPORT">
<ExportWarehouseTabs enabled={enabled} location={location} onChanged={onChanged} />
<ExportWarehouseTabs
enabled={enabled}
location={location}
onChanged={onChanged}
focusedBookingId={focusedBookingId}
focusedBookingLabel={focusedBookingLabel}
/>
</Tabs.Panel>
</Tabs>
) : activeDirection === 'IMPORT' ? (
<ImportWarehouseTabs enabled={enabled} onChanged={onChanged} />
) : (
<ExportWarehouseTabs enabled={enabled} location={location} onChanged={onChanged} />
<ExportWarehouseTabs
enabled={enabled}
location={location}
onChanged={onChanged}
focusedBookingId={focusedBookingId}
focusedBookingLabel={focusedBookingLabel}
/>
)}
</Stack>
);
}
/** New bulk Receive: Import / Export tabs with eligible PAID bookings. */
function BulkReceiveModal({ opened, onClose, onReceived }: ReceiveInventoryModalProps) {
function BulkReceiveModal({ opened, onClose, onReceived, bookingId, bookingLabel, direction = 'BOTH' }: ReceiveInventoryModalProps) {
return (
<Modal opened={opened} onClose={onClose} title="Receive at warehouse" centered size="80rem">
<Stack gap="md">
<WarehouseFlowWorkbench enabled={opened} direction="BOTH" onChanged={onReceived} />
<WarehouseFlowWorkbench
enabled={opened}
direction={direction}
onChanged={onReceived}
focusedBookingId={bookingId}
focusedBookingLabel={bookingLabel}
/>
<Group justify="flex-end" mt="sm">
<Button variant="default" onClick={onClose}>
@@ -2870,5 +2931,5 @@ function SingleBookingReceiveModal({
export function ReceiveInventoryModal(props: ReceiveInventoryModalProps) {
// Locked to a booking → legacy single receive; otherwise the Import/Export bulk flow.
return props.bookingId ? <SingleBookingReceiveModal {...props} /> : <BulkReceiveModal {...props} />;
return props.bookingId && props.mode !== 'bulk' ? <SingleBookingReceiveModal {...props} /> : <BulkReceiveModal {...props} />;
}

View File

@@ -15,6 +15,17 @@ interface ReleaseOrderModalProps {
opened: boolean;
onClose: () => void;
item: WarehouseInventoryItem | null;
truckPrefill?: ReleaseOrderTruckPrefill | null;
}
export interface ReleaseOrderTruckPrefill {
truckPlateNumber?: string | null;
trailerPlateNumber?: string | null;
driverName?: string | null;
driverLicense?: string | null;
driverPhone?: string | null;
truckType?: string | null;
containerNumber?: string | null;
}
const REGISTERED_FIRST_LAST_MILE_TRUCKS = [
@@ -120,7 +131,7 @@ const parseInspectionNote = (notes: string | null | undefined) => {
};
};
export function ReleaseOrderModal({ opened, onClose, item }: ReleaseOrderModalProps) {
export function ReleaseOrderModal({ opened, onClose, item, truckPrefill }: ReleaseOrderModalProps) {
const { toast } = useToast();
const releaseMutation = useMutation(api.warehouses.release.mutationOptions());
const [reference, setReference] = useState('');
@@ -145,27 +156,30 @@ export function ReleaseOrderModal({ opened, onClose, item }: ReleaseOrderModalPr
const assignedDriverName = assignedTruckValue(item, 'customerTruckDriverName');
const assignedTruckType = assignedTruckValue(item, 'customerTruckType');
const assignedContainerNumber = assignedTruckValue(item, 'customerTruckContainerNumber');
const prefillContainerNumber = truckPrefill?.containerNumber ?? '';
setReference(item?.releaseOrderReference ?? generateReleaseReference(item));
setTruckPlateNumber(inspection.truckPlateNumber || assignedTruckPlate);
setTrailerPlateNumber(inspection.trailerPlateNumber);
setDriverName(inspection.driverName || assignedDriverName);
setDriverLicense(inspection.driverLicense);
setDriverPhone(inspection.driverPhone);
setTruckType(inspection.truckType || assignedTruckType);
setContainerNumbers(initialContainerNumbers(item, inspection.containerNumber || assignedContainerNumber));
setTruckPlateNumber(inspection.truckPlateNumber || assignedTruckPlate || truckPrefill?.truckPlateNumber || '');
setTrailerPlateNumber(inspection.trailerPlateNumber || truckPrefill?.trailerPlateNumber || '');
setDriverName(inspection.driverName || assignedDriverName || truckPrefill?.driverName || '');
setDriverLicense(inspection.driverLicense || truckPrefill?.driverLicense || '');
setDriverPhone(inspection.driverPhone || truckPrefill?.driverPhone || '');
setTruckType(inspection.truckType || assignedTruckType || truckPrefill?.truckType || '');
setContainerNumbers(initialContainerNumbers(item, inspection.containerNumber || assignedContainerNumber || prefillContainerNumber));
setGateInTime(inspection.gateInTime);
setTareWeight(inspection.tareWeight);
setGrossWeight(inspection.grossWeight);
setNetWeight(item?.weight == null ? inspection.netWeight : Number(item.weight));
setGateOutTime(inspection.gateOutTime);
}
}, [opened, item]);
}, [opened, item, truckPrefill]);
const savedInspection = parseInspectionNote(item?.notes);
const isExitStep = savedInspection.tareWeight !== '';
const isEntranceLocked = isExitStep;
const isCustomerAssignedTruck = Boolean(item?.booking?.customerTruckAssignedAt);
const isTruckIdentityLocked = isEntranceLocked || isCustomerAssignedTruck;
const hasLastMileTruckPrefill = Boolean(truckPrefill?.truckPlateNumber || truckPrefill?.trailerPlateNumber);
const isTruckIdentityLocked = isEntranceLocked || isCustomerAssignedTruck || hasLastMileTruckPrefill;
const isDriverNameLocked = isEntranceLocked || isCustomerAssignedTruck || Boolean(truckPrefill?.driverName);
const systemNetWeight = item?.weight == null ? netWeight : Number(item.weight);
const computedNetWeight =
tareWeight !== '' && grossWeight !== '' ? Number((Number(grossWeight) - Number(tareWeight)).toFixed(3)) : null;
@@ -302,7 +316,7 @@ export function ReleaseOrderModal({ opened, onClose, item }: ReleaseOrderModalPr
/>
</Group>
<Group grow>
<TextInput label="Driver name" required value={driverName} onChange={(e) => setDriverName(e.currentTarget.value)} readOnly={isTruckIdentityLocked} />
<TextInput label="Driver name" required value={driverName} onChange={(e) => setDriverName(e.currentTarget.value)} readOnly={isDriverNameLocked} />
<TextInput label="Driver license" value={driverLicense} onChange={(e) => setDriverLicense(e.currentTarget.value)} readOnly={isEntranceLocked} />
</Group>
<Group grow>

View File

@@ -4,6 +4,7 @@ import {
ChevronRight,
Eye,
MoreHorizontal,
PackageCheck,
Printer,
RefreshCw,
Ruler,
@@ -35,6 +36,7 @@ import {
import { ruleEngineTable } from "@/components/ruleEngine/ruleEngineStyles";
import { FirstMileContainerAllocationTable } from "@/components/FirstMileContainerAllocationTable";
import { ReceiveInventoryModal } from "@/components/warehouses/ReceiveInventoryModal";
import { QUERY_KEYS } from "@/constants/QUERY_KEYS";
import { useToast } from "@/hooks/use-toast";
import {
@@ -338,6 +340,8 @@ const FirstMilePage = () => {
const [distanceValue, setDistanceValue] = useState("");
const [invoiceOpen, setInvoiceOpen] = useState(false);
const [invoiceRecord, setInvoiceRecord] = useState<FirstMileRecord | null>(null);
const [warehouseReceiveOpen, setWarehouseReceiveOpen] = useState(false);
const [warehouseReceiveRecord, setWarehouseReceiveRecord] = useState<FirstMileRecord | null>(null);
const [containerAllocationOpen, setContainerAllocationOpen] = useState(false);
const [containerAllocationFirstMileId, setContainerAllocationFirstMileId] = useState<string | null>(null);
@@ -527,6 +531,16 @@ const FirstMilePage = () => {
setInvoiceRecord(null);
};
const openWarehouseReceive = (record: FirstMileRecord) => {
setWarehouseReceiveRecord(record);
setWarehouseReceiveOpen(true);
};
const closeWarehouseReceive = () => {
setWarehouseReceiveOpen(false);
setWarehouseReceiveRecord(null);
};
const openContainerAllocation = (firstMileId: string) => {
setContainerAllocationFirstMileId(firstMileId);
setContainerAllocationOpen(true);
@@ -813,6 +827,7 @@ const FirstMilePage = () => {
const assigned = isAssigned(row.original);
const nextStatus = NEXT_STATUS[row.original.status];
const canPrint = row.original.status !== "PAYMENT_PENDING";
const canReceiveToWarehouse = row.original.status === "RECEIVED_TO_PORT";
return (
<Group gap={4} justify="flex-end" wrap="nowrap">
<Menu position="bottom-end" width={200} withinPortal>
@@ -851,6 +866,13 @@ const FirstMilePage = () => {
>
View detail
</Menu.Item>
<Menu.Item
leftSection={<PackageCheck size={15} />}
disabled={!canReceiveToWarehouse}
onClick={() => openWarehouseReceive(row.original)}
>
Receive to warehouse
</Menu.Item>
<Menu.Item
leftSection={<Ruler size={15} />}
onClick={() => openDistance(row.original.id)}
@@ -1039,6 +1061,19 @@ const FirstMilePage = () => {
</Stack>
</Modal>
<ReceiveInventoryModal
opened={warehouseReceiveOpen}
onClose={closeWarehouseReceive}
mode="bulk"
direction="EXPORT"
bookingId={warehouseReceiveRecord?.bookingId}
bookingLabel={warehouseReceiveRecord ? bookingRef(warehouseReceiveRecord) : undefined}
onReceived={() => {
void qc.invalidateQueries({ queryKey: QUERY_KEYS.FIRST_MILE.list() });
closeWarehouseReceive();
}}
/>
{/* Accept Booking modal — step 1: booking list, step 2: details + vehicle */}
<Modal
opened={acceptOpen}

View File

@@ -31,7 +31,7 @@ import {
TextInput,
UnstyledButton,
} from "@mantine/core";
import type { ArrivalQueueItem } from "@/types/warehouse";
import type { ArrivalQueueItem, ImportUnloadedItem, WarehouseInventoryItem } from "@/types/warehouse";
import { warehouseService } from "@/services/warehouse.service";
import { ruleEngineTable } from "@/components/ruleEngine/ruleEngineStyles";
@@ -46,6 +46,7 @@ import {
import { vehiclesService } from "@/services/vehicles.service";
import { ratesService } from "@/services/rates.service";
import { LastMileContainerAllocationTable, type LastMileContainerRow } from "@/components/LastMileContainerAllocationTable";
import { ReleaseOrderModal, type ReleaseOrderTruckPrefill } from "@/components/warehouses/ReleaseOrderModal";
import { api } from "@/auth/http";
const formatPrice = (amount: number) =>
@@ -110,6 +111,52 @@ const requestedDate = (r: LastMileRecord) => {
const serviceTypeName = (r: LastMileRecord) =>
r.booking?.serviceType?.label ?? r.booking?.serviceType?.name ?? "—";
const toReleaseInventoryItem = (row: ImportUnloadedItem): WarehouseInventoryItem =>
({
id: row.id,
bookingId: row.bookingId,
quantity: 1,
weight: Number(row.weight) || 0,
grnNumber: row.grnNumber,
status: row.currentStatus,
arrivedAt: row.arrivalTime,
unloadedAt: row.arrivalTime,
inspectionStatus: row.inspectionStatus,
releaseDate: row.releaseDate,
releaseOrderReference: row.releaseOrderReference,
handoverDocumentReference: row.handoverDocumentReference,
handoverDocumentDate: row.handoverDocumentDate,
deliveredAt: row.deliveredAt,
booking: row.bookingId
? {
id: row.bookingId,
reference: row.bookingReference ?? row.bookingId,
tradeDirection: "IMPORT",
lastMileDeliveryAddress: row.lastMileRequested ? row.pickupOption : null,
customerTruckPlateNumber: row.customerTruckPlateNumber,
customerTruckDriverName: row.customerTruckDriverName,
customerTruckType: row.customerTruckType,
customerTruckContainerNumber: row.customerTruckContainerNumber,
customerTruckAssignedAt: row.customerTruckAssignedAt,
}
: null,
}) as unknown as WarehouseInventoryItem;
const releasePrefillFromLastMile = (
record: LastMileRecord,
row?: ImportUnloadedItem | null,
): ReleaseOrderTruckPrefill => {
const vehicle = record.vehicle;
const truckType = [vehicle?.manufacturer, vehicle?.model].filter(Boolean).join(" ").trim();
return {
truckPlateNumber: vehicle?.powerPlateNo || vehicle?.plateNumber || null,
trailerPlateNumber: vehicle?.trailerPlateNo || null,
driverName: vehicle?.assignedDriverName || null,
truckType: vehicle?.vehicleType || truckType || null,
containerNumber: row?.containerNumber ?? null,
};
};
const InfoRow = ({ label, value }: { label: string; value: string }) => (
<Stack gap={2}>
<Text size="xs" c="dimmed" tt="uppercase" fw={600}>{label}</Text>
@@ -325,6 +372,8 @@ const LastMilePage = () => {
const [allocationOpen, setAllocationOpen] = useState(false);
const [allocationContainers, setAllocationContainers] = useState<LastMileContainerRow[]>([]);
const [releaseItem, setReleaseItem] = useState<WarehouseInventoryItem | null>(null);
const [releaseTruckPrefill, setReleaseTruckPrefill] = useState<ReleaseOrderTruckPrefill | null>(null);
const { data: listData, isLoading } = useQuery({
queryKey: QUERY_KEYS.LAST_MILE.list(),
@@ -352,6 +401,11 @@ const LastMilePage = () => {
const records = listData?.data ?? [];
const { data: pickupReadyRows = [] } = useQuery({
queryKey: ["warehouse-inventory", "import-pickup-ready-queue"],
queryFn: () => warehouseService.importPickupReadyQueue().then((r) => r.data),
});
const vehicleOptions = useMemo(
() =>
(Array.isArray(vehiclesData) ? vehiclesData : []).map((v) => {
@@ -533,6 +587,15 @@ const LastMilePage = () => {
[records, activeId],
);
const pickupReadyByBooking = useMemo(() => {
const map = new Map<string, ImportUnloadedItem>();
for (const row of pickupReadyRows) {
if (row.bookingId) map.set(row.bookingId, row);
if (row.bookingReference) map.set(row.bookingReference, row);
}
return map;
}, [pickupReadyRows]);
const selectedIds = useMemo(
() => Object.keys(rowSelection).filter((id) => rowSelection[id]),
[rowSelection],
@@ -569,6 +632,7 @@ const LastMilePage = () => {
const term = search.trim().toLowerCase();
return records.filter((r) => {
if (!matchesFilter(r)) return false;
if (filterPostPaymentPending && !(r.remainingPayment > 0)) return false;
if (!term) return true;
return [bookingRef(r), customerName(r), deliveryLocation(r), cargoDesc(r)]
.join(" ")
@@ -649,6 +713,37 @@ const LastMilePage = () => {
setTripSlipOpen(true);
};
const openTruckArrival = (record: LastMileRecord) => {
if (!isAssigned(record)) {
toast({
title: "Assign a truck first",
description: "Truck arrival opens after a last-mile vehicle is assigned.",
variant: "destructive",
});
return;
}
const row = pickupReadyByBooking.get(record.bookingId) ?? pickupReadyByBooking.get(bookingRef(record));
if (!row) {
toast({
title: "Import inventory is not pickup-ready",
description: `${bookingRef(record)} must be unloaded and pass inspection before truck arrival.`,
variant: "destructive",
});
return;
}
setReleaseTruckPrefill(releasePrefillFromLastMile(record, row));
setReleaseItem(toReleaseInventoryItem(row));
};
const closeTruckArrival = () => {
setReleaseItem(null);
setReleaseTruckPrefill(null);
void qc.invalidateQueries({ queryKey: ["warehouse-inventory"] });
void qc.invalidateQueries({ queryKey: QUERY_KEYS.LAST_MILE.ROOT });
};
const printTripSlip = () => {
if (!tripSlipRecord) return;
const win = window.open("", "_blank", "width=820,height=920");
@@ -793,6 +888,9 @@ const LastMilePage = () => {
const assigned = isAssigned(row.original);
const nextStatus = NEXT_STATUS[row.original.status];
const canPrint = row.original.status !== "PAYMENT_PENDING";
const releaseRow =
pickupReadyByBooking.get(row.original.bookingId) ?? pickupReadyByBooking.get(bookingRef(row.original));
const truckArrivalLabel = releaseRow?.releaseOrderReference ? "Truck Leaving" : "Truck Arrival";
return (
<Group gap={4} justify="flex-end" wrap="nowrap">
<Menu position="bottom-end" width={200} withinPortal>
@@ -824,6 +922,13 @@ const LastMilePage = () => {
>
Reassign
</Menu.Item>
<Menu.Item
leftSection={<Truck size={15} />}
disabled={!assigned}
onClick={() => openTruckArrival(row.original)}
>
{truckArrivalLabel}
</Menu.Item>
<Menu.Divider />
<Menu.Item
leftSection={<Eye size={15} />}
@@ -853,7 +958,7 @@ const LastMilePage = () => {
},
];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vehicleOptions]);
}, [vehicleOptions, pickupReadyByBooking]);
return (
<Stack gap="md">
@@ -1342,6 +1447,13 @@ const LastMilePage = () => {
</Group>
</Stack>
</Modal>
<ReleaseOrderModal
opened={Boolean(releaseItem)}
onClose={closeTruckArrival}
item={releaseItem}
truckPrefill={releaseTruckPrefill}
/>
</Stack>
);
};

View File

@@ -29,9 +29,12 @@ export interface LastMileVehicle {
plateNumber: string;
manufacturer: string;
model: string;
vehicleType?: string | null;
code?: string | null;
powerPlateNo?: string | null;
trailerPlateNo?: string | null;
assignedDriverId?: string | null;
assignedDriverName?: string | null;
}
export interface LastMileRecord {