feat: redesign shipment request cart as inventory-integrated flow
Some checks failed
Build and Deploy / build (push) Successful in 12m2s
Build and Deploy / deploy (push) Failing after 3s

Replace the wizard-style 4-step shipment cart with an inventory-page-
integrated flow matching the legacy portal UX. Users now add items
directly from inventory detail rows via "+" buttons, with a persistent
cart bar showing status. The "Complete Release" page is a flat form
instead of a multi-step wizard.

Key changes:
- Add ShipmentCartProvider context for cross-page cart state
- Add CartBar component (start/cancel release, view status)
- Integrate cart column into inventory detail table with per-row
  add buttons, plant mismatch indicators, and "Add All" support
- Rewrite /shipment-requests/new as flat Complete Release page
- Add check_only param to cart API (avoid auto-creating on mount)
- Add server-side plant constraint validation on cart items
- Add batch add API endpoint for "Add All" functionality
- Delete deprecated wizard cart and inventory browser dialog

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Lorentz Hinrichsen 2026-02-17 17:01:53 -05:00
parent e60e07c9a5
commit 500811f3e3
16 changed files with 1423 additions and 537 deletions

2
package-lock.json generated
View file

@ -12,7 +12,7 @@
"@hookform/resolvers": "^3.9.1", "@hookform/resolvers": "^3.9.1",
"@prisma/client": "^6.1.0", "@prisma/client": "^6.1.0",
"@radix-ui/react-accordion": "^1.2.2", "@radix-ui/react-accordion": "^1.2.2",
"@radix-ui/react-alert-dialog": "^1.1.4", "@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-avatar": "^1.1.2", "@radix-ui/react-avatar": "^1.1.2",
"@radix-ui/react-checkbox": "^1.1.3", "@radix-ui/react-checkbox": "^1.1.3",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.15",

View file

@ -21,7 +21,7 @@
"@hookform/resolvers": "^3.9.1", "@hookform/resolvers": "^3.9.1",
"@prisma/client": "^6.1.0", "@prisma/client": "^6.1.0",
"@radix-ui/react-accordion": "^1.2.2", "@radix-ui/react-accordion": "^1.2.2",
"@radix-ui/react-alert-dialog": "^1.1.4", "@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-avatar": "^1.1.2", "@radix-ui/react-avatar": "^1.1.2",
"@radix-ui/react-checkbox": "^1.1.3", "@radix-ui/react-checkbox": "^1.1.3",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.15",

View file

@ -9,6 +9,7 @@ import {
getQuestSession, getQuestSession,
getActiveCompany, getActiveCompany,
isSubUser, isSubUser,
hasPermission,
} from '@/lib/permissions'; } from '@/lib/permissions';
import { InventoryDetailTable } from '@/components/inventory/inventory-detail-table'; import { InventoryDetailTable } from '@/components/inventory/inventory-detail-table';
import { Card, CardContent } from '@/components/ui/card'; import { Card, CardContent } from '@/components/ui/card';
@ -74,6 +75,9 @@ async function InventoryDetailData({
const dbName = `[${process.env.PORTAL_DB_NAME || 'VorteqPortal'}]`; const dbName = `[${process.env.PORTAL_DB_NAME || 'VorteqPortal'}]`;
const sub = userIsSubUser ? 1 : 0; const sub = userIsSubUser ? 1 : 0;
// Check if user can create shipment requests (for cart integration)
const canShip = await hasPermission('create_shipment_request');
const details = await getInventoryDetails( const details = await getInventoryDetails(
category, category,
activeCompany.epicor_cust_id, activeCompany.epicor_cust_id,
@ -95,6 +99,8 @@ async function InventoryDetailData({
partNum={part} partNum={part}
plant={plant} plant={plant}
warehouse={warehouse} warehouse={warehouse}
cartEnabled={canShip}
category={category}
/> />
); );
} }

View file

@ -2,9 +2,11 @@ import {
getQuestSession, getQuestSession,
getActiveCompany, getActiveCompany,
getUserCompanies, getUserCompanies,
hasPermission,
} from '@/lib/permissions'; } from '@/lib/permissions';
import { PortalSidebar } from '@/components/layout/portal-sidebar'; import { PortalSidebar } from '@/components/layout/portal-sidebar';
import { PortalHeader } from '@/components/layout/portal-header'; import { PortalHeader } from '@/components/layout/portal-header';
import { PortalClientProviders } from '@/components/layout/portal-client-providers';
import { Breadcrumb } from '@/components/layout/breadcrumb'; import { Breadcrumb } from '@/components/layout/breadcrumb';
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import { getUnreadAlertCount } from '@/services/notifications'; import { getUnreadAlertCount } from '@/services/notifications';
@ -33,6 +35,9 @@ export default async function PortalLayout({
// Get available companies for the switcher // Get available companies for the switcher
const companies = await getUserCompanies(); const companies = await getUserCompanies();
// Check if user can create shipment requests (for cart provider)
const hasShipmentPermission = await hasPermission('create_shipment_request');
return ( return (
<div className="flex min-h-screen"> <div className="flex min-h-screen">
<PortalSidebar isAdmin={isAdmin} permissions={session.permissionRules} /> <PortalSidebar isAdmin={isAdmin} permissions={session.permissionRules} />
@ -51,7 +56,9 @@ export default async function PortalLayout({
/> />
<main className="p-6"> <main className="p-6">
<Breadcrumb /> <Breadcrumb />
{children} <PortalClientProviders hasShipmentPermission={hasShipmentPermission}>
{children}
</PortalClientProviders>
</main> </main>
</div> </div>
</div> </div>

View file

@ -1,12 +1,334 @@
'use client'; 'use client';
import { ShipmentRequestCart } from '@/components/requests/shipment-request-cart'; import { useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useShipmentCart } from '@/hooks/use-shipment-cart';
import { CartBar } from '@/components/requests/cart-bar';
import { CartItemsTable } from '@/components/requests/cart-items-table';
import { ShipToSelector } from '@/components/requests/ship-to-selector';
import { CartHeaderForm } from '@/components/requests/cart-header-form';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
Table,
TableBody,
TableCell,
TableRow,
} from '@/components/ui/table';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { ArrowLeft, Loader2, Send } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import Link from 'next/link';
import type { UpdateCartHeaderPayload } from '@/types/requests';
/**
* "Complete Release" page flat single-page form for reviewing cart items,
* setting ship-to address and order details, and submitting.
*/
export default function CompleteReleasePage() {
const router = useRouter();
const { toast } = useToast();
const {
cart,
cartLoading,
hasCart,
totalLbs,
refreshCart,
removeItem,
} = useShipmentCart();
const [submitting, setSubmitting] = useState(false);
// Group items by part number for totals summary
const totalsByPart = useMemo(() => {
if (!cart) return [];
const groups = new Map<string, { part_num: string; totalQty: number; count: number }>();
for (const item of cart.details) {
const existing = groups.get(item.part_num);
if (existing) {
existing.totalQty += item.quantity;
existing.count += 1;
} else {
groups.set(item.part_num, {
part_num: item.part_num,
totalQty: item.quantity,
count: 1,
});
}
}
return Array.from(groups.values());
}, [cart]);
const grandTotal = useMemo(() => Math.round(totalLbs), [totalLbs]);
// Update cart header
const updateHeader = async (data: UpdateCartHeaderPayload) => {
if (!cart) return;
const res = await fetch('/api/shipment-requests/cart', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: cart.id, ...data }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || 'Failed to update cart');
}
await refreshCart();
};
// Update cart item
const updateItem = async (
detailId: string,
data: { quantity?: number; notes?: string | null }
) => {
if (!cart) return;
const res = await fetch(`/api/shipment-requests/cart/items/${detailId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ request_id: cart.id, ...data }),
});
if (!res.ok) {
const err = await res.json();
toast({
title: 'Error',
description: err.error || 'Failed to update item',
variant: 'destructive',
});
return;
}
await refreshCart();
};
// Submit cart
const handleSubmit = async () => {
if (!cart) return;
setSubmitting(true);
try {
const res = await fetch('/api/shipment-requests/cart/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: cart.id }),
});
if (!res.ok) {
const err = await res.json();
toast({
title: 'Error',
description: err.error || 'Failed to submit request',
variant: 'destructive',
});
return;
}
toast({ title: 'Shipment request submitted successfully!' });
router.push('/shipment-requests');
} finally {
setSubmitting(false);
}
};
if (cartLoading) {
return (
<div>
<h1 className="mb-6 text-3xl font-bold">Complete Shipment Release</h1>
<Card>
<CardContent className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</CardContent>
</Card>
</div>
);
}
// No active cart
if (!hasCart || !cart) {
return (
<div>
<h1 className="mb-6 text-3xl font-bold">Complete Shipment Release</h1>
<Card>
<CardContent className="p-6 text-center">
<p className="mb-4 text-muted-foreground">
You must add some items to your shipment release in order to
complete it.
</p>
<Link href="/inventory">
<Button className="bg-teal-700 hover:bg-teal-800">
Select Items
</Button>
</Link>
</CardContent>
</Card>
</div>
);
}
const itemCount = cart.details.length;
const canSubmit =
itemCount > 0 && !!cart.ship_to_address && !submitting;
export default function NewShipmentRequestPage() {
return ( return (
<div> <div className="space-y-6">
<h1 className="mb-6 text-3xl font-bold">New Shipment Request</h1> <h1 className="text-3xl font-bold">Complete Shipment Release</h1>
<ShipmentRequestCart />
{/* Cart bar (hide "View/Complete Release" button since we're on this page) */}
<CartBar hideCompleteButton />
{/* Empty cart warning */}
{itemCount === 0 && (
<Card>
<CardContent className="p-6 text-center">
<p className="mb-4 text-muted-foreground">
You must add some items to your shipment release in order to
complete it.
</p>
<Link href="/inventory">
<Button className="bg-teal-700 hover:bg-teal-800">
Select Items
</Button>
</Link>
</CardContent>
</Card>
)}
{/* Items table */}
{itemCount > 0 && (
<>
<CartItemsTable
items={cart.details}
variant="ship"
onRemoveItem={removeItem}
onUpdateItem={updateItem}
onOpenBrowser={() => router.push('/inventory')}
/>
{/* Totals by Part */}
<Card>
<CardHeader>
<CardTitle>Totals by Part</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-hidden rounded-md border">
<Table>
<thead>
<tr className="bg-teal-700 text-white">
<th className="px-4 py-2 text-left text-xs font-semibold uppercase">
Part #
</th>
<th className="px-4 py-2 text-right text-xs font-semibold uppercase">
# Items
</th>
<th className="px-4 py-2 text-right text-xs font-semibold uppercase">
Total Lbs
</th>
</tr>
</thead>
<TableBody>
{totalsByPart.map((group, i) => (
<TableRow
key={group.part_num}
className={i % 2 === 0 ? 'bg-muted/30' : ''}
>
<TableCell className="font-medium">
{group.part_num}
</TableCell>
<TableCell className="text-right">
{group.count}
</TableCell>
<TableCell className="text-right">
{Math.round(group.totalQty).toLocaleString('en-US')}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
<div className="mt-3 text-right text-lg font-bold">
Total Shipment: {grandTotal.toLocaleString('en-US')} lbs
</div>
</CardContent>
</Card>
</>
)}
{/* Ship-To Address */}
<ShipToSelector
selectedAddress={cart.ship_to_address}
onSelect={(address) => updateHeader({ ship_to_address: address })}
onNext={() => {
/* no-op — flat page, no stepper */
}}
/>
{/* Order Details Form */}
<CartHeaderForm
initialData={{
order_number: cart.order_number,
po_number: cart.po_number,
release_number: cart.release_number,
pickup_date: cart.pickup_date,
instructions: cart.instructions,
email_recipients: cart.email_recipients,
}}
onSave={updateHeader}
onBack={() => router.push('/inventory')}
onNext={() => {
/* no-op — flat page */
}}
readOnly={false}
/>
{/* Action buttons */}
<div className="flex items-center justify-between">
<Link href="/inventory">
<Button variant="outline">
<ArrowLeft className="mr-2 h-4 w-4" />
Back to Inventory
</Button>
</Link>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
disabled={!canSubmit}
className="bg-teal-700 hover:bg-teal-800"
>
{submitting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Send className="mr-2 h-4 w-4" />
)}
Submit Shipment Release
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Submit Shipment Release?</AlertDialogTitle>
<AlertDialogDescription>
This will submit your shipment release request with{' '}
{itemCount} item{itemCount !== 1 ? 's' : ''} totaling{' '}
{grandTotal.toLocaleString('en-US')} lbs. This action cannot
be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={handleSubmit}
className="bg-teal-700 hover:bg-teal-800"
>
Submit
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div> </div>
); );
} }

View file

@ -0,0 +1,50 @@
import { NextRequest, NextResponse } from 'next/server';
import { getQuestSession, getActiveCompany, requirePermission } from '@/lib/permissions';
import { addBatchCartItems } from '@/services/ship-requests';
import type { AddShipCartItemPayload } from '@/types/requests';
/**
* POST: Add multiple items to the shipment request cart in one request.
* Used by the "Add All" button on the inventory detail page.
*/
export async function POST(request: NextRequest) {
const session = await getQuestSession();
const activeCompany = await getActiveCompany();
if (!session || !activeCompany) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
await requirePermission('create_shipment_request');
} catch {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
try {
const body = (await request.json()) as {
request_id: string;
items: AddShipCartItemPayload[];
};
if (!body.request_id) {
return NextResponse.json({ error: 'Request ID is required' }, { status: 400 });
}
if (!Array.isArray(body.items) || body.items.length === 0) {
return NextResponse.json({ error: 'Items array is required' }, { status: 400 });
}
const result = await addBatchCartItems(body.request_id, activeCompany.id, body.items);
return NextResponse.json({
success: true,
added: result.added,
skipped: result.skipped,
errors: result.errors,
});
} catch (error) {
console.error('Error batch adding cart items:', error);
const message = error instanceof Error ? error.message : 'Internal server error';
return NextResponse.json({ error: message }, { status: 500 });
}
}

View file

@ -1,10 +1,11 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { getQuestSession, getActiveCompany, requirePermission } from '@/lib/permissions'; import { getQuestSession, getActiveCompany, requirePermission } from '@/lib/permissions';
import { addCartItem, removeCartItem } from '@/services/ship-requests'; import { addCartItem, removeCartItem, getRequestById } from '@/services/ship-requests';
import type { AddShipCartItemPayload } from '@/types/requests'; import type { AddShipCartItemPayload } from '@/types/requests';
/** /**
* POST: Add an item to the shipment request cart * POST: Add an item to the shipment request cart.
* Enforces single-plant constraint: all items must be from the same plant.
*/ */
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
const session = await getQuestSession(); const session = await getQuestSession();
@ -35,13 +36,35 @@ export async function POST(request: NextRequest) {
); );
} }
// Plant constraint: check existing items' plant
const cart = await getRequestById(request_id, activeCompany.id);
if (cart && cart.details.length > 0) {
const firstDetail = cart.details[0]!;
const lockedPlant = firstDetail.plant;
if (item.plant !== lockedPlant) {
return NextResponse.json(
{
success: false,
action: 'bad_plant',
reason: `Cannot add items from a different plant. Your shipment release is locked to: ${lockedPlant}`,
},
{ status: 409 }
);
}
}
const detail = await addCartItem(request_id, activeCompany.id, item); const detail = await addCartItem(request_id, activeCompany.id, item);
return NextResponse.json(detail, { status: 201 }); return NextResponse.json({ success: true, detail }, { status: 201 });
} catch (error) { } catch (error) {
console.error('Error adding cart item:', error); console.error('Error adding cart item:', error);
const message = error instanceof Error ? error.message : 'Internal server error'; const message = error instanceof Error ? error.message : 'Internal server error';
const status = message.includes('already exists') ? 409 : 500; if (message.includes('already exists')) {
return NextResponse.json({ error: message }, { status }); return NextResponse.json(
{ success: false, action: 'in_cart', reason: message },
{ status: 409 }
);
}
return NextResponse.json({ error: message }, { status: 500 });
} }
} }

View file

@ -1,14 +1,17 @@
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { getQuestSession, getActiveCompany, requirePermission } from '@/lib/permissions'; import { getQuestSession, getActiveCompany, requirePermission } from '@/lib/permissions';
import { getOrCreateCart, updateCartHeader } from '@/services/ship-requests'; import { getOrCreateCart, getActiveCart, updateCartHeader } from '@/services/ship-requests';
import type { UpdateCartHeaderPayload } from '@/types/requests'; import type { UpdateCartHeaderPayload } from '@/types/requests';
export const dynamic = 'force-dynamic'; export const dynamic = 'force-dynamic';
/** /**
* GET: Get or create an active shipment request cart * GET: Get or create an active shipment request cart
*
* Query params:
* - check_only=true: Only check for existing active cart, return 204 if none exists
*/ */
export async function GET() { export async function GET(request: NextRequest) {
const session = await getQuestSession(); const session = await getQuestSession();
const activeCompany = await getActiveCompany(); const activeCompany = await getActiveCompany();
@ -23,6 +26,16 @@ export async function GET() {
} }
try { try {
const checkOnly = request.nextUrl.searchParams.get('check_only') === 'true';
if (checkOnly) {
const cart = await getActiveCart(session.user.id, activeCompany.id);
if (!cart) {
return new NextResponse(null, { status: 204 });
}
return NextResponse.json(cart);
}
const cart = await getOrCreateCart(session.user.id, activeCompany.id); const cart = await getOrCreateCart(session.user.id, activeCompany.id);
return NextResponse.json(cart); return NextResponse.json(cart);
} catch (error) { } catch (error) {

View file

@ -17,11 +17,20 @@ import {
TableCell, TableCell,
TableRow, TableRow,
} from '@/components/ui/table'; } from '@/components/ui/table';
import { Download, Search } from 'lucide-react'; import { Download, Search, Plus, Ban, Loader2 } from 'lucide-react';
import { import {
SortableTableHead, SortableTableHead,
useSortableTable, useSortableTable,
} from '@/components/ui/sortable-table-head'; } from '@/components/ui/sortable-table-head';
import {
useShipmentCartOptional,
cartItemKey,
} from '@/hooks/use-shipment-cart';
import { CartBar } from '@/components/requests/cart-bar';
import { useToast } from '@/hooks/use-toast';
// Categories where items cannot be added to a shipment release
const BLOCKED_CATEGORIES = ['unprocessed-rr', 'processed-rr'];
type Props = { type Props = {
data: InventoryDetailRow[]; data: InventoryDetailRow[];
@ -29,6 +38,10 @@ type Props = {
plant?: string; plant?: string;
warehouse?: string; warehouse?: string;
embedded?: boolean; embedded?: boolean;
/** Whether to show cart integration (add-to-cart buttons, cart bar) */
cartEnabled?: boolean;
/** Current inventory category (used to block R&R) */
category?: string;
}; };
function formatNum(val: number | string | null | undefined): string { function formatNum(val: number | string | null | undefined): string {
@ -88,11 +101,21 @@ function flattenRow(row: InventoryDetailRow): FlatDetailRow {
function DetailTableContent({ function DetailTableContent({
data, data,
partNum, partNum,
plant,
cartEnabled = false,
category,
}: { }: {
data: InventoryDetailRow[]; data: InventoryDetailRow[];
partNum?: string; partNum?: string;
plant?: string;
cartEnabled?: boolean;
category?: string;
}) { }) {
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState('');
const [addingIdx, setAddingIdx] = useState<number | null>(null);
const [addingAll, setAddingAll] = useState(false);
const cartCtx = useShipmentCartOptional();
const { toast } = useToast();
const flatData = data.map(flattenRow); const flatData = data.map(flattenRow);
@ -113,6 +136,101 @@ function DetailTableContent({
const { sortKey, sortDirection, handleSort, sortedData } = const { sortKey, sortDirection, handleSort, sortedData } =
useSortableTable(filteredData); useSortableTable(filteredData);
// Cart state
const showCartColumn =
cartEnabled &&
cartCtx &&
cartCtx.hasCart &&
category &&
!BLOCKED_CATEGORIES.includes(category);
const cartPlant = cartCtx?.cartPlant;
const isPlantMismatch = !!(
showCartColumn &&
cartPlant &&
plant &&
cartPlant !== plant
);
// Build payload for a row
const buildPayload = (raw: InventoryDetailRow) => ({
part_num: String(raw.CustPartNum ?? raw.LotNum ?? ''),
lot_num: raw.LotNum ? String(raw.LotNum) : undefined,
plant: plant || String(raw.WIP_FG ?? ''),
warehouse: raw.Bin ? String(raw.Bin) : undefined,
quantity: Number(raw.OnHandQty ?? 0),
});
// Check if a row is in the cart
const isInCart = (raw: InventoryDetailRow) => {
if (!cartCtx) return false;
const key = cartItemKey(
String(raw.CustPartNum ?? raw.LotNum ?? ''),
raw.LotNum ? String(raw.LotNum) : null,
plant || String(raw.WIP_FG ?? ''),
raw.Bin ? String(raw.Bin) : null
);
return cartCtx.cartItemMap.has(key);
};
const handleAddItem = async (raw: InventoryDetailRow, idx: number) => {
if (!cartCtx) return;
setAddingIdx(idx);
try {
const result = await cartCtx.addItem(buildPayload(raw));
if (result.success) {
toast({ title: 'Item added to shipment' });
} else if (result.action === 'bad_plant') {
toast({
title: 'Plant mismatch',
description: result.reason,
variant: 'destructive',
});
} else if (result.action === 'in_cart') {
toast({
title: 'Already in cart',
description: 'This item is already in your shipment release.',
});
} else {
toast({
title: 'Error',
description: result.reason || 'Failed to add item',
variant: 'destructive',
});
}
} finally {
setAddingIdx(null);
}
};
const handleAddAll = async () => {
if (!cartCtx) return;
setAddingAll(true);
try {
const items = data
.filter((raw) => !isInCart(raw))
.map(buildPayload);
if (items.length === 0) {
toast({ title: 'All items are already in your shipment' });
return;
}
await cartCtx.addAllItems(items);
toast({
title: 'Items added',
description: `Added items to your shipment release.`,
});
} finally {
setAddingAll(false);
}
};
// Count how many items can be added (not already in cart)
const availableToAdd = showCartColumn && !isPlantMismatch
? data.filter((raw) => !isInCart(raw)).length
: 0;
const handleExportCSV = () => { const handleExportCSV = () => {
const headers = [ const headers = [
'Cust Part#', 'Cust Part#',
@ -162,8 +280,25 @@ function DetailTableContent({
window.URL.revokeObjectURL(url); window.URL.revokeObjectURL(url);
}; };
const totalColumns = showCartColumn ? 15 : 14;
return ( return (
<> <>
{/* Plant mismatch warning */}
{showCartColumn && isPlantMismatch && (
<div className="mb-4 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800">
<strong>You cannot add items to your shipment release from this plant</strong>{' '}
because items from another plant have already been selected.
</div>
)}
{/* R&R blocked warning */}
{cartEnabled && cartCtx?.hasCart && category && BLOCKED_CATEGORIES.includes(category) && (
<div className="mb-4 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800">
<strong>Rejects and Returns may not be added to a shipment release.</strong>
</div>
)}
<div className="mb-4 flex items-center gap-4"> <div className="mb-4 flex items-center gap-4">
<div className="relative flex-1"> <div className="relative flex-1">
<Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" /> <Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
@ -174,6 +309,21 @@ function DetailTableContent({
className="pl-8" className="pl-8"
/> />
</div> </div>
{showCartColumn && !isPlantMismatch && availableToAdd > 0 && (
<Button
onClick={handleAddAll}
disabled={addingAll}
size="sm"
className="bg-teal-700 hover:bg-teal-800"
>
{addingAll ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
Add All
</Button>
)}
<Button onClick={handleExportCSV} variant="outline" size="sm"> <Button onClick={handleExportCSV} variant="outline" size="sm">
<Download className="mr-2 h-4 w-4" /> <Download className="mr-2 h-4 w-4" />
Export CSV Export CSV
@ -184,6 +334,11 @@ function DetailTableContent({
<Table> <Table>
<thead> <thead>
<tr className="bg-indigo-600 text-white"> <tr className="bg-indigo-600 text-white">
{showCartColumn && (
<th className="w-10 px-2 py-2 text-center text-xs font-semibold uppercase">
{/* Cart action column */}
</th>
)}
<SortableTableHead <SortableTableHead
sortKey="CustPartNum" sortKey="CustPartNum"
currentSortKey={sortKey} currentSortKey={sortKey}
@ -306,41 +461,87 @@ function DetailTableContent({
{sortedData.length === 0 ? ( {sortedData.length === 0 ? (
<TableRow> <TableRow>
<TableCell <TableCell
colSpan={14} colSpan={totalColumns}
className="text-center text-muted-foreground" className="text-center text-muted-foreground"
> >
No inventory found No inventory found
</TableCell> </TableCell>
</TableRow> </TableRow>
) : ( ) : (
sortedData.map((row, i) => ( sortedData.map((row, i) => {
<TableRow key={i} className={i % 2 === 0 ? 'bg-muted/30' : ''}> const rawRow = data[flatData.indexOf(
<TableCell>{row.CustPartNum}</TableCell> flatData.find(
<TableCell>{row.SkidNum}</TableCell> (f) =>
<TableCell>{row.LotNum}</TableCell> f.CustPartNum === row.CustPartNum &&
<TableCell>{row.MfgLot}</TableCell> f.LotNum === row.LotNum &&
<TableCell>{row.Bin}</TableCell> f.Bin === row.Bin &&
<TableCell className="text-right"> f.OnHandQty === row.OnHandQty
{formatNum(row.OnHandQty)} )!
</TableCell> )];
<TableCell className="text-right"> const inCart = rawRow ? isInCart(rawRow) : false;
{formatNum(row.LinearFt)}
</TableCell> return (
<TableCell className="text-right"> <TableRow
{formatNum(row.TheoreticalWeight)} key={i}
</TableCell> className={`${i % 2 === 0 ? 'bg-muted/30' : ''} ${
<TableCell>{row.WIP_FG}</TableCell> inCart ? 'bg-purple-50' : ''
<TableCell className="text-right"> }`}
{formatNum(row.NumCoilsPerSkid)} >
</TableCell> {showCartColumn && (
<TableCell>{row.CustomerPoNum}</TableCell> <TableCell className="w-10 px-2 text-center">
<TableCell>{row.SalesOrderJob}</TableCell> {isPlantMismatch ? (
<TableCell>{row.AllocRelease}</TableCell> <span title="Another plant already selected for your shipment">
<TableCell> <Ban className="mx-auto h-4 w-4 text-gray-400" />
{formatDate(row.DateProcessedToInventory)} </span>
</TableCell> ) : inCart ? (
</TableRow> <span
)) className="inline-block h-4 w-4 rounded-full bg-purple-500"
title="In your shipment"
/>
) : (
<button
type="button"
onClick={() => rawRow && handleAddItem(rawRow, i)}
disabled={addingIdx === i}
className="inline-flex h-6 w-6 items-center justify-center rounded-full text-teal-700 hover:bg-teal-100 disabled:opacity-50"
title="Add to shipment"
>
{addingIdx === i ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Plus className="h-3.5 w-3.5" />
)}
</button>
)}
</TableCell>
)}
<TableCell>{row.CustPartNum}</TableCell>
<TableCell>{row.SkidNum}</TableCell>
<TableCell>{row.LotNum}</TableCell>
<TableCell>{row.MfgLot}</TableCell>
<TableCell>{row.Bin}</TableCell>
<TableCell className="text-right">
{formatNum(row.OnHandQty)}
</TableCell>
<TableCell className="text-right">
{formatNum(row.LinearFt)}
</TableCell>
<TableCell className="text-right">
{formatNum(row.TheoreticalWeight)}
</TableCell>
<TableCell>{row.WIP_FG}</TableCell>
<TableCell className="text-right">
{formatNum(row.NumCoilsPerSkid)}
</TableCell>
<TableCell>{row.CustomerPoNum}</TableCell>
<TableCell>{row.SalesOrderJob}</TableCell>
<TableCell>{row.AllocRelease}</TableCell>
<TableCell>
{formatDate(row.DateProcessedToInventory)}
</TableCell>
</TableRow>
);
})
)} )}
</TableBody> </TableBody>
</Table> </Table>
@ -359,24 +560,37 @@ export function InventoryDetailTable({
plant, plant,
warehouse, warehouse,
embedded = false, embedded = false,
cartEnabled = false,
category,
}: Props) { }: Props) {
if (embedded) { if (embedded) {
return <DetailTableContent data={data} partNum={partNum} />; return <DetailTableContent data={data} partNum={partNum} plant={plant} />;
} }
return ( return (
<Card> <>
<CardHeader> {/* Cart bar (only shown when cartEnabled and user has permission) */}
<CardTitle>Inventory Detail</CardTitle> {cartEnabled && <CartBar />}
<CardDescription>
{partNum && `Part: ${partNum}`} <Card>
{plant && ` | Plant: ${plant}`} <CardHeader>
{warehouse && ` | Warehouse: ${warehouse}`} <CardTitle>Inventory Detail</CardTitle>
</CardDescription> <CardDescription>
</CardHeader> {partNum && `Part: ${partNum}`}
<CardContent> {plant && ` | Plant: ${plant}`}
<DetailTableContent data={data} partNum={partNum} /> {warehouse && ` | Warehouse: ${warehouse}`}
</CardContent> </CardDescription>
</Card> </CardHeader>
<CardContent>
<DetailTableContent
data={data}
partNum={partNum}
plant={plant}
cartEnabled={cartEnabled}
category={category}
/>
</CardContent>
</Card>
</>
); );
} }

View file

@ -0,0 +1,24 @@
'use client';
import { ShipmentCartProvider } from '@/hooks/use-shipment-cart';
import type { ReactNode } from 'react';
type Props = {
children: ReactNode;
hasShipmentPermission: boolean;
};
/**
* Client-side providers that wrap the portal layout.
* Currently provides ShipmentCartProvider for users with the create_shipment_request permission.
*/
export function PortalClientProviders({
children,
hasShipmentPermission,
}: Props) {
if (!hasShipmentPermission) {
return <>{children}</>;
}
return <ShipmentCartProvider>{children}</ShipmentCartProvider>;
}

View file

@ -0,0 +1,162 @@
'use client';
import { useShipmentCartOptional } from '@/hooks/use-shipment-cart';
import { Button } from '@/components/ui/button';
import { Loader2, Package, X } from 'lucide-react';
import Link from 'next/link';
import { useState } from 'react';
import { useToast } from '@/hooks/use-toast';
type Props = {
/** Hide the "View/Complete Release" button (used when already on that page) */
hideCompleteButton?: boolean;
};
/**
* Persistent cart status bar for inventory pages.
*
* States:
* - Loading: spinner
* - No cart: "Start Shipment Release" button
* - Cart open: Shows item count, total lbs, plant, ship-to summary,
* "View/Complete Release" link, "Cancel" button
*/
export function CartBar({ hideCompleteButton = false }: Props) {
const cartCtx = useShipmentCartOptional();
const { toast } = useToast();
const [starting, setStarting] = useState(false);
const [cancelling, setCancelling] = useState(false);
// If no cart provider, don't render anything
if (!cartCtx) return null;
const { cart, cartLoading, hasCart, totalLbs, cartPlant, startCart, cancelCart } = cartCtx;
if (cartLoading) {
return (
<div className="mb-4 flex items-center justify-center rounded-md border bg-muted/30 p-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
);
}
// No active cart — show "Start Shipment Release" button
if (!hasCart) {
return (
<div className="mb-4 rounded-md border bg-muted/30 p-3">
<Button
onClick={async () => {
setStarting(true);
try {
await startCart();
toast({ title: 'Shipment release started' });
} catch {
toast({
title: 'Error',
description: 'Failed to start shipment release',
variant: 'destructive',
});
} finally {
setStarting(false);
}
}}
disabled={starting}
className="bg-teal-700 hover:bg-teal-800"
>
{starting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Package className="mr-2 h-4 w-4" />
)}
Start Shipment Release
</Button>
</div>
);
}
// Active cart — show status bar
const itemCount = cart?.details.length ?? 0;
const formattedLbs = Math.round(totalLbs).toLocaleString('en-US');
const shipTo = cart?.ship_to_address;
return (
<div className="mb-4 rounded-md border border-teal-200 bg-teal-50 p-3">
<div className="flex flex-wrap items-start justify-between gap-4">
{/* Left: Cart info */}
<div className="flex flex-wrap gap-x-6 gap-y-1 text-sm">
<div>
<span className="font-semibold text-teal-800">
Shipment Release
</span>
</div>
<div>
<span className="text-teal-600">Date Started: </span>
<span className="font-medium">
{cart?.created_at
? new Date(cart.created_at).toLocaleDateString()
: '-'}
</span>
</div>
{cartPlant && (
<div>
<span className="text-teal-600">Plant: </span>
<span className="font-medium">{cartPlant}</span>
</div>
)}
<div>
<span className="text-teal-600">Items Selected: </span>
<span className="font-medium">{itemCount}</span>
</div>
<div>
<span className="text-teal-600">Total Lbs: </span>
<span className="font-medium">{formattedLbs}</span>
</div>
{shipTo && (
<div>
<span className="text-teal-600">Ship To: </span>
<span className="font-medium">{shipTo}</span>
</div>
)}
</div>
{/* Right: Action buttons */}
<div className="flex items-center gap-2">
{!hideCompleteButton && (
<Link href="/shipment-requests/new">
<Button size="sm" className="bg-teal-700 hover:bg-teal-800">
View / Complete Release
</Button>
</Link>
)}
<Button
size="sm"
variant="destructive"
onClick={async () => {
setCancelling(true);
try {
await cancelCart();
toast({ title: 'Shipment release cancelled' });
} catch {
toast({
title: 'Error',
description: 'Failed to cancel shipment release',
variant: 'destructive',
});
} finally {
setCancelling(false);
}
}}
disabled={cancelling}
>
{cancelling ? (
<Loader2 className="mr-1 h-3 w-3 animate-spin" />
) : (
<X className="mr-1 h-3 w-3" />
)}
Cancel
</Button>
</div>
</div>
</div>
);
}

View file

@ -1,219 +0,0 @@
'use client';
import { useEffect, useState } from 'react';
import type { InventoryDetailRow } from '@/services/inventory';
import type { AddShipCartItemPayload } from '@/types/requests';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Table,
TableBody,
TableCell,
TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Search, Plus, Loader2, Package } from 'lucide-react';
type Props = {
open: boolean;
onClose: () => void;
onAddItem: (item: AddShipCartItemPayload) => Promise<void>;
};
type InventoryCategory = 'wip' | 'finished-goods' | 'processed-other';
const CATEGORIES: { value: InventoryCategory; label: string }[] = [
{ value: 'finished-goods', label: 'Finished Goods' },
{ value: 'wip', label: 'Work in Progress' },
{ value: 'processed-other', label: 'Processed Other' },
];
export function InventoryBrowserDialog({ open, onClose, onAddItem }: Props) {
const [category, setCategory] = useState<InventoryCategory>('finished-goods');
const [items, setItems] = useState<InventoryDetailRow[] | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [searchTerm, setSearchTerm] = useState('');
const [addingIndex, setAddingIndex] = useState<number | null>(null);
const [quantities, setQuantities] = useState<Record<number, string>>({});
useEffect(() => {
if (!open) return;
setLoading(true);
setError(null);
setItems(null);
fetch(`/api/inventory/details?category=${category}`)
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((json) => {
setItems(json.data || []);
})
.catch((err) => setError(err.message))
.finally(() => setLoading(false));
}, [open, category]);
const filtered = items?.filter((item) => {
if (!searchTerm) return true;
const s = searchTerm.toLowerCase();
return (
String(item.LotNum || '').toLowerCase().includes(s) ||
String(item.CustPartNum || '').toLowerCase().includes(s) ||
String(item.Bin || '').toLowerCase().includes(s) ||
String(item.SkidNum || '').toLowerCase().includes(s)
);
});
const handleAdd = async (item: InventoryDetailRow, index: number) => {
setAddingIndex(index);
try {
const qty = parseFloat(quantities[index] || '0') || (item.OnHandQty ?? 0);
await onAddItem({
part_num: String(item.CustPartNum || item.LotNum || ''),
lot_num: item.LotNum ? String(item.LotNum) : undefined,
plant: String(item.WIP_FG || ''),
warehouse: item.Bin ? String(item.Bin) : undefined,
quantity: qty,
});
} finally {
setAddingIndex(null);
}
};
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-4xl max-h-[80vh] overflow-hidden flex flex-col">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Package className="h-5 w-5" />
Browse Inventory
</DialogTitle>
</DialogHeader>
<div className="flex gap-2 mb-3">
{CATEGORIES.map((cat) => (
<Button
key={cat.value}
variant={category === cat.value ? 'default' : 'outline'}
size="sm"
onClick={() => setCategory(cat.value)}
className={category === cat.value ? 'bg-teal-700 hover:bg-teal-800' : ''}
>
{cat.label}
</Button>
))}
</div>
<div className="relative mb-3">
<Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search by lot#, part#, bin..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-8"
/>
</div>
<div className="flex-1 overflow-auto">
{loading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : error ? (
<p className="py-4 text-center text-sm text-destructive">
Failed to load inventory: {error}
</p>
) : filtered && filtered.length === 0 ? (
<p className="py-4 text-center text-sm text-muted-foreground">
No inventory items found.
</p>
) : filtered ? (
<div className="rounded-md border">
<Table>
<thead>
<tr className="bg-teal-700 text-white">
<th className="px-3 py-2 text-left text-xs font-semibold uppercase">
Lot #
</th>
<th className="px-3 py-2 text-left text-xs font-semibold uppercase">
Part #
</th>
<th className="px-3 py-2 text-left text-xs font-semibold uppercase">
Bin
</th>
<th className="px-3 py-2 text-right text-xs font-semibold uppercase">
On Hand
</th>
<th className="px-3 py-2 text-right text-xs font-semibold uppercase">
Qty
</th>
<th className="px-3 py-2 text-center text-xs font-semibold uppercase">
Add
</th>
</tr>
</thead>
<TableBody>
{filtered.slice(0, 100).map((item, i) => (
<TableRow
key={`${item.LotNum}-${item.Bin}-${i}`}
className={i % 2 === 0 ? 'bg-muted/30' : ''}
>
<TableCell className="font-medium">
{item.LotNum || '-'}
</TableCell>
<TableCell>{item.CustPartNum || '-'}</TableCell>
<TableCell>{item.Bin || '-'}</TableCell>
<TableCell className="text-right">
{item.OnHandQty ?? 0}
</TableCell>
<TableCell className="text-right">
<Input
type="number"
className="h-7 w-20 text-right"
placeholder={String(item.OnHandQty ?? 0)}
value={quantities[i] ?? ''}
onChange={(e) =>
setQuantities((prev) => ({
...prev,
[i]: e.target.value,
}))
}
min={0}
step="any"
/>
</TableCell>
<TableCell className="text-center">
<Button
size="sm"
variant="ghost"
onClick={() => handleAdd(item, i)}
disabled={addingIndex === i}
className="text-teal-700 hover:text-teal-900"
>
<Plus className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{filtered.length > 100 && (
<p className="p-2 text-center text-xs text-muted-foreground">
Showing first 100 of {filtered.length} items. Use search to narrow results.
</p>
)}
</div>
) : null}
</div>
</DialogContent>
</Dialog>
);
}

View file

@ -1,259 +0,0 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import type {
ShipRequestHeader,
AddShipCartItemPayload,
UpdateCartHeaderPayload,
} from '@/types/requests';
import { RequestStepper, type StepConfig } from './request-stepper';
import { ShipToSelector } from './ship-to-selector';
import { CartItemsTable } from './cart-items-table';
import { CartHeaderForm } from './cart-header-form';
import { CartReview } from './cart-review';
import { InventoryBrowserDialog } from './inventory-browser-dialog';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Loader2, ArrowLeft, ArrowRight } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useToast } from '@/hooks/use-toast';
const STEPS: StepConfig[] = [
{ label: 'Address', description: 'Select ship-to' },
{ label: 'Items', description: 'Add items' },
{ label: 'Details', description: 'Order info' },
{ label: 'Review', description: 'Submit' },
];
export function ShipmentRequestCart() {
const router = useRouter();
const { toast } = useToast();
const [cart, setCart] = useState<ShipRequestHeader | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [currentStep, setCurrentStep] = useState(0);
const [browserOpen, setBrowserOpen] = useState(false);
// Fetch or create cart
const fetchCart = useCallback(async () => {
try {
const res = await fetch('/api/shipment-requests/cart');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
setCart(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load cart');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchCart();
}, [fetchCart]);
// Update cart header (ship-to, details, etc.)
const updateHeader = async (data: UpdateCartHeaderPayload) => {
if (!cart) return;
const res = await fetch('/api/shipment-requests/cart', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: cart.id, ...data }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || 'Failed to update cart');
}
const updated = await res.json();
setCart(updated);
};
// Add item to cart
const addItem = async (item: AddShipCartItemPayload) => {
if (!cart) return;
const res = await fetch('/api/shipment-requests/cart/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ request_id: cart.id, ...item }),
});
if (!res.ok) {
const err = await res.json();
toast({
title: 'Error',
description: err.error || 'Failed to add item',
variant: 'destructive',
});
return;
}
toast({ title: 'Item added to cart' });
await fetchCart();
};
// Remove item from cart
const removeItem = async (detailId: string) => {
if (!cart) return;
const res = await fetch(
`/api/shipment-requests/cart/items?detailId=${detailId}&requestId=${cart.id}`,
{ method: 'DELETE' }
);
if (!res.ok) {
const err = await res.json();
toast({
title: 'Error',
description: err.error || 'Failed to remove item',
variant: 'destructive',
});
return;
}
await fetchCart();
};
// Update item
const updateItem = async (
detailId: string,
data: { quantity?: number; notes?: string | null }
) => {
if (!cart) return;
const res = await fetch(
`/api/shipment-requests/cart/items/${detailId}`,
{
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ request_id: cart.id, ...data }),
}
);
if (!res.ok) {
const err = await res.json();
toast({
title: 'Error',
description: err.error || 'Failed to update item',
variant: 'destructive',
});
return;
}
await fetchCart();
};
// Submit cart
const submitCart = async () => {
if (!cart) return;
const res = await fetch('/api/shipment-requests/cart/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: cart.id }),
});
if (!res.ok) {
const err = await res.json();
toast({
title: 'Error',
description: err.error || 'Failed to submit request',
variant: 'destructive',
});
return;
}
toast({ title: 'Shipment request submitted successfully!' });
router.push('/shipment-requests');
};
// Handle ship-to selection
const handleSelectAddress = (address: string) => {
updateHeader({ ship_to_address: address });
};
if (loading) {
return (
<Card>
<CardContent className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</CardContent>
</Card>
);
}
if (error || !cart) {
return (
<Card>
<CardContent className="p-6 text-center text-destructive">
Failed to load cart: {error || 'Unknown error'}
</CardContent>
</Card>
);
}
return (
<div className="space-y-4">
<RequestStepper
steps={STEPS}
currentStep={currentStep}
onStepClick={setCurrentStep}
/>
{/* Step 0: Ship-To Address */}
{currentStep === 0 && (
<ShipToSelector
selectedAddress={cart.ship_to_address}
onSelect={handleSelectAddress}
onNext={() => setCurrentStep(1)}
/>
)}
{/* Step 1: Items */}
{currentStep === 1 && (
<>
<CartItemsTable
items={cart.details}
variant="ship"
onRemoveItem={removeItem}
onUpdateItem={updateItem}
onOpenBrowser={() => setBrowserOpen(true)}
/>
<div className="flex justify-between">
<Button variant="outline" onClick={() => setCurrentStep(0)}>
<ArrowLeft className="mr-2 h-4 w-4" />
Back
</Button>
<Button
onClick={() => setCurrentStep(2)}
disabled={cart.details.length === 0}
>
Next
<ArrowRight className="ml-2 h-4 w-4" />
</Button>
</div>
<InventoryBrowserDialog
open={browserOpen}
onClose={() => setBrowserOpen(false)}
onAddItem={addItem}
/>
</>
)}
{/* Step 2: Details */}
{currentStep === 2 && (
<CartHeaderForm
initialData={{
order_number: cart.order_number,
po_number: cart.po_number,
release_number: cart.release_number,
pickup_date: cart.pickup_date,
instructions: cart.instructions,
email_recipients: cart.email_recipients,
}}
onSave={updateHeader}
onBack={() => setCurrentStep(1)}
onNext={() => setCurrentStep(3)}
/>
)}
{/* Step 3: Review */}
{currentStep === 3 && (
<CartReview
cart={cart}
variant="ship"
onSubmit={submitCart}
onBack={() => setCurrentStep(2)}
/>
)}
</div>
);
}

View file

@ -0,0 +1,141 @@
"use client"
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
const AlertDialog = AlertDialogPrimitive.Root
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
const AlertDialogPortal = AlertDialogPrimitive.Portal
const AlertDialogOverlay = React.forwardRef<
React.ComponentRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef<
React.ComponentRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className
)}
{...props}
/>
)
AlertDialogHeader.displayName = "AlertDialogHeader"
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
AlertDialogFooter.displayName = "AlertDialogFooter"
const AlertDialogTitle = React.forwardRef<
React.ComponentRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
const AlertDialogDescription = React.forwardRef<
React.ComponentRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName
const AlertDialogAction = React.forwardRef<
React.ComponentRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
const AlertDialogCancel = React.forwardRef<
React.ComponentRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className
)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}

View file

@ -0,0 +1,286 @@
'use client';
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import type {
ShipRequestHeader,
ShipRequestDetailItem,
AddShipCartItemPayload,
} from '@/types/requests';
// =============================================================================
// Types
// =============================================================================
type AddItemResult = {
success: boolean;
action?: 'in_cart' | 'bad_plant';
reason?: string;
};
type ShipmentCartContextValue = {
/** Current active cart (null if none) */
cart: ShipRequestHeader | null;
/** Whether the initial cart check is loading */
cartLoading: boolean;
/** Map of "partNum|lotNum|plant|warehouse" → detail item for O(1) lookups */
cartItemMap: Map<string, ShipRequestDetailItem>;
/** The locked plant (from first item), or null if cart is empty */
cartPlant: string | null;
/** Whether there's an active (non-submitted, non-cancelled) cart */
hasCart: boolean;
/** Total weight (sum of quantities) in cart */
totalLbs: number;
/** Start a new cart (auto-creates via API) */
startCart: () => Promise<void>;
/** Cancel the active draft cart */
cancelCart: () => Promise<void>;
/** Add a single item to the cart */
addItem: (item: AddShipCartItemPayload) => Promise<AddItemResult>;
/** Add all items in batch */
addAllItems: (items: AddShipCartItemPayload[]) => Promise<void>;
/** Remove a single item from the cart */
removeItem: (detailId: string) => Promise<void>;
/** Re-fetch cart data from server */
refreshCart: () => Promise<void>;
};
// =============================================================================
// Context
// =============================================================================
const ShipmentCartContext = createContext<ShipmentCartContextValue | null>(null);
// =============================================================================
// Helper: build lookup key for cart items
// =============================================================================
function cartItemKey(
partNum: string,
lotNum: string | null | undefined,
plant: string,
warehouse: string | null | undefined
): string {
return `${partNum}|${lotNum ?? ''}|${plant}|${warehouse ?? ''}`;
}
// =============================================================================
// Provider
// =============================================================================
export function ShipmentCartProvider({ children }: { children: ReactNode }) {
const [cart, setCart] = useState<ShipRequestHeader | null>(null);
const [cartLoading, setCartLoading] = useState(true);
// On mount: lightweight check for existing active cart
const checkCart = useCallback(async () => {
try {
const res = await fetch('/api/shipment-requests/cart?check_only=true');
if (res.status === 204) {
setCart(null);
} else if (res.ok) {
const data = await res.json();
setCart(data);
} else if (res.status === 403) {
// User doesn't have permission - that's fine, no cart
setCart(null);
}
} catch {
// Network error - fail silently, cart features just won't show
setCart(null);
} finally {
setCartLoading(false);
}
}, []);
useEffect(() => {
checkCart();
}, [checkCart]);
// Refresh cart (full re-fetch)
const refreshCart = useCallback(async () => {
try {
const res = await fetch('/api/shipment-requests/cart?check_only=true');
if (res.status === 204) {
setCart(null);
} else if (res.ok) {
const data = await res.json();
setCart(data);
}
} catch {
// Silently fail
}
}, []);
// Start a new cart (auto-creates)
const startCart = useCallback(async () => {
const res = await fetch('/api/shipment-requests/cart');
if (!res.ok) throw new Error('Failed to start cart');
const data = await res.json();
setCart(data);
}, []);
// Cancel active draft cart
const cancelCart = useCallback(async () => {
if (!cart) return;
const res = await fetch(`/api/shipment-requests/${cart.id}/cancel`, {
method: 'POST',
});
if (!res.ok) throw new Error('Failed to cancel cart');
setCart(null);
}, [cart]);
// Add single item
const addItem = useCallback(
async (item: AddShipCartItemPayload): Promise<AddItemResult> => {
if (!cart) return { success: false, reason: 'No active cart' };
const res = await fetch('/api/shipment-requests/cart/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ request_id: cart.id, ...item }),
});
const data = await res.json();
if (!res.ok) {
return {
success: false,
action: data.action,
reason: data.reason || data.error || 'Failed to add item',
};
}
// Refresh cart to get updated details
await refreshCart();
return { success: true };
},
[cart, refreshCart]
);
// Add all items in batch
const addAllItems = useCallback(
async (items: AddShipCartItemPayload[]) => {
if (!cart) return;
await fetch('/api/shipment-requests/cart/items/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ request_id: cart.id, items }),
});
// Refresh cart regardless of result
await refreshCart();
},
[cart, refreshCart]
);
// Remove item
const removeItem = useCallback(
async (detailId: string) => {
if (!cart) return;
await fetch(
`/api/shipment-requests/cart/items?detailId=${detailId}&requestId=${cart.id}`,
{ method: 'DELETE' }
);
await refreshCart();
},
[cart, refreshCart]
);
// Derived values
const cartItemMap = useMemo(() => {
const map = new Map<string, ShipRequestDetailItem>();
if (cart) {
for (const d of cart.details) {
const key = cartItemKey(d.part_num, d.lot_num, d.plant, d.warehouse);
map.set(key, d);
}
}
return map;
}, [cart]);
const cartPlant = useMemo(() => {
if (!cart || cart.details.length === 0) return null;
return cart.details[0]!.plant;
}, [cart]);
const hasCart = cart !== null;
const totalLbs = useMemo(() => {
if (!cart) return 0;
return cart.details.reduce((sum, d) => sum + d.quantity, 0);
}, [cart]);
const value: ShipmentCartContextValue = useMemo(
() => ({
cart,
cartLoading,
cartItemMap,
cartPlant,
hasCart,
totalLbs,
startCart,
cancelCart,
addItem,
addAllItems,
removeItem,
refreshCart,
}),
[
cart,
cartLoading,
cartItemMap,
cartPlant,
hasCart,
totalLbs,
startCart,
cancelCart,
addItem,
addAllItems,
removeItem,
refreshCart,
]
);
return (
<ShipmentCartContext.Provider value={value}>
{children}
</ShipmentCartContext.Provider>
);
}
// =============================================================================
// Hook
// =============================================================================
export function useShipmentCart() {
const ctx = useContext(ShipmentCartContext);
if (!ctx) {
throw new Error('useShipmentCart must be used within ShipmentCartProvider');
}
return ctx;
}
/**
* Safe version of useShipmentCart that returns null if not in provider.
* Use this for components that may or may not be inside the cart provider.
*/
export function useShipmentCartOptional() {
return useContext(ShipmentCartContext);
}
/**
* Build a cart item lookup key from inventory row data.
* Exported so components can use the same key format.
*/
export { cartItemKey };

View file

@ -437,3 +437,119 @@ export async function cancelRequest(
return serializeHeader(cancelled); return serializeHeader(cancelled);
} }
// =============================================================================
// Lightweight Cart Check (no auto-create)
// =============================================================================
/**
* Check if an active cart exists for this user+company WITHOUT creating one.
* Returns null if no active cart exists.
*/
export async function getActiveCart(
userId: string,
companyId: string
): Promise<ShipRequestHeader | null> {
const existing = await db.ship_request.findFirst({
where: {
auth_user_id: userId,
quest_company_id: companyId,
is_submitted: false,
is_cancelled: false,
},
include: { details: { orderBy: { created_at: 'asc' } } },
orderBy: { created_at: 'desc' },
});
return existing ? serializeHeader(existing) : null;
}
// =============================================================================
// Batch Cart Item Operations
// =============================================================================
export type BatchAddResult = {
added: ShipRequestDetailItem[];
skipped: { item: AddShipCartItemPayload; reason: string }[];
errors: { item: AddShipCartItemPayload; error: string }[];
};
/**
* Add multiple items to the cart in one operation.
* Skips duplicates and plant mismatches rather than throwing.
*/
export async function addBatchCartItems(
requestId: string,
companyId: string,
items: AddShipCartItemPayload[]
): Promise<BatchAddResult> {
// Verify cart is active
const cart = await db.ship_request.findFirst({
where: { id: requestId, quest_company_id: companyId, is_submitted: false, is_cancelled: false },
include: { details: { orderBy: { created_at: 'asc' } } },
});
if (!cart) {
throw new Error('Cart not found or already submitted/cancelled');
}
// Determine locked plant from existing items
const lockedPlant = cart.details.length > 0 ? cart.details[0]!.plant : null;
const added: ShipRequestDetailItem[] = [];
const skipped: { item: AddShipCartItemPayload; reason: string }[] = [];
const errors: { item: AddShipCartItemPayload; error: string }[] = [];
for (const item of items) {
try {
// Plant constraint check
if (lockedPlant && item.plant !== lockedPlant) {
skipped.push({ item, reason: `Plant mismatch: cart is locked to ${lockedPlant}` });
continue;
}
// Duplicate check
const duplicate = await db.ship_request_detail.findFirst({
where: {
ship_request_id: requestId,
part_num: item.part_num,
lot_num: item.lot_num || null,
plant: item.plant,
warehouse: item.warehouse || null,
},
});
if (duplicate) {
skipped.push({ item, reason: 'Already in cart' });
continue;
}
// If this is the first item, it sets the plant
const detail = await db.ship_request_detail.create({
data: {
ship_request_id: requestId,
part_num: item.part_num,
lot_num: item.lot_num || null,
plant: item.plant,
warehouse: item.warehouse || null,
quantity: item.quantity,
notes: item.notes || null,
},
});
added.push(serializeDetail(detail));
} catch (err) {
errors.push({ item, error: err instanceof Error ? err.message : 'Unknown error' });
}
}
// Touch cart activity
if (added.length > 0) {
await db.ship_request.update({
where: { id: requestId },
data: { last_cart_activity: new Date() },
});
}
return { added, skipped, errors };
}