Adds complete initial codebase for the RJ Bulk Supplies fuel delivery backoffice: - Authentication pages and protected route layouts - Customer, supplier, fuel purchase, and delivery note management - Custom reporting and customer statement sending tools - Full UI component library and Tailwind styling - Server actions, API routes, and PocketBase integration - Development scripts and project configuration updates - Updated README and package metadata
258 lines
9.2 KiB
TypeScript
258 lines
9.2 KiB
TypeScript
"use client";
|
|
|
|
import { useActionState, useEffect, useRef, useState, useTransition } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Label } from "@/components/ui/label";
|
|
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
|
import { Select } from "@/components/ui/select";
|
|
import { Combobox } from "@/components/ui/combobox";
|
|
import { createDeliveryNote, updateDeliveryNote, type ActionResult } from "@/actions/delivery-notes";
|
|
import { toast } from "sonner";
|
|
import type { Customer, DeliveryNote } from "@/lib/types";
|
|
import { DELIVERY_STATUSES, TANK_OPTIONS } from "@/lib/types";
|
|
import { RefreshCw } from "lucide-react";
|
|
|
|
const initial: ActionResult = { ok: false, error: "" };
|
|
|
|
interface Props {
|
|
customers: Customer[];
|
|
note?: DeliveryNote;
|
|
customerName?: string;
|
|
preselectedCustomerId?: string;
|
|
}
|
|
|
|
function todayISO() {
|
|
return new Date().toISOString().slice(0, 10);
|
|
}
|
|
|
|
export function DeliveryNoteForm({ customers, note, customerName, preselectedCustomerId }: Props) {
|
|
const router = useRouter();
|
|
const isEdit = !!note;
|
|
const boundAction = isEdit ? updateDeliveryNote.bind(null, note!.id) : createDeliveryNote;
|
|
const [state, formAction, pending] = useActionState(boundAction, initial);
|
|
const formRef = useRef<HTMLFormElement>(null);
|
|
const [number, setNumber] = useState(note?.number || "");
|
|
const [date, setDate] = useState((note?.date || "").slice(0, 10) || todayISO());
|
|
const [customerId, setCustomerId] = useState(note?.customer || preselectedCustomerId || "");
|
|
const [qty, setQty] = useState<number | "">(note?.qty_litres_supplied ?? "");
|
|
const [price, setPrice] = useState<number | "">(note?.price_per_litre ?? "");
|
|
const [total, setTotal] = useState<number | "">(note?.total_value ?? "");
|
|
const [source, setSource] = useState<string>(note?.pricing_source || "");
|
|
const [autoFilled, setAutoFilled] = useState(false);
|
|
const [tank, setTank] = useState<string>(note?.plant_dispensing || "Plant 1");
|
|
const [, startTransition] = useTransition();
|
|
|
|
// Auto-fill price when customer/date change
|
|
useEffect(() => {
|
|
if (isEdit) return;
|
|
if (!customerId || !date) return;
|
|
startTransition(async () => {
|
|
try {
|
|
const res = await fetch(`/api/delivery-notes/price?customer=${customerId}&date=${date}`);
|
|
if (res.ok) {
|
|
const data = await res.json();
|
|
if (data.price) {
|
|
setPrice(data.price);
|
|
setSource(data.source || "");
|
|
setAutoFilled(true);
|
|
if (qty) setTotal(Number((data.price * Number(qty)).toFixed(2)));
|
|
}
|
|
}
|
|
} catch {}
|
|
});
|
|
}, [customerId, date, isEdit, qty]);
|
|
|
|
// Recompute total on qty/price change
|
|
useEffect(() => {
|
|
if (qty && price) {
|
|
setTotal(Number((Number(qty) * Number(price)).toFixed(2)));
|
|
}
|
|
}, [qty, price]);
|
|
|
|
// Auto-suggest next note number — called by the "Auto-Number" button, not on mount.
|
|
function autoNumber() {
|
|
if (isEdit) return;
|
|
startTransition(async () => {
|
|
try {
|
|
const res = await fetch("/api/delivery-notes/next-number");
|
|
if (res.ok) {
|
|
const data = await res.json();
|
|
if (data.number) setNumber(data.number);
|
|
}
|
|
} catch {}
|
|
});
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (state.ok) {
|
|
toast.success(isEdit ? "Delivery note updated" : "Delivery note created");
|
|
if (!isEdit) {
|
|
router.push("/delivery-notes");
|
|
} else {
|
|
router.push(`/delivery-notes/${note!.id}`);
|
|
}
|
|
} else if (state.error) {
|
|
toast.error(state.error);
|
|
}
|
|
}, [state, isEdit, router, note]);
|
|
|
|
const customerItems = customers.map((c) => ({
|
|
value: c.id,
|
|
label: c.name,
|
|
hint: c.email || c.contact_number || undefined,
|
|
}));
|
|
|
|
return (
|
|
<Card className="max-w-3xl">
|
|
<CardHeader>
|
|
<CardTitle>{isEdit ? `Edit ${note!.number}` : "Add delivery note"}</CardTitle>
|
|
</CardHeader>
|
|
<form ref={formRef} action={formAction}>
|
|
<CardContent className="space-y-4">
|
|
<div className="grid gap-4 sm:grid-cols-2">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="number">Delivery note # *</Label>
|
|
<div className="flex gap-2">
|
|
<Input
|
|
id="number"
|
|
name="number"
|
|
value={number}
|
|
onChange={(e) => setNumber(e.target.value)}
|
|
required
|
|
placeholder="e.g. 0001"
|
|
className="font-mono"
|
|
/>
|
|
{!isEdit && (
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={autoNumber}
|
|
aria-label="Auto-Number"
|
|
title="Suggest next number from the highest existing"
|
|
>
|
|
<RefreshCw className="h-4 w-4" />
|
|
Auto-Number
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="date">Delivery date *</Label>
|
|
<Input
|
|
id="date"
|
|
name="date"
|
|
type="date"
|
|
value={date}
|
|
onChange={(e) => setDate(e.target.value)}
|
|
max={todayISO()}
|
|
required
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="customer">Customer *</Label>
|
|
<Combobox
|
|
id="customer"
|
|
name="customer"
|
|
items={customerItems}
|
|
value={customerId}
|
|
onChange={setCustomerId}
|
|
placeholder="Search customers…"
|
|
emptyMessage={customers.length === 0 ? "No customers — add one first." : "No matches."}
|
|
required
|
|
/>
|
|
</div>
|
|
<div className="grid gap-4 sm:grid-cols-2">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="plant_dispensing">Plant / Dispensing</Label>
|
|
<Select
|
|
id="plant_dispensing"
|
|
name="plant_dispensing"
|
|
value={tank}
|
|
onChange={(e) => setTank(e.target.value)}
|
|
options={[
|
|
{ value: "Plant 1", label: "Plant 1" },
|
|
...TANK_OPTIONS.map((t) => ({ value: t, label: t })),
|
|
]}
|
|
/>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="vehicle_registration">Vehicle registration</Label>
|
|
<Input
|
|
id="vehicle_registration"
|
|
name="vehicle_registration"
|
|
defaultValue={note?.vehicle_registration || ""}
|
|
placeholder="e.g. ABC 123 GP"
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="grid gap-4 sm:grid-cols-3">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="qty_litres_supplied">Qty (litres) *</Label>
|
|
<Input
|
|
id="qty_litres_supplied"
|
|
name="qty_litres_supplied"
|
|
type="number"
|
|
step="0.01"
|
|
min="0.01"
|
|
value={qty}
|
|
onChange={(e) => setQty(e.target.value === "" ? "" : Number(e.target.value))}
|
|
required
|
|
/>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="price_per_litre">Price / L</Label>
|
|
<Input
|
|
id="price_per_litre"
|
|
name="price_per_litre"
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
value={price}
|
|
onChange={(e) => {
|
|
setPrice(e.target.value === "" ? "" : Number(e.target.value));
|
|
setAutoFilled(false);
|
|
}}
|
|
/>
|
|
{autoFilled && source && (
|
|
<p className="text-xs text-muted-foreground">auto-filled from {source} pricing</p>
|
|
)}
|
|
<input type="hidden" name="pricing_source" value={source} />
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="total_value">Total value</Label>
|
|
<Input
|
|
id="total_value"
|
|
name="total_value"
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
value={total}
|
|
onChange={(e) => setTotal(e.target.value === "" ? "" : Number(e.target.value))}
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="status">Status</Label>
|
|
<Select
|
|
id="status"
|
|
name="status"
|
|
defaultValue={note?.status || "Pending"}
|
|
options={DELIVERY_STATUSES.map((s) => ({ value: s, label: s }))}
|
|
/>
|
|
</div>
|
|
</CardContent>
|
|
<CardFooter className="flex justify-between">
|
|
<Button type="button" variant="ghost" onClick={() => router.back()}>
|
|
Cancel
|
|
</Button>
|
|
<Button type="submit" disabled={pending}>
|
|
{pending ? "Saving…" : isEdit ? "Update note" : "Create note"}
|
|
</Button>
|
|
</CardFooter>
|
|
</form>
|
|
</Card>
|
|
);
|
|
}
|