Fix loading sheet creation flow

This commit is contained in:
2026-09-23 12:46:23 +05:30
parent 35fa3b19e3
commit ae302d0c9c
7 changed files with 540 additions and 83 deletions
@@ -31,10 +31,13 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
[HttpPost]
public async Task<IActionResult> Create(CreateLoadingSheetRequest request, CancellationToken ct)
{
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
// TEMPORARY: currentUser.UserId is always unset due to the broken auth middleware
// (testbug.md #28) — fall back to the explicitly supplied user until that's fixed.
var userId = currentUser.UserId ?? request.PopulatedByUserId;
if (userId is null) return BadRequest(new { error = "PopulatedByUserId is required while auth is unavailable" });
try
{
var result = await service.CreateAsync(request, userId, ct);
var result = await service.CreateAsync(request, userId.Value, ct);
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
}
catch (KeyNotFoundException) { return NotFound(); }
@@ -54,12 +57,15 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
}
[HttpPost("{id:guid}/confirm")]
public async Task<IActionResult> Confirm(Guid id, CancellationToken ct)
public async Task<IActionResult> Confirm(Guid id, ConfirmLoadingSheetRequest request, CancellationToken ct)
{
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
// TEMPORARY: currentUser.UserId is always unset due to the broken auth middleware
// (testbug.md #28) — fall back to the explicitly supplied user until that's fixed.
var userId = currentUser.UserId ?? request.ConfirmedByUserId;
if (userId is null) return BadRequest(new { error = "ConfirmedByUserId is required while auth is unavailable" });
try
{
var result = await service.ConfirmAsync(id, userId, ct);
var result = await service.ConfirmAsync(id, userId.Value, ct);
return Ok(result);
}
catch (KeyNotFoundException) { return NotFound(); }
@@ -25,7 +25,9 @@ public record LoadingSheetItemResponse(
public record LoadingSheetOrderResponse(Guid ShopPOId);
public record CreateLoadingSheetRequest(Guid FK_RideId);
public record CreateLoadingSheetRequest(Guid FK_RideId, Guid? PopulatedByUserId = null);
public record SetItemsRequest(List<SetItemInput> Items);
public record SetItemInput(Guid FK_ItemId, Guid FK_WarehouseId, decimal Quantity, Guid? FK_ShopPOItemId = null);
public record ConfirmLoadingSheetRequest(Guid? ConfirmedByUserId = null);
@@ -64,26 +64,47 @@ public class LoadingSheetService(
if (sheet.Status != LoadingSheetStatus.Planned)
throw new InvalidOperationException("Items can only be changed while the sheet is Planned");
var shopPOItemIds = request.Items
.Where(i => i.FK_ShopPOItemId.HasValue)
.Select(i => i.FK_ShopPOItemId!.Value)
// Upsert by (item, warehouse, shop PO item): a matching row gets its quantity
// updated in place, a new combination is added. Rows for combinations not present
// in this request are left untouched, so a later save can top up the same PO
// item's remaining quantity from a different warehouse without losing what was
// already planned from the first one.
await uow.BeginAsync(ct);
try
{
var newItems = new List<LoadingSheetItem>();
foreach (var input in request.Items)
{
var existing = sheet.Items.FirstOrDefault(i =>
i.FK_ItemId == input.FK_ItemId &&
i.FK_WarehouseId == input.FK_WarehouseId &&
i.FK_ShopPOItemId == input.FK_ShopPOItemId);
if (existing is not null)
existing.QuantityDispatched = input.Quantity;
else
newItems.Add(new LoadingSheetItem
{
FK_LoadingSheetId = sheet.Id,
FK_ItemId = input.FK_ItemId,
FK_WarehouseId = input.FK_WarehouseId,
FK_ShopPOItemId = input.FK_ShopPOItemId,
QuantityDispatched = input.Quantity
});
}
if (newItems.Count > 0)
await repo.AddItemsAsync(newItems);
var shopPOItemIds = sheet.Items.Select(i => i.FK_ShopPOItemId)
.Concat(newItems.Select(i => i.FK_ShopPOItemId))
.Where(x => x.HasValue)
.Select(x => x!.Value)
.Distinct()
.ToList();
var shopPOIds = shopPOItemIds.Count > 0
? await repo.GetShopPOIdsByItemIdsAsync(shopPOItemIds)
: new List<Guid>();
await uow.BeginAsync(ct);
try
{
repo.RemoveItems(sheet.Items);
await repo.AddItemsAsync(request.Items.Select(i => new LoadingSheetItem
{
FK_LoadingSheetId = sheet.Id,
FK_ItemId = i.FK_ItemId,
FK_WarehouseId = i.FK_WarehouseId,
FK_ShopPOItemId = i.FK_ShopPOItemId,
QuantityDispatched = i.Quantity
}));
await repo.ReplaceOrdersAsync(sheet.Id, shopPOIds);
await uow.CommitAsync(ct);
}
@@ -14,83 +14,83 @@ import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { FieldGroup } from '@/components/ui/field'
import { toast } from '@/components/ui/toast'
import { loadingSheets as loadingSheetsApi, rides as ridesApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { RideResponse } from '@/types/api'
import { loadingSheets as loadingSheetsApi, users as usersApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { LoadingSheetResponse, UserResponse } from '@/types/api'
const schema = z.object({
fK_RideId: z.string().min(1, 'Ride is required'),
confirmedByUserId: z.string().min(1, 'Confirmed by is required'),
})
type FormValues = z.infer<typeof schema>
interface LoadingSheetCreateDialogProps {
interface ConfirmLoadingSheetDialogProps {
open: boolean
onClose: () => void
onSuccess: () => void
sheet: LoadingSheetResponse | null
}
export function LoadingSheetCreateDialog({ open, onClose, onSuccess }: LoadingSheetCreateDialogProps) {
const [ridesList, setRidesList] = useState<RideResponse[]>([])
export function ConfirmLoadingSheetDialog({ open, onClose, onSuccess, sheet }: ConfirmLoadingSheetDialogProps) {
const [usersList, setUsersList] = useState<UserResponse[]>([])
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: { fK_RideId: '' },
defaultValues: { confirmedByUserId: '' },
})
useEffect(() => {
if (!open) return
form.reset({ fK_RideId: '' })
ridesApi.list({ status: 'Open', pageSize: 200 })
.then((res) => setRidesList(getPaginatedItems(res)))
.catch((err) => toast.add({ title: 'Failed to load rides', description: getApiError(err), type: 'error' }))
form.reset({ confirmedByUserId: '' })
usersApi.list({ pageSize: 200 })
.then((res) => setUsersList(getPaginatedItems(res)))
.catch((err) => toast.add({ title: 'Failed to load users', description: getApiError(err), type: 'error' }))
}, [open])
if (!sheet) return null
async function onSubmit(values: FormValues) {
try {
await loadingSheetsApi.create(values)
toast.add({ title: 'Loading sheet created', type: 'success' })
await loadingSheetsApi.confirm(sheet!.id, values.confirmedByUserId)
toast.add({ title: 'Loading sheet confirmed — stock committed to vehicle', type: 'success' })
onSuccess()
onClose()
} catch (err) {
toast.add({ title: 'Failed to create loading sheet', description: getApiError(err), type: 'error' })
toast.add({ title: 'Failed to confirm loading sheet', description: getApiError(err), type: 'error' })
}
}
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-lg">
<Dialog open={open} onOpenChange={(v) => { if (!v) onClose() }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>New Loading Sheet</DialogTitle>
<DialogDescription>
Create a loading sheet for an open ride. Only one planned sheet per ride is allowed.
</DialogDescription>
<DialogTitle>Confirm Loading Sheet</DialogTitle>
<DialogDescription>{sheet.items.length} item(s) will be committed to the vehicle&apos;s stock.</DialogDescription>
</DialogHeader>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
<FieldGroup>
<FormField
control={form.control}
name="fK_RideId"
label="Ride"
name="confirmedByUserId"
label="Confirmed By"
description="Temporary — required until auth resolves the logged-in user automatically."
required
render={({ field }) => (
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select open ride..." />
<SelectValue placeholder="Select user..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select open ride...</SelectItem>
{ridesList.map((r) => (
<SelectItem key={r.id} value={r.id}>
{r.vehicleNumberPlate} — {r.driverFullName}
</SelectItem>
<SelectItem value="" disabled>Select user...</SelectItem>
{usersList.map((user) => (
<SelectItem key={user.id} value={user.id}>{user.fullName}</SelectItem>
))}
</SelectContent>
</Select>
@@ -99,11 +99,9 @@ export function LoadingSheetCreateDialog({ open, onClose, onSuccess }: LoadingSh
</FieldGroup>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Creating…' : 'Create Sheet'}
{form.formState.isSubmitting ? 'Confirming…' : 'Confirm & Commit Stock'}
</Button>
</DialogFooter>
</form>
@@ -88,6 +88,8 @@ export function LoadingSheetItemsDialog({ open, onClose, onSuccess, sheet }: Loa
useEffect(() => {
if (!open) return
setRouteId('')
setPos([])
setLines({})
routesApi.list({ regionId: regionId || undefined, pageSize: 200 })
.then((res) => setRoutesList(getPaginatedItems(res)))
.catch((err) => toast.add({ title: 'Failed to load routes', description: getApiError(err), type: 'error' }))
@@ -95,15 +97,20 @@ export function LoadingSheetItemsDialog({ open, onClose, onSuccess, sheet }: Loa
useEffect(() => {
if (!open) return
setLines({})
if (!routeId) {
setPos([])
return
}
setLoading(true)
shopPosApi.list({ regionId: regionId || undefined, routeId: routeId || undefined, confirmed: true, pageSize: 200 })
shopPosApi.list({ regionId: regionId || undefined, routeId, confirmed: true, pageSize: 200 })
.then((res) => {
const items = getPaginatedItems(res).filter((po) => po.status === 'Pending' || po.status === 'PartiallyFulfilled')
setPos(items)
})
.catch((err) => toast.add({ title: 'Failed to load Shop POs', description: getApiError(err), type: 'error' }))
.finally(() => setLoading(false))
}, [open, regionId, routeId])
}, [open, routeId])
const rows = useMemo<PickedLine[]>(() => {
const result: PickedLine[] = []
@@ -138,6 +145,10 @@ export function LoadingSheetItemsDialog({ open, onClose, onSuccess, sheet }: Loa
async function handleSubmit() {
if (!sheet) return
if (!routeId) {
toast.add({ title: 'Select a route first', type: 'error' })
return
}
if (!warehouseId) {
toast.add({ title: 'Select a warehouse first', type: 'error' })
return
@@ -179,8 +190,8 @@ export function LoadingSheetItemsDialog({ open, onClose, onSuccess, sheet }: Loa
<DialogHeader>
<DialogTitle>Set Loading Sheet Items</DialogTitle>
<DialogDescription>
Pick items from confirmed Shop POs to load onto the vehicle for this ride. Narrow the list
by region/route first.
Select a route first. Confirmed Shop POs for that route will then be available to pick
items from.
</DialogDescription>
</DialogHeader>
@@ -201,13 +212,12 @@ export function LoadingSheetItemsDialog({ open, onClose, onSuccess, sheet }: Loa
</div>
<div className="flex flex-col gap-1">
<label className="text-xs text-muted-foreground">Route</label>
<Select value={routeId || ALL} onValueChange={(v) => setRouteId(!v || v === ALL ? '' : v)}>
<label className="text-xs text-muted-foreground">Route *</label>
<Select value={routeId} onValueChange={(v) => setRouteId(v ?? '')}>
<SelectTrigger className="w-48">
<SelectValue placeholder="All routes" />
<SelectValue placeholder="Select route..." />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL}>All routes</SelectItem>
{routesList.map((r) => (
<SelectItem key={r.id} value={r.id}>{r.routeName}</SelectItem>
))}
@@ -242,10 +252,12 @@ export function LoadingSheetItemsDialog({ open, onClose, onSuccess, sheet }: Loa
</tr>
</thead>
<tbody>
{loading ? (
{!routeId ? (
<tr><td colSpan={5} className="text-center text-muted-foreground px-3 py-6">Select a route to see its confirmed Shop POs.</td></tr>
) : loading ? (
<tr><td colSpan={5} className="text-center text-muted-foreground px-3 py-6">Loading…</td></tr>
) : rows.length === 0 ? (
<tr><td colSpan={5} className="text-center text-muted-foreground px-3 py-6">No eligible Shop PO items found for this filter.</td></tr>
<tr><td colSpan={5} className="text-center text-muted-foreground px-3 py-6">No eligible Shop PO items found for this route.</td></tr>
) : (
rows.map((row) => {
const line = lines[row.shopPOItemId] ?? row
@@ -1,6 +1,7 @@
'use client'
import { useState, useEffect, useCallback, useMemo } from 'react'
import { useRouter } from 'next/navigation'
import { HugeiconsIcon } from '@hugeicons/react'
import { Add01Icon } from '@hugeicons/core-free-icons'
@@ -22,8 +23,8 @@ import type { LoadingSheetResponse, LoadingSheetStatus, RideResponse, RegionResp
const ALL = '__all__'
import { LoadingSheetViewSheet } from './loading-sheet-view-sheet'
import { LoadingSheetCreateDialog } from './loading-sheet-create-dialog'
import { LoadingSheetItemsDialog } from './loading-sheet-items-dialog'
import { ConfirmLoadingSheetDialog } from './confirm-loading-sheet-dialog'
const fmtDate = (v: string) =>
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
@@ -36,15 +37,16 @@ const LS_STATUS_VARIANT: Record<LoadingSheetStatus, 'default' | 'secondary' | 'd
}
export function LoadingSheetsClient() {
const router = useRouter()
const [data, setData] = useState<LoadingSheetResponse[]>([])
const [loading, setLoading] = useState(true)
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
const [createOpen, setCreateOpen] = useState(false)
const [viewOpen, setViewOpen] = useState(false)
const [itemsOpen, setItemsOpen] = useState(false)
const [confirmOpen, setConfirmOpen] = useState(false)
const [selectedSheet, setSelectedSheet] = useState<LoadingSheetResponse | null>(null)
const [ridesList, setRidesList] = useState<RideResponse[]>([])
@@ -116,14 +118,9 @@ export function LoadingSheetsClient() {
setItemsOpen(true)
}
async function handleConfirm(row: LoadingSheetResponse) {
try {
await loadingSheetsApi.confirm(row.id)
toast.add({ title: 'Loading sheet confirmed — stock committed to vehicle', type: 'success' })
fetchData(page, pageSize)
} catch (err) {
toast.add({ title: 'Failed to confirm loading sheet', description: getApiError(err), type: 'error' })
}
function handleConfirm(row: LoadingSheetResponse) {
setSelectedSheet(row)
setConfirmOpen(true)
}
async function handleGenerateTasks(row: LoadingSheetResponse) {
@@ -233,7 +230,7 @@ export function LoadingSheetsClient() {
Items loaded onto a vehicle before a delivery run
</p>
</div>
<Button onClick={() => setCreateOpen(true)}>
<Button onClick={() => router.push('/operations/loading/new')}>
<HugeiconsIcon icon={Add01Icon} size={16} />
New Sheet
</Button>
@@ -329,12 +326,6 @@ export function LoadingSheetsClient() {
}}
/>
<LoadingSheetCreateDialog
open={createOpen}
onClose={() => setCreateOpen(false)}
onSuccess={() => fetchData(page, pageSize)}
/>
<LoadingSheetViewSheet
open={viewOpen}
onClose={() => setViewOpen(false)}
@@ -347,6 +338,13 @@ export function LoadingSheetsClient() {
onSuccess={() => fetchData(page, pageSize)}
sheet={selectedSheet}
/>
<ConfirmLoadingSheetDialog
open={confirmOpen}
onClose={() => setConfirmOpen(false)}
onSuccess={() => fetchData(page, pageSize)}
sheet={selectedSheet}
/>
</>
)
}
@@ -0,0 +1,420 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import { HugeiconsIcon } from '@hugeicons/react'
import { ArrowLeft01Icon } from '@hugeicons/core-free-icons'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { FieldGroup } from '@/components/ui/field'
import { Separator } from '@/components/ui/separator'
import { toast } from '@/components/ui/toast'
import {
shopPos as shopPosApi,
regions as regionsApi,
routes as routesApi,
stores as storesApi,
warehouses as warehousesApi,
rides as ridesApi,
users as usersApi,
loadingSheets as loadingSheetsApi,
getApiError,
getPaginatedItems,
} from '@/lib/api/index'
import type {
ShopPOResponse,
RegionResponse,
RouteResponse,
StoreResponse,
WarehouseResponse,
RideResponse,
UserResponse,
} from '@/types/api'
import type { LoadingSheetItemInput } from '@/lib/api/operations'
const ALL = '__all__'
interface PickedLine {
shopPOItemId: string
itemId: string
itemName: string
storeName: string
orderedQty: number
remainingQty: number
checked: boolean
quantity: number
}
export default function NewLoadingSheetPage() {
const router = useRouter()
const [regionsList, setRegionsList] = useState<RegionResponse[]>([])
const [routesList, setRoutesList] = useState<RouteResponse[]>([])
const [storesList, setStoresList] = useState<StoreResponse[]>([])
const [warehousesList, setWarehousesList] = useState<WarehouseResponse[]>([])
const [ridesList, setRidesList] = useState<RideResponse[]>([])
const [usersList, setUsersList] = useState<UserResponse[]>([])
const [regionId, setRegionId] = useState('')
const [routeId, setRouteId] = useState('')
const [storeId, setStoreId] = useState('')
const [warehouseId, setWarehouseId] = useState('')
const [rideId, setRideId] = useState('')
const [populatedByUserId, setPopulatedByUserId] = useState('')
const [pos, setPos] = useState<ShopPOResponse[]>([])
const [loadingPos, setLoadingPos] = useState(false)
const [submitting, setSubmitting] = useState(false)
const [lines, setLines] = useState<Record<string, PickedLine>>({})
useEffect(() => {
Promise.all([
regionsApi.list({ pageSize: 200 }),
warehousesApi.list({ pageSize: 200 }),
ridesApi.list({ status: 'Open', pageSize: 200 }),
usersApi.list({ pageSize: 200 }),
])
.then(([regionsRes, warehousesRes, ridesRes, usersRes]) => {
setRegionsList(getPaginatedItems(regionsRes))
setWarehousesList(getPaginatedItems(warehousesRes))
setRidesList(getPaginatedItems(ridesRes))
setUsersList(getPaginatedItems(usersRes))
})
.catch((err) => toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' }))
}, [])
useEffect(() => {
setRouteId('')
setStoreId('')
setPos([])
setLines({})
routesApi.list({ regionId: regionId || undefined, pageSize: 200 })
.then((res) => setRoutesList(getPaginatedItems(res)))
.catch((err) => toast.add({ title: 'Failed to load routes', description: getApiError(err), type: 'error' }))
}, [regionId])
useEffect(() => {
setStoreId('')
setLines({})
if (!routeId) {
setStoresList([])
setPos([])
return
}
storesApi.list({ routeId, pageSize: 200 })
.then((res) => setStoresList(getPaginatedItems(res)))
.catch((err) => toast.add({ title: 'Failed to load shops', description: getApiError(err), type: 'error' }))
setLoadingPos(true)
shopPosApi.list({ routeId, confirmed: true, pageSize: 200 })
.then((res) => {
const items = getPaginatedItems(res).filter((po) => po.status === 'Pending' || po.status === 'PartiallyFulfilled')
setPos(items)
})
.catch((err) => toast.add({ title: 'Failed to load Shop POs', description: getApiError(err), type: 'error' }))
.finally(() => setLoadingPos(false))
}, [routeId])
const rows = useMemo<PickedLine[]>(() => {
const result: PickedLine[] = []
for (const po of pos) {
if (storeId && po.storeId !== storeId) continue
for (const item of po.items) {
const remaining = item.quantity - item.quantityFulfilled
if (remaining <= 0) continue
result.push(
lines[item.id] ?? {
shopPOItemId: item.id,
itemId: item.itemId,
itemName: item.itemName,
storeName: po.storeName,
orderedQty: item.quantity,
remainingQty: remaining,
checked: false,
quantity: remaining,
}
)
}
}
return result
}, [pos, storeId, lines])
const selectedRows = useMemo(
() => rows.filter((r) => (lines[r.shopPOItemId]?.checked ?? false)),
[rows, lines]
)
const totalQuantity = useMemo(
() => selectedRows.reduce((sum, r) => sum + (Number(lines[r.shopPOItemId]?.quantity) || 0), 0),
[selectedRows, lines]
)
function toggleLine(line: PickedLine, checked: boolean) {
setLines((prev) => ({ ...prev, [line.shopPOItemId]: { ...line, checked } }))
}
function setLineQuantity(line: PickedLine, quantity: number) {
setLines((prev) => ({ ...prev, [line.shopPOItemId]: { ...line, quantity } }))
}
async function handleSubmit() {
if (!routeId) {
toast.add({ title: 'Select a route first', type: 'error' })
return
}
if (!warehouseId) {
toast.add({ title: 'Select a warehouse', type: 'error' })
return
}
if (selectedRows.length === 0) {
toast.add({ title: 'Select at least one item', type: 'error' })
return
}
if (!rideId) {
toast.add({ title: 'Select a ride to load the vehicle', type: 'error' })
return
}
if (!populatedByUserId) {
toast.add({ title: 'Select who is populating this sheet', type: 'error' })
return
}
const items: LoadingSheetItemInput[] = selectedRows.map((r) => {
const line = lines[r.shopPOItemId]
return {
fK_ItemId: line.itemId,
fK_WarehouseId: warehouseId,
quantity: line.quantity,
fK_ShopPOItemId: line.shopPOItemId,
}
})
setSubmitting(true)
try {
const sheet = await loadingSheetsApi.create({ fK_RideId: rideId, populatedByUserId })
await loadingSheetsApi.updateItems(sheet.id, items)
toast.add({ title: 'Loading sheet created', type: 'success' })
router.push('/operations/loading')
} catch (err) {
toast.add({ title: 'Failed to create loading sheet', description: getApiError(err), type: 'error' })
} finally {
setSubmitting(false)
}
}
return (
<div className="flex flex-col gap-6">
<div className="flex items-center gap-4">
<Button type="button" variant="outline" size="sm" onClick={() => router.push('/operations/loading')}>
<HugeiconsIcon icon={ArrowLeft01Icon} size={16} strokeWidth={2} />
Back
</Button>
<div>
<h1 className="text-2xl font-semibold text-foreground">New Loading Sheet</h1>
<p className="text-sm text-muted-foreground">
Select a route first. Confirmed Shop POs for that route&apos;s shops will then be
available to pick items from. Pick the ride to load last.
</p>
</div>
</div>
<div className="rounded-2xl border p-6">
<h3 className="mb-4 text-sm font-medium text-foreground">Route &amp; Warehouse</h3>
<FieldGroup>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
<div className="flex flex-col gap-1">
<label className="text-sm font-medium text-foreground">Region</label>
<Select value={regionId || ALL} onValueChange={(v) => setRegionId(!v || v === ALL ? '' : v)}>
<SelectTrigger>
<SelectValue placeholder="All regions" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL}>All regions</SelectItem>
{regionsList.map((r) => (
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1">
<label className="text-sm font-medium text-foreground">Route *</label>
<Select value={routeId} onValueChange={(v) => setRouteId(v ?? '')}>
<SelectTrigger>
<SelectValue placeholder="Select route..." />
</SelectTrigger>
<SelectContent>
{routesList.map((r) => (
<SelectItem key={r.id} value={r.id}>{r.routeName}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1">
<label className="text-sm font-medium text-foreground">Shop</label>
<Select
value={storeId || ALL}
onValueChange={(v) => setStoreId(!v || v === ALL ? '' : v)}
disabled={!routeId}
>
<SelectTrigger>
<SelectValue placeholder="All shops" />
</SelectTrigger>
<SelectContent>
<SelectItem value={ALL}>All shops on route</SelectItem>
{storesList.map((s) => (
<SelectItem key={s.id} value={s.id}>{s.storeName}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1">
<label className="text-sm font-medium text-foreground">Warehouse *</label>
<Select value={warehouseId} onValueChange={(v) => setWarehouseId(v ?? '')}>
<SelectTrigger>
<SelectValue placeholder="Select warehouse..." />
</SelectTrigger>
<SelectContent>
{warehousesList.map((w) => (
<SelectItem key={w.id} value={w.id}>{w.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</FieldGroup>
</div>
<div className="rounded-2xl border p-6">
<div className="mb-4">
<h3 className="text-sm font-medium text-foreground">Items</h3>
<p className="text-sm text-muted-foreground">
Pick items from confirmed Shop POs for the selected route/shop.
</p>
</div>
<div className="overflow-x-auto rounded-xl border">
<table className="w-full text-sm">
<thead className="bg-muted/50">
<tr>
<th className="w-10 px-3 py-2"></th>
<th className="px-3 py-2 text-left font-medium">Shop</th>
<th className="px-3 py-2 text-left font-medium">Item</th>
<th className="w-24 px-3 py-2 text-right font-medium">Ordered</th>
<th className="w-32 px-3 py-2 text-right font-medium">Qty to load</th>
</tr>
</thead>
<tbody>
{!routeId ? (
<tr><td colSpan={5} className="text-center text-muted-foreground px-3 py-6">Select a route to see its confirmed Shop POs.</td></tr>
) : loadingPos ? (
<tr><td colSpan={5} className="text-center text-muted-foreground px-3 py-6">Loading…</td></tr>
) : rows.length === 0 ? (
<tr><td colSpan={5} className="text-center text-muted-foreground px-3 py-6">No eligible Shop PO items found for this route.</td></tr>
) : (
rows.map((row) => {
const line = lines[row.shopPOItemId] ?? row
return (
<tr key={row.shopPOItemId} className="border-t">
<td className="px-3 py-2">
<Checkbox
checked={line.checked}
onCheckedChange={(v) => toggleLine(row, v === true)}
/>
</td>
<td className="px-3 py-2">{row.storeName}</td>
<td className="px-3 py-2">{row.itemName}</td>
<td className="px-3 py-2 text-right text-muted-foreground">{row.remainingQty}</td>
<td className="px-3 py-2">
<Input
type="number"
min={1}
max={row.remainingQty}
value={line.quantity}
disabled={!line.checked}
onChange={(e) => setLineQuantity(row, Number(e.target.value))}
/>
</td>
</tr>
)
})
)}
</tbody>
</table>
</div>
</div>
<div className="rounded-2xl border p-6">
<h3 className="mb-4 text-sm font-medium text-foreground">Ride &amp; Assignment</h3>
<FieldGroup>
<div className="grid gap-6 sm:grid-cols-2">
<div className="flex flex-col gap-1">
<label className="text-sm font-medium text-foreground">Ride (vehicle to load) *</label>
<Select value={rideId} onValueChange={(v) => setRideId(v ?? '')}>
<SelectTrigger>
<SelectValue placeholder="Select open ride..." />
</SelectTrigger>
<SelectContent>
{ridesList.map((r) => (
<SelectItem key={r.id} value={r.id}>
{r.vehicleNumberPlate} — {r.driverFullName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1">
<label className="text-sm font-medium text-foreground">Populated By *</label>
<Select value={populatedByUserId} onValueChange={(v) => setPopulatedByUserId(v ?? '')}>
<SelectTrigger>
<SelectValue placeholder="Select user..." />
</SelectTrigger>
<SelectContent>
{usersList.map((u) => (
<SelectItem key={u.id} value={u.id}>{u.fullName}</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-xs text-muted-foreground">Temporary — required until auth resolves the logged-in user automatically.</span>
</div>
</div>
</FieldGroup>
</div>
<div className="flex justify-end">
<div className="w-full rounded-2xl border p-6 sm:w-96">
<h3 className="text-sm font-medium text-foreground">Loading Sheet Summary</h3>
<p className="mt-1 text-sm text-muted-foreground">
{selectedRows.length} item{selectedRows.length === 1 ? '' : 's'} selected.
</p>
<Separator className="my-4" />
<div className="flex items-center justify-between">
<p className="text-sm font-medium text-foreground">Total Quantity</p>
<p className="text-xl font-semibold text-foreground">{totalQuantity}</p>
</div>
<div className="mt-6 flex flex-col gap-2">
<Button type="button" disabled={submitting} onClick={handleSubmit}>
{submitting ? 'Creating…' : 'Create Loading Sheet'}
</Button>
<Button type="button" variant="outline" onClick={() => router.push('/operations/loading')}>
Cancel
</Button>
</div>
</div>
</div>
</div>
)
}