Add stock movement view and edit dialogs, and integrate with stock movements client

This commit is contained in:
2026-09-08 13:18:11 +05:30
parent 3bcb42ea9b
commit eea87c0ee2
5 changed files with 329 additions and 13 deletions
@@ -0,0 +1,58 @@
'use client'
import { Badge } from '@/components/ui/badge'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import type { StockBalanceResponse, LocationType } from '@/types/api'
const LOCATION_TYPE_VARIANT: Record<LocationType, 'default' | 'secondary'> = {
Warehouse: 'default',
Vehicle: 'secondary',
External: 'secondary',
}
const fmtDateTime = (v: string) =>
new Date(v).toLocaleString('en-GB', {
day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
})
interface StockBalanceViewSheetProps {
open: boolean
onClose: () => void
balance: StockBalanceResponse | null
}
function Row({ label, value }: { label: string; value: React.ReactNode }) {
return (
<div className="flex items-center justify-between py-2 text-sm border-b last:border-0">
<span className="text-muted-foreground">{label}</span>
<span className="font-medium text-right">{value}</span>
</div>
)
}
export function StockBalanceViewSheet({ open, onClose, balance }: StockBalanceViewSheetProps) {
if (!balance) return null
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>Stock Balance Details</DialogTitle>
</DialogHeader>
<div className="flex flex-col">
<Row label="Item" value={balance.itemName} />
<Row label="Location" value={balance.locationName} />
<Row label="Location Type" value={<Badge variant={LOCATION_TYPE_VARIANT[balance.locationType]}>{balance.locationType}</Badge>} />
<Row label="Quantity" value={balance.quantity} />
<Row label="Last Updated" value={fmtDateTime(balance.updatedAt)} />
</div>
</DialogContent>
</Dialog>
)
}
@@ -8,6 +8,8 @@ import { Badge } from '@/components/ui/badge'
import { toast } from '@/components/ui/toast' import { toast } from '@/components/ui/toast'
import { stock as stockApi, getApiError, getPaginatedItems } from '@/lib/api/index' import { stock as stockApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { StockBalanceResponse, LocationType } from '@/types/api' import type { StockBalanceResponse, LocationType } from '@/types/api'
import { StockBalanceViewSheet } from './stock-balance-view-sheet'
import { StockAdjustDialog } from './stock-adjust-dialog'
const fmtDate = (v: string) => const fmtDate = (v: string) =>
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
@@ -15,6 +17,7 @@ const fmtDate = (v: string) =>
const LOCATION_TYPE_VARIANT: Record<LocationType, 'default' | 'secondary'> = { const LOCATION_TYPE_VARIANT: Record<LocationType, 'default' | 'secondary'> = {
Warehouse: 'default', Warehouse: 'default',
Vehicle: 'secondary', Vehicle: 'secondary',
External: 'secondary',
} }
export function StockBalancesClient() { export function StockBalancesClient() {
@@ -23,6 +26,20 @@ export function StockBalancesClient() {
const [total, setTotal] = useState(0) const [total, setTotal] = useState(0)
const [page, setPage] = useState(1) const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20) const [pageSize, setPageSize] = useState(20)
const [viewing, setViewing] = useState<StockBalanceResponse | null>(null)
const [viewOpen, setViewOpen] = useState(false)
const [adjusting, setAdjusting] = useState<StockBalanceResponse | null>(null)
const [adjustOpen, setAdjustOpen] = useState(false)
function openView(row: StockBalanceResponse) {
setViewing(row)
setViewOpen(true)
}
function openAdjust(row: StockBalanceResponse) {
setAdjusting(row)
setAdjustOpen(true)
}
const fetchData = useCallback(async (p: number, ps: number) => { const fetchData = useCallback(async (p: number, ps: number) => {
setLoading(true) setLoading(true)
@@ -55,12 +72,12 @@ export function StockBalancesClient() {
minWidth: 200, minWidth: 200,
}, },
{ {
key: 'locationId', key: 'locationName',
title: 'Location ID', title: 'Location',
fields: ['locationId'], fields: ['locationName'],
width: 160, width: 180,
cellRender: (row) => ( cellRender: (row) => (
<span className="font-mono text-sm">{row.locationId.substring(0, 8)}</span> <span className="text-sm">{row.locationName}</span>
), ),
}, },
{ {
@@ -88,6 +105,20 @@ export function StockBalancesClient() {
width: 140, width: 140,
}, },
], ],
rowActions: {
actions: () => [
{
action: 'view',
label: 'View balance',
onClick: openView,
},
{
action: 'edit',
label: 'Adjust stock',
onClick: openAdjust,
},
],
},
}), [pageSize]) }), [pageSize])
return ( return (
@@ -111,6 +142,19 @@ export function StockBalancesClient() {
setPageSize(p.pageSize) setPageSize(p.pageSize)
}} }}
/> />
<StockBalanceViewSheet
open={viewOpen}
onClose={() => setViewOpen(false)}
balance={viewing}
/>
<StockAdjustDialog
open={adjustOpen}
onClose={() => setAdjustOpen(false)}
onSuccess={() => fetchData(page, pageSize)}
balance={adjusting}
/>
</> </>
) )
} }
@@ -0,0 +1,103 @@
'use client'
import { useEffect } from 'react'
import { useForm, zodResolver, z } from '@/lib/form'
import { FormField } from '@/components/shared/form-field'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { FieldGroup } from '@/components/ui/field'
import { toast } from '@/components/ui/toast'
import { stock as stockApi, getApiError } from '@/lib/api/index'
import type { StockMovementResponse } from '@/types/api'
const schema = z.object({
reasonCode: z.string().min(1, 'Reason is required'),
})
type FormValues = z.infer<typeof schema>
interface StockMovementEditDialogProps {
open: boolean
onClose: () => void
onSuccess: () => void
movement: StockMovementResponse | null
}
export function StockMovementEditDialog({ open, onClose, onSuccess, movement }: StockMovementEditDialogProps) {
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: { reasonCode: '' },
})
useEffect(() => {
if (!open || !movement) return
form.reset({ reasonCode: movement.reasonCode ?? '' })
}, [open, movement])
if (!movement) return null
async function onSubmit(values: FormValues) {
try {
await stockApi.updateMovementReason(movement!.id, values.reasonCode)
toast.add({ title: 'Reason updated', type: 'success' })
onSuccess()
onClose()
} catch (err) {
toast.add({ title: 'Failed to update reason', description: getApiError(err), type: 'error' })
}
}
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>Edit Movement — {movement.itemName}</DialogTitle>
<DialogDescription>
Movements are an immutable ledger — quantity, locations, and type can never be changed
once recorded. Only the reason/note can be edited.
</DialogDescription>
</DialogHeader>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
<FieldGroup>
<FormField
control={form.control}
name="reasonCode"
label="Reason"
required
render={({ field, invalid }) => (
<Input
id="reasonCode"
name={field.name}
ref={field.ref}
value={field.value as string}
onChange={field.onChange}
onBlur={field.onBlur}
placeholder="e.g. Corrected reason for this movement"
aria-invalid={invalid}
/>
)}
/>
</FieldGroup>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Saving…' : 'Save'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,68 @@
'use client'
import { Badge } from '@/components/ui/badge'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import type { StockMovementResponse, MovementType } from '@/types/api'
const MOVEMENT_TYPE_VARIANT: Record<MovementType, 'default' | 'secondary' | 'destructive'> = {
Sale: 'default',
CustomerReturn: 'secondary',
Transfer: 'secondary',
Damage: 'destructive',
Adjustment: 'secondary',
Load: 'default',
PurchaseReceipt: 'default',
PurchaseReturn: 'secondary',
}
const fmtDateTime = (v: string) =>
new Date(v).toLocaleString('en-GB', {
day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
})
interface StockMovementViewSheetProps {
open: boolean
onClose: () => void
movement: StockMovementResponse | null
}
function Row({ label, value }: { label: string; value: React.ReactNode }) {
return (
<div className="flex items-center justify-between py-2 text-sm border-b last:border-0">
<span className="text-muted-foreground">{label}</span>
<span className="font-medium text-right">{value}</span>
</div>
)
}
export function StockMovementViewSheet({ open, onClose, movement }: StockMovementViewSheetProps) {
if (!movement) return null
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>Stock Movement Details</DialogTitle>
</DialogHeader>
<div className="flex flex-col">
<Row label="Item" value={movement.itemName} />
<Row label="Type" value={<Badge variant={MOVEMENT_TYPE_VARIANT[movement.type]}>{movement.type}</Badge>} />
<Row label="From Location" value={movement.fromLocationName ?? '—'} />
<Row label="From Type" value={movement.fromLocationType ?? '—'} />
<Row label="To Location" value={movement.toLocationName ?? '—'} />
<Row label="To Type" value={movement.toLocationType ?? '—'} />
<Row label="Quantity" value={movement.quantity} />
<Row label="Reason" value={movement.reasonCode ?? '—'} />
<Row label="Reference ID" value={movement.referenceId ? <span className="font-mono text-xs">{movement.referenceId}</span> : '—'} />
<Row label="Created" value={fmtDateTime(movement.createdAt)} />
</div>
</DialogContent>
</Dialog>
)
}
@@ -8,6 +8,8 @@ import { Badge } from '@/components/ui/badge'
import { toast } from '@/components/ui/toast' import { toast } from '@/components/ui/toast'
import { stock as stockApi, getApiError, getPaginatedItems } from '@/lib/api/index' import { stock as stockApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { StockMovementResponse, MovementType } from '@/types/api' import type { StockMovementResponse, MovementType } from '@/types/api'
import { StockMovementViewSheet } from './stock-movement-view-sheet'
import { StockMovementEditDialog } from './stock-movement-edit-dialog'
const fmtDate = (v: string) => const fmtDate = (v: string) =>
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
@@ -29,6 +31,20 @@ export function StockMovementsClient() {
const [total, setTotal] = useState(0) const [total, setTotal] = useState(0)
const [page, setPage] = useState(1) const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20) const [pageSize, setPageSize] = useState(20)
const [viewing, setViewing] = useState<StockMovementResponse | null>(null)
const [viewOpen, setViewOpen] = useState(false)
const [editing, setEditing] = useState<StockMovementResponse | null>(null)
const [editOpen, setEditOpen] = useState(false)
function openView(row: StockMovementResponse) {
setViewing(row)
setViewOpen(true)
}
function openEdit(row: StockMovementResponse) {
setEditing(row)
setEditOpen(true)
}
const fetchData = useCallback(async (p: number, ps: number) => { const fetchData = useCallback(async (p: number, ps: number) => {
setLoading(true) setLoading(true)
@@ -70,24 +86,24 @@ export function StockMovementsClient() {
), ),
}, },
{ {
key: 'fromLocationType', key: 'fromLocationName',
title: 'From', title: 'From',
fields: ['fromLocationType'], fields: ['fromLocationName'],
width: 140, width: 160,
cellRender: (row) => ( cellRender: (row) => (
<span className="text-sm text-muted-foreground"> <span className="text-sm text-muted-foreground">
{row.fromLocationType ?? '—'} {row.fromLocationName ?? '—'}
</span> </span>
), ),
}, },
{ {
key: 'toLocationType', key: 'toLocationName',
title: 'To', title: 'To',
fields: ['toLocationType'], fields: ['toLocationName'],
width: 140, width: 160,
cellRender: (row) => ( cellRender: (row) => (
<span className="text-sm text-muted-foreground"> <span className="text-sm text-muted-foreground">
{row.toLocationType ?? '—'} {row.toLocationName ?? '—'}
</span> </span>
), ),
}, },
@@ -107,6 +123,20 @@ export function StockMovementsClient() {
width: 140, width: 140,
}, },
], ],
rowActions: {
actions: () => [
{
action: 'view',
label: 'View movement',
onClick: openView,
},
{
action: 'edit',
label: 'Edit reason',
onClick: openEdit,
},
],
},
}), [pageSize]) }), [pageSize])
return ( return (
@@ -130,6 +160,19 @@ export function StockMovementsClient() {
setPageSize(p.pageSize) setPageSize(p.pageSize)
}} }}
/> />
<StockMovementViewSheet
open={viewOpen}
onClose={() => setViewOpen(false)}
movement={viewing}
/>
<StockMovementEditDialog
open={editOpen}
onClose={() => setEditOpen(false)}
onSuccess={() => fetchData(page, pageSize)}
movement={editing}
/>
</> </>
) )
} }