name: CI/CD - ERP Core Monorepo

on:
  pull_request:
    branches:
      - production
    types:
      - closed

jobs:
  backend-build-and-deploy:
    name: Build & Deploy ERP Core Backend
    runs-on: linux
    if: github.event.pull_request.merged == true
    steps:
      - name: Checkout code
        run: |
          git clone \
            --depth 1 \
            --branch production \
            https://oauth2:${{ secrets.ERPCORE }}@gitea.hexdive.com/New_REP_SYSTEM/ERP-core.git \
            .

      - name: Restore backend
        run: dotnet restore Backend/ERPCore.sln

      - name: Publish backend
        run: |
          rm -rf /tmp/erpcore-deploy
          mkdir -p /tmp/erpcore-deploy
          dotnet publish Backend/ERPCore/ERPCore.csproj \
            -c Release \
            -r linux-x64 \
            --self-contained true \
            -o /tmp/erpcore-deploy

      - name: Stop backend service
        run: systemctl stop erpcore.service

      - name: Copy backend to deploy folder
        run: |
          mkdir -p /home/erp/core/publish
          rm -rf /home/erp/core/publish/*
          cp -r /tmp/erpcore-deploy/* /home/erp/core/publish/

      - name: Fix backend ownership and permissions
        run: |
          chown -R erpuser:erpuser /home/erp/core/publish
          find /home/erp/core/publish -type d -exec chmod 755 {} +
          find /home/erp/core/publish -type f -exec chmod 644 {} +
          chmod +x /home/erp/core/publish/ERPCore

      - name: Restart backend service
        run: systemctl restart erpcore.service

      - name: Verify backend
        run: |
          systemctl is-active erpcore.service && echo "Backend service running" || echo "Backend service failed"

  frontend-build-and-deploy:
    name: Build & Deploy ERP Core Frontend
    runs-on: linux
    needs: backend-build-and-deploy
    if: github.event.pull_request.merged == true
    steps:
      - name: Checkout code
        run: |
          git clone \
            --depth 1 \
            --branch Production \
            https://oauth2:${{ secrets.ERPCORE }}@gitea.hexdive.com/New_REP_SYSTEM/ERP-core.git \
            .

      - name: Build frontend Docker image
        run: docker build -t erpcore-frontend:latest Frontend/erp-system

      - name: Stop & remove existing frontend container
        run: |
          docker stop erpcore-frontend 2>/dev/null || true
          docker rm erpcore-frontend 2>/dev/null || true

      - name: Start frontend container
        run: |
          docker run -d \
            --name erpcore-frontend \
            -p 6702:6702 \
            --add-host=host.docker.internal:host-gateway \
            -e BACKEND_ORIGIN=http://host.docker.internal:6701 \
            --restart unless-stopped \
            --memory="512m" \
            --cpus="1.0" \
            --cap-drop ALL \
            --security-opt no-new-privileges \
            erpcore-frontend:latest

      - name: Remove old frontend images
        run: docker image prune -f

      - name: Verify frontend
        run: |
          docker ps --filter name=erpcore-frontend --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" \
            | grep erpcore-frontend && echo "Frontend container running" || echo "Frontend container failed"
This commit is contained in:
Kalana B. Thilakarathna
2026-09-17 13:59:05 +05:30
parent 93f2f1bd3b
commit 03d01d4c4e
61 changed files with 2195 additions and 1245 deletions
@@ -1,111 +1,2 @@
'use client'
import { Badge } from '@/components/ui/badge'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Separator } from '@/components/ui/separator'
import type { SaleResponse, SaleStatus, PaymentStatus } from '@/types/api'
const SALE_STATUS_VARIANT: Record<SaleStatus, 'default' | 'secondary' | 'destructive'> = {
Pending: 'secondary',
Completed: 'default',
Cancelled: 'destructive',
}
const PAYMENT_STATUS_VARIANT: Record<PaymentStatus, 'default' | 'secondary' | 'destructive'> = {
Pending: 'secondary',
PartiallyPaid: 'secondary',
Paid: 'default',
}
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
const truncId = (id: string) => id.substring(0, 8)
const fmtDateTime = (v: string | null) =>
v
? new Date(v).toLocaleString('en-GB', {
day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
})
: '—'
interface SaleViewSheetProps {
open: boolean
onClose: () => void
sale: SaleResponse | 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 SaleViewSheet({ open, onClose, sale }: SaleViewSheetProps) {
if (!sale) return null
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>Sale Details</DialogTitle>
</DialogHeader>
<div className="flex flex-col">
<Row label="Sale ID" value={<span className="font-mono">{truncId(sale.id)}</span>} />
<Row label="Store ID" value={<span className="font-mono">{truncId(sale.storeId)}</span>} />
<Row label="Status" value={<Badge variant={SALE_STATUS_VARIANT[sale.status]}>{sale.status}</Badge>} />
<Row label="Payment Status" value={<Badge variant={PAYMENT_STATUS_VARIANT[sale.paymentStatus]}>{sale.paymentStatus}</Badge>} />
<Row label="Total Amount" value={fmtAmount(sale.totalAmount)} />
<Row label="Fulfill Immediately" value={sale.fulfillImmediately ? 'Yes' : 'No'} />
<Row label="Order Status" value={sale.orderStatus} />
<Row label="Sale Date" value={fmtDateTime(sale.saleDate)} />
<Row label="Completed At" value={fmtDateTime(sale.completedAt)} />
<Row label="Created At" value={fmtDateTime(sale.createdAt)} />
</div>
<Separator />
<div>
<p className="text-sm font-medium mb-2">Items ({sale.items.length})</p>
<div className="overflow-x-auto rounded-md border">
<table className="w-full text-sm">
<thead className="bg-muted/50">
<tr>
<th className="text-left font-medium px-3 py-2">Item</th>
<th className="text-right font-medium px-3 py-2">Quantity</th>
<th className="text-right font-medium px-3 py-2">Fulfilled</th>
<th className="text-right font-medium px-3 py-2">Unit Price</th>
</tr>
</thead>
<tbody>
{sale.items.length === 0 ? (
<tr>
<td colSpan={4} className="text-center text-muted-foreground px-3 py-4">
No items on this sale.
</td>
</tr>
) : (
sale.items.map((item) => (
<tr key={item.itemId} className="border-t">
<td className="px-3 py-2 font-mono">{truncId(item.itemId)}</td>
<td className="text-right px-3 py-2">{item.quantity}</td>
<td className="text-right px-3 py-2">{item.quantityFulfilled}</td>
<td className="text-right px-3 py-2">{fmtAmount(item.unitPrice)}</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</DialogContent>
</Dialog>
)
}
// Replaced by shop-po-view-sheet.tsx
export {}
@@ -1,7 +1,6 @@
'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'
@@ -10,10 +9,11 @@ import type { TableConfig } from '@/components/shared/data-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/toast'
import { sales as salesApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { SaleResponse, SaleStatus, PaymentStatus } from '@/types/api'
import { shopPos as shopPosApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { ShopPOResponse, ShopPOStatus } from '@/types/api'
import { SaleViewSheet } from './sale-view-sheet'
import { ShopPOViewSheet } from './shop-po-view-sheet'
import { ShopPOCreateSheet } from './shop-po-create-sheet'
const fmtDate = (v: string) =>
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
@@ -21,36 +21,31 @@ const fmtDate = (v: string) =>
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
const truncId = (id: string) => id.substring(0, 8)
const SALE_STATUS_VARIANT: Record<SaleStatus, 'default' | 'secondary' | 'destructive'> = {
const PO_STATUS_VARIANT: Record<ShopPOStatus, 'default' | 'secondary' | 'destructive'> = {
Pending: 'secondary',
Completed: 'default',
PartiallyFulfilled: 'secondary',
Fulfilled: 'default',
Cancelled: 'destructive',
}
const PAYMENT_STATUS_VARIANT: Record<PaymentStatus, 'default' | 'secondary' | 'destructive'> = {
Pending: 'secondary',
PartiallyPaid: 'secondary',
Paid: 'default',
}
export function SalesClient() {
const router = useRouter()
const [data, setData] = useState<SaleResponse[]>([])
const [data, setData] = useState<ShopPOResponse[]>([])
const [loading, setLoading] = useState(true)
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
const [viewOpen, setViewOpen] = useState(false)
const [selectedSale, setSelectedSale] = useState<SaleResponse | null>(null)
const [createOpen, setCreateOpen] = useState(false)
const [selectedPO, setSelectedPO] = useState<ShopPOResponse | null>(null)
const fetchData = useCallback(async (p: number, ps: number) => {
setLoading(true)
try {
const res = await salesApi.list({ page: p, pageSize: ps })
const res = await shopPosApi.list({ page: p, pageSize: ps })
setData(getPaginatedItems(res))
setTotal(res.total)
} catch (err) {
toast.add({ title: 'Failed to load sales', description: getApiError(err), type: 'error' })
toast.add({ title: 'Failed to load Shop POs', description: getApiError(err), type: 'error' })
} finally {
setLoading(false)
}
@@ -60,45 +55,52 @@ export function SalesClient() {
fetchData(page, pageSize)
}, [fetchData, page, pageSize])
function handleView(row: SaleResponse) {
setSelectedSale(row)
function handleView(row: ShopPOResponse) {
setSelectedPO(row)
setViewOpen(true)
}
async function handleCancel(row: SaleResponse) {
async function handleConfirm(row: ShopPOResponse) {
try {
await salesApi.cancel(row.id)
toast.add({ title: 'Sale cancelled', type: 'success' })
await shopPosApi.confirm(row.id)
toast.add({ title: 'Shop PO confirmed', type: 'success' })
fetchData(page, pageSize)
} catch (err) {
toast.add({ title: 'Failed to cancel sale', description: getApiError(err), type: 'error' })
toast.add({ title: 'Failed to confirm Shop PO', description: getApiError(err), type: 'error' })
}
}
const tableConfig = useMemo<TableConfig<SaleResponse>>(() => ({
async function handleCancel(row: ShopPOResponse) {
try {
await shopPosApi.cancel(row.id)
toast.add({ title: 'Shop PO cancelled', type: 'success' })
fetchData(page, pageSize)
} catch (err) {
toast.add({ title: 'Failed to cancel Shop PO', description: getApiError(err), type: 'error' })
}
}
const tableConfig = useMemo<TableConfig<ShopPOResponse>>(() => ({
rowKey: 'id',
serverSide: true,
stickyHeader: true,
emptyMessage: 'No sales found.',
emptyMessage: 'No Shop POs found.',
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
columns: [
{
key: 'id',
title: 'Sale ID',
title: 'PO ID',
fields: ['id'],
width: 140,
width: 120,
cellRender: (row) => (
<span className="font-mono text-sm">{truncId(row.id)}</span>
),
},
{
key: 'storeId',
title: 'Store ID',
fields: ['storeId'],
width: 140,
cellRender: (row) => (
<span className="font-mono text-sm">{truncId(row.storeId)}</span>
),
key: 'store',
title: 'Store',
fields: [{ key: 'storeName', primary: true }],
minWidth: 180,
},
{
key: 'totalAmount',
@@ -113,25 +115,21 @@ export function SalesClient() {
key: 'status',
title: 'Status',
fields: ['status'],
width: 140,
cellRender: (row) => (
<Badge variant={SALE_STATUS_VARIANT[row.status]}>{row.status}</Badge>
),
},
{
key: 'paymentStatus',
title: 'Payment',
fields: ['paymentStatus'],
width: 160,
cellRender: (row) => (
<Badge variant={PAYMENT_STATUS_VARIANT[row.paymentStatus]}>{row.paymentStatus}</Badge>
<Badge variant={PO_STATUS_VARIANT[row.status]}>{row.status}</Badge>
),
},
{
key: 'saleDate',
title: 'Sale Date',
fields: [{ key: 'saleDate', transform: (v) => fmtDate(v as string) }],
width: 140,
key: 'confirmed',
title: 'Confirmed',
fields: ['confirmedAt'],
width: 120,
cellRender: (row) => (
<span className="text-sm text-muted-foreground">
{row.confirmedAt ? fmtDate(row.confirmedAt) : 'Unconfirmed'}
</span>
),
},
{
key: 'createdAt',
@@ -144,14 +142,20 @@ export function SalesClient() {
actions: () => [
{
action: 'view',
label: 'View sale',
label: 'View PO',
onClick: handleView,
},
{
action: 'confirm',
label: 'Confirm PO',
onClick: handleConfirm,
visible: (target) => !target.confirmedAt && target.status !== 'Cancelled',
},
{
action: 'cancel',
label: 'Cancel sale',
label: 'Cancel PO',
onClick: handleCancel,
visible: (target) => target.status !== 'Cancelled',
visible: (target) => target.status !== 'Cancelled' && target.status !== 'Fulfilled',
},
],
},
@@ -161,14 +165,14 @@ export function SalesClient() {
<>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-semibold text-foreground">Sales</h1>
<h1 className="text-2xl font-semibold text-foreground">Shop POs</h1>
<p className="text-sm text-muted-foreground mt-0.5">
Sales transactions recorded against stores
Purchase orders raised by agents on behalf of stores
</p>
</div>
<Button onClick={() => router.push('/sales/new')}>
<Button onClick={() => setCreateOpen(true)}>
<HugeiconsIcon icon={Add01Icon} size={16} />
Add Sale
New PO
</Button>
</div>
@@ -183,10 +187,16 @@ export function SalesClient() {
}}
/>
<SaleViewSheet
<ShopPOCreateSheet
open={createOpen}
onClose={() => setCreateOpen(false)}
onSuccess={() => fetchData(page, pageSize)}
/>
<ShopPOViewSheet
open={viewOpen}
onClose={() => setViewOpen(false)}
sale={selectedSale}
po={selectedPO}
/>
</>
)
@@ -0,0 +1,217 @@
'use client'
import { useEffect, useState } from 'react'
import { useForm, zodResolver, z } from '@/lib/form'
import { FormField } from '@/components/shared/form-field'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
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 { shopPos as shopPosApi, stores as storesApi, items as itemsApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { StoreResponse, ItemSummaryResponse } from '@/types/api'
const itemLineSchema = z.object({
itemId: z.string().min(1, 'Item required'),
quantity: z.number().int().min(1, 'Min 1'),
unitPrice: z.number().min(0, 'Price must be 0 or more'),
})
const schema = z.object({
storeId: z.string().min(1, 'Store is required'),
items: z.array(itemLineSchema).min(1, 'At least one item is required'),
})
type FormValues = z.infer<typeof schema>
interface ShopPOCreateSheetProps {
open: boolean
onClose: () => void
onSuccess: () => void
}
const emptyLine = { itemId: '', quantity: 1, unitPrice: 0 }
export function ShopPOCreateSheet({ open, onClose, onSuccess }: ShopPOCreateSheetProps) {
const [storesList, setStoresList] = useState<StoreResponse[]>([])
const [itemsList, setItemsList] = useState<ItemSummaryResponse[]>([])
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: { storeId: '', items: [emptyLine] },
})
const watchedItems = form.watch('items')
useEffect(() => {
if (!open) return
form.reset({ storeId: '', items: [emptyLine] })
Promise.all([
storesApi.list({ pageSize: 200 }),
itemsApi.list({ pageSize: 200 }),
])
.then(([s, i]) => {
setStoresList(getPaginatedItems(s))
setItemsList(getPaginatedItems(i))
})
.catch((err) => toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' }))
}, [open])
function addLine() {
form.setValue('items', [...watchedItems, emptyLine])
}
function removeLine(idx: number) {
form.setValue('items', watchedItems.filter((_, i) => i !== idx))
}
async function onSubmit(values: FormValues) {
try {
await shopPosApi.create(values)
toast.add({ title: 'Shop PO created', type: 'success' })
onSuccess()
onClose()
} catch (err) {
toast.add({ title: 'Failed to create Shop PO', description: getApiError(err), type: 'error' })
}
}
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>New Shop PO</DialogTitle>
<DialogDescription>Raise a purchase order on behalf of a store.</DialogDescription>
</DialogHeader>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
<FieldGroup>
<FormField
control={form.control}
name="storeId"
label="Store"
required
render={({ field }) => (
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select store..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select store...</SelectItem>
{storesList.map((s) => (
<SelectItem key={s.id} value={s.id}>
{s.storeName} — {s.ownerName}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</FieldGroup>
<div>
<div className="flex items-center justify-between mb-2">
<p className="text-sm font-medium">Line Items</p>
<Button type="button" variant="outline" size="sm" onClick={addLine}>
+ Add Item
</Button>
</div>
<div className="flex flex-col gap-3">
{watchedItems.map((_, idx) => (
<div key={idx} className="grid grid-cols-[1fr_80px_100px_36px] gap-2 items-end">
<FormField
control={form.control}
name={`items.${idx}.itemId`}
label={idx === 0 ? 'Item' : undefined}
render={({ field }) => (
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select item..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select item...</SelectItem>
{itemsList.map((item) => (
<SelectItem key={item.id} value={item.id}>
{item.name} ({item.sku})
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
<FormField
control={form.control}
name={`items.${idx}.quantity`}
label={idx === 0 ? 'Qty' : undefined}
render={({ field, invalid }) => (
<Input
type="number"
min={1}
value={Number(field.value as number)}
onChange={(e) => field.onChange(Number(e.target.value))}
onBlur={field.onBlur}
aria-invalid={invalid}
/>
)}
/>
<FormField
control={form.control}
name={`items.${idx}.unitPrice`}
label={idx === 0 ? 'Unit Price' : undefined}
render={({ field, invalid }) => (
<Input
type="number"
step="0.01"
min={0}
value={Number(field.value as number)}
onChange={(e) => field.onChange(Number(e.target.value))}
onBlur={field.onBlur}
aria-invalid={invalid}
/>
)}
/>
<div className={idx === 0 ? 'mt-6' : ''}>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeLine(idx)}
disabled={watchedItems.length === 1}
className="h-9 w-9 p-0 text-muted-foreground hover:text-destructive"
>
×
</Button>
</div>
</div>
))}
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Creating…' : 'Create PO'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,106 @@
'use client'
import { Badge } from '@/components/ui/badge'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Separator } from '@/components/ui/separator'
import type { ShopPOResponse, ShopPOStatus } from '@/types/api'
const PO_STATUS_VARIANT: Record<ShopPOStatus, 'default' | 'secondary' | 'destructive'> = {
Pending: 'secondary',
PartiallyFulfilled: 'secondary',
Fulfilled: 'default',
Cancelled: 'destructive',
}
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
const truncId = (id: string) => id.substring(0, 8)
const fmtDateTime = (v: string | null) =>
v
? new Date(v).toLocaleString('en-GB', {
day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
})
: '—'
interface ShopPOViewSheetProps {
open: boolean
onClose: () => void
po: ShopPOResponse | 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 ShopPOViewSheet({ open, onClose, po }: ShopPOViewSheetProps) {
if (!po) return null
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>Shop PO Details</DialogTitle>
</DialogHeader>
<div className="flex flex-col">
<Row label="PO ID" value={<span className="font-mono">{truncId(po.id)}</span>} />
<Row label="Store" value={po.storeName} />
<Row label="Status" value={<Badge variant={PO_STATUS_VARIANT[po.status]}>{po.status}</Badge>} />
<Row label="Total Amount" value={fmtAmount(po.totalAmount)} />
<Row label="Invoice" value={po.invoiceId ? <span className="font-mono">{truncId(po.invoiceId)}</span> : 'No invoice yet'} />
<Row label="Confirmed At" value={fmtDateTime(po.confirmedAt)} />
<Row label="Fulfilled At" value={fmtDateTime(po.fulfilledAt)} />
<Row label="Created At" value={fmtDateTime(po.createdAt)} />
</div>
<Separator />
<div>
<p className="text-sm font-medium mb-2">Line Items ({po.items.filter(i => i.isActive).length})</p>
<div className="overflow-x-auto rounded-md border">
<table className="w-full text-sm">
<thead className="bg-muted/50">
<tr>
<th className="text-left font-medium px-3 py-2">Item</th>
<th className="text-right font-medium px-3 py-2">Qty</th>
<th className="text-right font-medium px-3 py-2">Fulfilled</th>
<th className="text-right font-medium px-3 py-2">Unit Price</th>
<th className="text-right font-medium px-3 py-2">Line Total</th>
</tr>
</thead>
<tbody>
{po.items.filter(i => i.isActive).length === 0 ? (
<tr>
<td colSpan={5} className="text-center text-muted-foreground px-3 py-4">
No items on this PO.
</td>
</tr>
) : (
po.items.filter(i => i.isActive).map((item) => (
<tr key={item.id} className="border-t">
<td className="px-3 py-2">{item.itemName}</td>
<td className="text-right px-3 py-2">{item.quantity}</td>
<td className="text-right px-3 py-2">{item.quantityFulfilled}</td>
<td className="text-right px-3 py-2">{fmtAmount(item.unitPrice)}</td>
<td className="text-right px-3 py-2 font-medium">{fmtAmount(item.quantity * item.unitPrice)}</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -15,24 +15,21 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
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 {
sales as salesApi,
shopPos as shopPosApi,
stores as storesApi,
rides as ridesApi,
items as itemsApi,
users as usersApi,
priceLists as priceListsApi,
getApiError,
getPaginatedItems,
} from '@/lib/api/index'
import type { ItemSummaryResponse, RideResponse, StoreResponse, UserResponse } from '@/types/api'
import type { ItemSummaryResponse, StoreResponse } from '@/types/api'
const saleItemSchema = z.object({
const lineItemSchema = z.object({
itemId: z.string().min(1, 'Item is required'),
quantity: z.number().min(1, 'Quantity must be at least 1'),
unitPrice: z.number().min(0.01, 'Unit price must be greater than 0'),
@@ -40,11 +37,7 @@ const saleItemSchema = z.object({
const schema = z.object({
storeId: z.string().min(1, 'Store is required'),
saleDate: z.string().min(1, 'Sale date is required'),
createdByUserId: z.string().min(1, 'Created by is required'),
rideId: z.string(),
fulfillImmediately: z.boolean(),
items: z.array(saleItemSchema).min(1, 'At least one item is required'),
items: z.array(lineItemSchema).min(1, 'At least one item is required'),
})
type FormValues = z.infer<typeof schema>
@@ -53,61 +46,46 @@ function createDefaultItem() {
return { itemId: '', quantity: 1, unitPrice: 0 }
}
function todayIso() {
return new Date().toISOString().slice(0, 10)
}
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
export default function NewSalePage() {
export default function NewShopPOPage() {
const router = useRouter()
const [storesList, setStoresList] = useState<StoreResponse[]>([])
const [ridesList, setRidesList] = useState<RideResponse[]>([])
const [itemsList, setItemsList] = useState<ItemSummaryResponse[]>([])
const [usersList, setUsersList] = useState<UserResponse[]>([])
const [priceMinByIndex, setPriceMinByIndex] = useState<Record<number, number | null>>({})
const [priceRetailByIndex, setPriceRetailByIndex] = useState<Record<number, number | null>>({})
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
storeId: '',
saleDate: todayIso(),
createdByUserId: '',
rideId: '',
fulfillImmediately: false,
items: [createDefaultItem()],
},
})
const { fields, append, remove } = useFieldArray({
control: form.control,
name: 'items',
defaultValues: { storeId: '', items: [createDefaultItem()] },
})
const { fields, append, remove } = useFieldArray({ control: form.control, name: 'items' })
const watchedItems = useWatch({ control: form.control, name: 'items' })
const watchedStoreId = useWatch({ control: form.control, name: 'storeId' })
const watchedSaleDate = useWatch({ control: form.control, name: 'saleDate' })
const itemsById = useMemo(
() => new Map(itemsList.map((item) => [item.id, item])),
[itemsList]
)
const totalAmount = useMemo(
() => watchedItems.reduce((sum, item) => sum + (Number(item.quantity) || 0) * (Number(item.unitPrice) || 0), 0),
() => watchedItems.reduce((sum, line) => sum + (Number(line.quantity) || 0) * (Number(line.unitPrice) || 0), 0),
[watchedItems]
)
const [priceMinByIndex, setPriceMinByIndex] = useState<Record<number, number | null>>({})
const [priceRetailByIndex, setPriceRetailByIndex] = useState<Record<number, number | null>>({})
async function resolveAndSetPrice(index: number, itemId: string) {
const item = itemsById.get(itemId)
if (watchedStoreId && watchedSaleDate) {
const today = new Date().toISOString().slice(0, 10)
if (watchedStoreId) {
try {
const resolution = await priceListsApi.resolve({ itemId, storeId: watchedStoreId, saleDate: watchedSaleDate })
const resolution = await priceListsApi.resolve({ itemId, storeId: watchedStoreId, saleDate: today })
form.setValue(`items.${index}.unitPrice`, resolution.price, { shouldValidate: true })
setPriceMinByIndex((prev) => ({ ...prev, [index]: resolution.minPrice }))
setPriceRetailByIndex((prev) => ({ ...prev, [index]: resolution.retailPrice }))
return
} catch {
// No resolvable price for this store/date (e.g. store/item not found) — fall back below.
// No resolvable price for this store — fall back to item default.
}
}
if (item) {
@@ -117,28 +95,22 @@ export default function NewSalePage() {
}
}
// Re-resolve every already-selected line's price whenever the store or sale date changes,
// since the applicable price list is scoped by the store's region and the sale date.
useEffect(() => {
if (!watchedStoreId || !watchedSaleDate) return
if (!watchedStoreId) return
watchedItems.forEach((line, index) => {
if (line.itemId) resolveAndSetPrice(index, line.itemId)
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [watchedStoreId, watchedSaleDate])
}, [watchedStoreId])
useEffect(() => {
Promise.all([
storesApi.list({ pageSize: 200 }),
ridesApi.list({ pageSize: 200, rideType: 'Sale' }),
itemsApi.list({ pageSize: 200 }),
usersApi.list({ pageSize: 200 }),
])
.then(([stores, rides, items, usersRes]) => {
.then(([stores, items]) => {
setStoresList(getPaginatedItems(stores))
setRidesList(getPaginatedItems(rides))
setItemsList(getPaginatedItems(items))
setUsersList(getPaginatedItems(usersRes))
})
.catch((err) => {
toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' })
@@ -147,18 +119,14 @@ export default function NewSalePage() {
async function onSubmit(values: FormValues) {
try {
await salesApi.create({
await shopPosApi.create({
storeId: values.storeId,
saleDate: values.saleDate,
rideId: values.rideId || null,
fulfillImmediately: values.fulfillImmediately,
items: values.items,
createdByUserId: values.createdByUserId,
})
toast.add({ title: 'Sale created', type: 'success' })
toast.add({ title: 'Shop PO created', type: 'success' })
router.push('/sales')
} catch (err) {
toast.add({ title: 'Failed to create sale', description: getApiError(err), type: 'error' })
toast.add({ title: 'Failed to create Shop PO', description: getApiError(err), type: 'error' })
}
}
@@ -170,116 +138,34 @@ export default function NewSalePage() {
Back
</Button>
<div>
<h1 className="text-2xl font-semibold text-foreground">Create Sale</h1>
<p className="text-sm text-muted-foreground">Record a sale for a store with one or more items.</p>
<h1 className="text-2xl font-semibold text-foreground">Create Shop PO</h1>
<p className="text-sm text-muted-foreground">Record a purchase order for a store.</p>
</div>
</div>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
<div className="rounded-2xl border p-6">
<h3 className="mb-4 text-sm font-medium text-foreground">Sale Details</h3>
<h3 className="mb-4 text-sm font-medium text-foreground">Order Details</h3>
<FieldGroup>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
<FormField
control={form.control}
name="storeId"
label="Store"
required
render={({ field }) => (
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select store..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select store...</SelectItem>
{storesList.map((store) => (
<SelectItem key={store.id} value={store.id}>
{store.storeName} - {store.ownerName}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
<FormField
control={form.control}
name="saleDate"
label="Sale Date"
required
render={({ field, invalid }) => (
<Input
id="saleDate"
name={field.name}
ref={field.ref}
type="date"
value={field.value as string}
onChange={field.onChange}
onBlur={field.onBlur}
aria-invalid={invalid}
/>
)}
/>
<FormField
control={form.control}
name="createdByUserId"
label="Created 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 user..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select user...</SelectItem>
{usersList.map((user) => (
<SelectItem key={user.id} value={user.id}>
{user.fullName}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
<FormField
control={form.control}
name="rideId"
label="Ride"
render={({ field }) => (
<Select
value={(field.value as string) || '__none__'}
onValueChange={(value) => field.onChange(value === '__none__' ? '' : value)}
>
<SelectTrigger>
<SelectValue placeholder="Select ride..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="__none__">No ride</SelectItem>
{ridesList.map((ride) => (
<SelectItem key={ride.id} value={ride.id}>
{ride.routeName} - {ride.vehicleNumberPlate}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</div>
<FormField
control={form.control}
name="fulfillImmediately"
name="storeId"
label="Store"
required
render={({ field }) => (
<label className="flex items-center gap-3 text-sm font-medium">
<Checkbox
checked={Boolean(field.value)}
onCheckedChange={(checked) => field.onChange(Boolean(checked))}
/>
Fulfill immediately (van sale)
</label>
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select store..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select store...</SelectItem>
{storesList.map((store) => (
<SelectItem key={store.id} value={store.id}>
{store.storeName} — {store.ownerName}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</FieldGroup>
@@ -313,7 +199,9 @@ export default function NewSalePage() {
<tbody>
{fields.map((fieldItem, index) => {
const selectedItem = itemsById.get(watchedItems[index]?.itemId ?? '')
const lineTotal = (Number(watchedItems[index]?.quantity) || 0) * (Number(watchedItems[index]?.unitPrice) || 0)
const lineTotal =
(Number(watchedItems[index]?.quantity) || 0) *
(Number(watchedItems[index]?.unitPrice) || 0)
return (
<tr key={fieldItem.id} className="border-t align-top">
@@ -336,7 +224,7 @@ export default function NewSalePage() {
<SelectItem value="" disabled>Select item...</SelectItem>
{itemsList.map((item) => (
<SelectItem key={item.id} value={item.id}>
{item.name} - {item.sku}
{item.name} — {item.sku}
</SelectItem>
))}
</SelectContent>
@@ -356,9 +244,6 @@ export default function NewSalePage() {
name={`items.${index}.quantity`}
render={({ field, invalid }) => (
<Input
id={`items.${index}.quantity`}
name={field.name}
ref={field.ref}
type="number"
min={1}
value={Number(field.value as number)}
@@ -377,9 +262,6 @@ export default function NewSalePage() {
name={`items.${index}.unitPrice`}
render={({ field, invalid }) => (
<Input
id={`items.${index}.unitPrice`}
name={field.name}
ref={field.ref}
type="number"
min={0.01}
step="0.01"
@@ -393,12 +275,12 @@ export default function NewSalePage() {
/>
{priceMinByIndex[index] != null && (
<p className="mt-1 text-xs text-muted-foreground">
Negotiable down to {fmtAmount(priceMinByIndex[index]!)}
Min: {fmtAmount(priceMinByIndex[index]!)}
</p>
)}
{priceRetailByIndex[index] != null && (
<p className="mt-1 text-xs text-muted-foreground">
Retail price: {fmtAmount(priceRetailByIndex[index]!)}
Retail: {fmtAmount(priceRetailByIndex[index]!)}
</p>
)}
</td>
@@ -426,9 +308,9 @@ export default function NewSalePage() {
<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">Sale Summary</h3>
<h3 className="text-sm font-medium text-foreground">Order Summary</h3>
<p className="mt-1 text-sm text-muted-foreground">
{watchedItems.length} item{watchedItems.length === 1 ? '' : 's'} on this sale.
{watchedItems.length} item{watchedItems.length === 1 ? '' : 's'} on this order.
</p>
<Separator className="my-4" />
@@ -440,7 +322,7 @@ export default function NewSalePage() {
<div className="mt-6 flex flex-col gap-2">
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Creating...' : 'Create Sale'}
{form.formState.isSubmitting ? 'Creating...' : 'Create Shop PO'}
</Button>
<Button type="button" variant="outline" onClick={() => router.push('/sales')}>
Cancel
@@ -1,111 +1,2 @@
'use client'
import { useEffect } from 'react'
import { useForm, zodResolver, z } from '@/lib/form'
import { FormField } from '@/components/shared/form-field'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
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 { orders as ordersApi, getApiError } from '@/lib/api/index'
import type { OrderResponse, OrderStatus } from '@/types/api'
const STATUS_OPTIONS: OrderStatus[] = ['Pending', 'PartiallyFulfilled', 'Fulfilled', 'Cancelled']
const schema = z.object({
status: z.enum(['Pending', 'PartiallyFulfilled', 'Fulfilled', 'Cancelled']),
})
type FormValues = z.infer<typeof schema>
interface OrderEditStatusDialogProps {
open: boolean
onClose: () => void
onSuccess: () => void
order: OrderResponse | null
}
export function OrderEditStatusDialog({ open, onClose, onSuccess, order }: OrderEditStatusDialogProps) {
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: { status: 'Pending' },
})
useEffect(() => {
if (open && order) {
form.reset({ status: order.status })
}
}, [open, order])
if (!order) return null
async function onSubmit(values: FormValues) {
try {
await ordersApi.update(order!.id, values.status)
toast.add({ title: 'Order status updated', type: 'success' })
onSuccess()
onClose()
} catch (err) {
toast.add({ title: 'Failed to update order', 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 Order Status</DialogTitle>
<DialogDescription>
Changing this also updates the linked sale — Fulfilled completes the sale, Cancelled cancels it.
</DialogDescription>
</DialogHeader>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
<FieldGroup>
<FormField
control={form.control}
name="status"
label="Status"
required
render={({ field }) => (
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select status..." />
</SelectTrigger>
<SelectContent>
{STATUS_OPTIONS.map((s) => (
<SelectItem key={s} value={s}>{s}</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</FieldGroup>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Saving…' : 'Save Changes'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)
}
// Retained for compatibility — invoice status transitions are now handled inline via table row actions.
export {}
@@ -7,14 +7,18 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Separator } from '@/components/ui/separator'
import type { OrderResponse, OrderStatus } from '@/types/api'
import type { InvoiceResponse, InvoiceStatus, PaymentStatus } from '@/types/api'
const ORDER_STATUS_VARIANT: Record<OrderStatus, 'default' | 'secondary' | 'destructive'> = {
const INVOICE_STATUS_VARIANT: Record<InvoiceStatus, 'default' | 'secondary' | 'destructive'> = {
Draft: 'secondary',
Printed: 'secondary',
Finalized: 'default',
}
const PAYMENT_STATUS_VARIANT: Record<PaymentStatus, 'default' | 'secondary' | 'destructive'> = {
Pending: 'secondary',
PartiallyFulfilled: 'secondary',
Fulfilled: 'default',
Cancelled: 'destructive',
PartiallyPaid: 'secondary',
Paid: 'default',
}
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
@@ -30,8 +34,7 @@ const fmtDateTime = (v: string | null) =>
interface OrderViewSheetProps {
open: boolean
onClose: () => void
order: OrderResponse | null
storeName?: string
invoice: InvoiceResponse | null
}
function Row({ label, value }: { label: string; value: React.ReactNode }) {
@@ -43,61 +46,26 @@ function Row({ label, value }: { label: string; value: React.ReactNode }) {
)
}
export function OrderViewSheet({ open, onClose, order, storeName }: OrderViewSheetProps) {
if (!order) return null
export function OrderViewSheet({ open, onClose, invoice }: OrderViewSheetProps) {
if (!invoice) return null
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-2xl">
<DialogContent className="overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>Order Details</DialogTitle>
<DialogTitle>Invoice Details</DialogTitle>
</DialogHeader>
<div className="flex flex-col">
<Row label="Order ID" value={<span className="font-mono">{truncId(order.id)}</span>} />
<Row label="Sale ID" value={<span className="font-mono">{truncId(order.saleId)}</span>} />
<Row label="Store" value={storeName ?? <span className="font-mono">{truncId(order.storeId)}</span>} />
<Row label="Status" value={<Badge variant={ORDER_STATUS_VARIANT[order.status]}>{order.status}</Badge>} />
<Row label="Total Amount" value={fmtAmount(order.totalAmount)} />
<Row label="Order Date" value={fmtDateTime(order.orderDate)} />
<Row label="Fulfilled At" value={fmtDateTime(order.fulfilledAt)} />
<Row label="Created At" value={fmtDateTime(order.createdAt)} />
</div>
<Separator />
<div>
<p className="text-sm font-medium mb-2">Items ({order.items.length})</p>
<div className="overflow-x-auto rounded-md border">
<table className="w-full text-sm">
<thead className="bg-muted/50">
<tr>
<th className="text-left font-medium px-3 py-2">Item</th>
<th className="text-right font-medium px-3 py-2">Quantity</th>
<th className="text-right font-medium px-3 py-2">Fulfilled</th>
<th className="text-right font-medium px-3 py-2">Unit Price</th>
</tr>
</thead>
<tbody>
{order.items.length === 0 ? (
<tr>
<td colSpan={4} className="text-center text-muted-foreground px-3 py-4">
No items on this order.
</td>
</tr>
) : (
order.items.map((item) => (
<tr key={item.itemId} className="border-t">
<td className="px-3 py-2 font-mono">{truncId(item.itemId)}</td>
<td className="text-right px-3 py-2">{item.quantity}</td>
<td className="text-right px-3 py-2">{item.quantityFulfilled}</td>
<td className="text-right px-3 py-2">{fmtAmount(item.unitPrice)}</td>
</tr>
))
)}
</tbody>
</table>
</div>
<Row label="Invoice ID" value={<span className="font-mono">{truncId(invoice.id)}</span>} />
<Row label="Shop PO" value={<span className="font-mono">{truncId(invoice.shopPOId)}</span>} />
<Row label="Store" value={invoice.storeName} />
<Row label="Status" value={<Badge variant={INVOICE_STATUS_VARIANT[invoice.status]}>{invoice.status}</Badge>} />
<Row label="Payment" value={<Badge variant={PAYMENT_STATUS_VARIANT[invoice.paymentStatus]}>{invoice.paymentStatus}</Badge>} />
<Row label="Total Amount" value={fmtAmount(invoice.totalAmount)} />
<Row label="Printed At" value={fmtDateTime(invoice.printedAt)} />
<Row label="Finalized At" value={fmtDateTime(invoice.finalizedAt)} />
<Row label="Created At" value={fmtDateTime(invoice.createdAt)} />
</div>
</DialogContent>
</Dialog>
@@ -6,11 +6,10 @@ import { DataTable } from '@/components/shared/data-table'
import type { TableConfig } from '@/components/shared/data-table'
import { Badge } from '@/components/ui/badge'
import { toast } from '@/components/ui/toast'
import { orders as ordersApi, stores as storesApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { OrderResponse, OrderStatus, StoreResponse } from '@/types/api'
import { invoices as invoicesApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { InvoiceResponse, InvoiceStatus, PaymentStatus } from '@/types/api'
import { OrderViewSheet } from './order-view-sheet'
import { OrderEditStatusDialog } from './order-edit-status-dialog'
const fmtDate = (v: string) =>
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
@@ -18,78 +17,80 @@ const fmtDate = (v: string) =>
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
const truncId = (id: string) => id.substring(0, 8)
const ORDER_STATUS_VARIANT: Record<OrderStatus, 'default' | 'secondary' | 'destructive'> = {
const INVOICE_STATUS_VARIANT: Record<InvoiceStatus, 'default' | 'secondary' | 'destructive'> = {
Draft: 'secondary',
Printed: 'secondary',
Finalized: 'default',
}
const PAYMENT_STATUS_VARIANT: Record<PaymentStatus, 'default' | 'secondary' | 'destructive'> = {
Pending: 'secondary',
PartiallyFulfilled: 'secondary',
Fulfilled: 'default',
Cancelled: 'destructive',
PartiallyPaid: 'secondary',
Paid: 'default',
}
export function OrdersClient() {
const [data, setData] = useState<OrderResponse[]>([])
const [data, setData] = useState<InvoiceResponse[]>([])
const [loading, setLoading] = useState(true)
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
const [viewOpen, setViewOpen] = useState(false)
const [editOpen, setEditOpen] = useState(false)
const [selectedOrder, setSelectedOrder] = useState<OrderResponse | null>(null)
const [storesList, setStoresList] = useState<StoreResponse[]>([])
const [selectedInvoice, setSelectedInvoice] = useState<InvoiceResponse | null>(null)
const storesById = useMemo(
() => new Map(storesList.map((s) => [s.id, s.storeName])),
[storesList]
)
const fetchData = useCallback(async () => {
const fetchData = useCallback(async (p: number, ps: number) => {
setLoading(true)
try {
const items = await ordersApi.list()
setData(items)
setTotal(items.length)
const res = await invoicesApi.list({ page: p, pageSize: ps })
setData(getPaginatedItems(res))
setTotal(res.total)
} catch (err) {
toast.add({ title: 'Failed to load orders', description: getApiError(err), type: 'error' })
toast.add({ title: 'Failed to load invoices', description: getApiError(err), type: 'error' })
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
fetchData()
storesApi.list({ pageSize: 200 })
.then((res) => setStoresList(getPaginatedItems(res)))
.catch((err) => toast.add({ title: 'Failed to load stores', description: getApiError(err), type: 'error' }))
}, [fetchData])
fetchData(page, pageSize)
}, [fetchData, page, pageSize])
function handleView(row: OrderResponse) {
setSelectedOrder(row)
function handleView(row: InvoiceResponse) {
setSelectedInvoice(row)
setViewOpen(true)
}
function handleEdit(row: OrderResponse) {
setSelectedOrder(row)
setEditOpen(true)
}
async function handleDelete(row: OrderResponse) {
async function handlePrint(row: InvoiceResponse) {
try {
await ordersApi.delete(row.id)
toast.add({ title: 'Order cancelled', type: 'success' })
fetchData()
await invoicesApi.print(row.id)
toast.add({ title: 'Invoice marked as printed', type: 'success' })
fetchData(page, pageSize)
} catch (err) {
toast.add({ title: 'Failed to cancel order', description: getApiError(err), type: 'error' })
toast.add({ title: 'Failed to print invoice', description: getApiError(err), type: 'error' })
}
}
const tableConfig = useMemo<TableConfig<OrderResponse>>(() => ({
async function handleFinalize(row: InvoiceResponse) {
try {
await invoicesApi.finalize(row.id)
toast.add({ title: 'Invoice finalized', type: 'success' })
fetchData(page, pageSize)
} catch (err) {
toast.add({ title: 'Failed to finalize invoice', description: getApiError(err), type: 'error' })
}
}
const tableConfig = useMemo<TableConfig<InvoiceResponse>>(() => ({
rowKey: 'id',
serverSide: true,
stickyHeader: true,
emptyMessage: 'No orders found.',
emptyMessage: 'No invoices found.',
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
columns: [
{
key: 'id',
title: 'Order ID',
title: 'Invoice ID',
fields: ['id'],
width: 140,
cellRender: (row) => (
@@ -97,22 +98,10 @@ export function OrdersClient() {
),
},
{
key: 'saleId',
title: 'Sale ID',
fields: ['saleId'],
width: 140,
cellRender: (row) => (
<span className="font-mono text-sm">{truncId(row.saleId)}</span>
),
},
{
key: 'storeId',
key: 'store',
title: 'Store',
fields: ['storeId'],
minWidth: 160,
cellRender: (row) => (
<span className="text-sm">{storesById.get(row.storeId) ?? truncId(row.storeId)}</span>
),
fields: [{ key: 'storeName', primary: true }],
minWidth: 180,
},
{
key: 'totalAmount',
@@ -127,16 +116,19 @@ export function OrdersClient() {
key: 'status',
title: 'Status',
fields: ['status'],
width: 180,
width: 140,
cellRender: (row) => (
<Badge variant={ORDER_STATUS_VARIANT[row.status]}>{row.status}</Badge>
<Badge variant={INVOICE_STATUS_VARIANT[row.status]}>{row.status}</Badge>
),
},
{
key: 'orderDate',
title: 'Order Date',
fields: [{ key: 'orderDate', transform: (v) => fmtDate(v as string) }],
width: 140,
key: 'paymentStatus',
title: 'Payment',
fields: ['paymentStatus'],
width: 150,
cellRender: (row) => (
<Badge variant={PAYMENT_STATUS_VARIANT[row.paymentStatus]}>{row.paymentStatus}</Badge>
),
},
{
key: 'createdAt',
@@ -149,32 +141,32 @@ export function OrdersClient() {
actions: () => [
{
action: 'view',
label: 'View order',
label: 'View invoice',
onClick: handleView,
},
{
action: 'edit',
label: 'Edit status',
onClick: handleEdit,
visible: (target) => target.status !== 'Cancelled',
action: 'print',
label: 'Mark as printed',
onClick: handlePrint,
visible: (target) => target.status === 'Draft',
},
{
action: 'cancel',
label: 'Delete order',
onClick: handleDelete,
visible: (target) => target.status !== 'Cancelled',
action: 'finalize',
label: 'Finalize invoice',
onClick: handleFinalize,
visible: (target) => target.status === 'Printed',
},
],
},
}), [pageSize, storesById])
}), [pageSize])
return (
<>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-semibold text-foreground">Orders</h1>
<h1 className="text-2xl font-semibold text-foreground">Invoices</h1>
<p className="text-sm text-muted-foreground mt-0.5">
Fulfillment status of store orders
Billing documents generated from confirmed Shop POs
</p>
</div>
</div>
@@ -185,6 +177,7 @@ export function OrdersClient() {
loading={loading}
totalCount={total}
onServerSideChange={({ page: p }) => {
setPage(p.page)
setPageSize(p.pageSize)
}}
/>
@@ -192,15 +185,7 @@ export function OrdersClient() {
<OrderViewSheet
open={viewOpen}
onClose={() => setViewOpen(false)}
order={selectedOrder}
storeName={selectedOrder ? storesById.get(selectedOrder.storeId) : undefined}
/>
<OrderEditStatusDialog
open={editOpen}
onClose={() => setEditOpen(false)}
onSuccess={fetchData}
order={selectedOrder}
invoice={selectedInvoice}
/>
</>
)
@@ -1,6 +1,6 @@
'use client'
import { useEffect, useState } from 'react'
import { useEffect } from 'react'
import { useForm, zodResolver, z } from '@/lib/form'
import { FormField } from '@/components/shared/form-field'
import { Input } from '@/components/ui/input'
@@ -22,14 +22,13 @@ import {
} from '@/components/ui/dialog'
import { FieldGroup } from '@/components/ui/field'
import { toast } from '@/components/ui/toast'
import { payments as paymentsApi, sales as salesApi, users as usersApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { SaleResponse, UserResponse } from '@/types/api'
import { payments as paymentsApi, getApiError } from '@/lib/api/index'
import type { InvoiceResponse } from '@/types/api'
const schema = z.object({
saleId: z.string().min(1, 'Sale is required'),
invoiceId: z.string().min(1, 'Invoice is required'),
amount: z.number().min(0.01, 'Amount must be greater than 0'),
method: z.enum(['Cash', 'Credit']),
collectedByUserId: z.string().min(1, 'Collected by is required'),
})
type FormValues = z.infer<typeof schema>
@@ -38,51 +37,31 @@ interface PaymentSheetProps {
open: boolean
onClose: () => void
onSuccess: () => void
invoices: InvoiceResponse[]
}
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
const truncId = (id: string) => id.substring(0, 8)
export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
const [salesList, setSalesList] = useState<SaleResponse[]>([])
const [usersList, setUsersList] = useState<UserResponse[]>([])
export function PaymentSheet({ open, onClose, onSuccess, invoices }: PaymentSheetProps) {
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: {
saleId: '',
invoiceId: '',
amount: 0,
method: 'Cash',
collectedByUserId: '',
},
})
useEffect(() => {
if (!open) return
form.reset({
saleId: '',
amount: 0,
method: 'Cash',
collectedByUserId: '',
})
Promise.all([
salesApi.list({ pageSize: 200 }),
usersApi.list({ pageSize: 200 }),
])
.then(([salesRes, usersRes]) => {
setSalesList(getPaginatedItems(salesRes).filter((s) => s.status !== 'Cancelled'))
setUsersList(getPaginatedItems(usersRes))
})
.catch((err) => {
toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' })
})
form.reset({ invoiceId: '', amount: 0, method: 'Cash' })
}, [open])
async function onSubmit(values: FormValues) {
const { invoiceId, ...rest } = values
try {
await paymentsApi.create(values)
await paymentsApi.create(invoiceId, rest)
toast.add({ title: 'Payment recorded', type: 'success' })
onSuccess()
onClose()
@@ -91,31 +70,33 @@ export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
}
}
const pendingInvoices = invoices.filter((inv) => inv.paymentStatus !== 'Paid')
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>Record Payment</DialogTitle>
<DialogDescription>Record a cash or credit payment against a sale.</DialogDescription>
<DialogDescription>Record a cash or credit payment against an invoice.</DialogDescription>
</DialogHeader>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
<FieldGroup>
<FormField
control={form.control}
name="saleId"
label="Sale"
name="invoiceId"
label="Invoice"
required
render={({ field }) => (
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select sale..." />
<SelectValue placeholder="Select invoice..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select sale...</SelectItem>
{salesList.map((sale) => (
<SelectItem key={sale.id} value={sale.id}>
{truncId(sale.id)} — {fmtAmount(sale.totalAmount)} ({sale.paymentStatus})
<SelectItem value="" disabled>Select invoice...</SelectItem>
{pendingInvoices.map((inv) => (
<SelectItem key={inv.id} value={inv.id}>
{inv.storeName} — {fmtAmount(inv.totalAmount)} ({inv.paymentStatus}) [{truncId(inv.id)}]
</SelectItem>
))}
</SelectContent>
@@ -150,10 +131,7 @@ export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
label="Payment Method"
required
render={({ field }) => (
<Select
value={field.value as string}
onValueChange={field.onChange}
>
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select method" />
</SelectTrigger>
@@ -164,29 +142,6 @@ export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
</Select>
)}
/>
<FormField
control={form.control}
name="collectedByUserId"
label="Collected 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 user..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="" disabled>Select user...</SelectItem>
{usersList.map((user) => (
<SelectItem key={user.id} value={user.id}>
{user.fullName}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</FieldGroup>
<DialogFooter>
@@ -26,8 +26,7 @@ interface PaymentViewSheetProps {
open: boolean
onClose: () => void
payment: PaymentResponse | null
storeName?: string
collectedByName?: string
invoiceName?: string
}
function Row({ label, value }: { label: string; value: React.ReactNode }) {
@@ -39,7 +38,7 @@ function Row({ label, value }: { label: string; value: React.ReactNode }) {
)
}
export function PaymentViewSheet({ open, onClose, payment, storeName, collectedByName }: PaymentViewSheetProps) {
export function PaymentViewSheet({ open, onClose, payment, invoiceName }: PaymentViewSheetProps) {
if (!payment) return null
return (
@@ -51,12 +50,11 @@ export function PaymentViewSheet({ open, onClose, payment, storeName, collectedB
<div className="flex flex-col">
<Row label="Payment ID" value={<span className="font-mono">{truncId(payment.id)}</span>} />
<Row label="Sale ID" value={<span className="font-mono">{truncId(payment.saleId)}</span>} />
<Row label="Store" value={storeName ?? <span className="font-mono">{truncId(payment.storeId)}</span>} />
<Row label="Invoice" value={invoiceName ?? <span className="font-mono">{truncId(payment.invoiceId)}</span>} />
<Row label="Amount" value={fmtAmount(payment.amount)} />
<Row label="Method" value={<Badge variant={PAYMENT_METHOD_VARIANT[payment.method]}>{payment.method}</Badge>} />
<Row label="Collected At" value={fmtDateTime(payment.collectedAt)} />
<Row label="Collected By" value={collectedByName ?? <span className="font-mono">{truncId(payment.collectedBy)}</span>} />
<Row label="Collected By" value={<span className="font-mono">{truncId(payment.collectedBy)}</span>} />
<Row label="Created At" value={fmtDateTime(payment.createdAt)} />
</div>
</DialogContent>
@@ -8,9 +8,10 @@ import { DataTable } from '@/components/shared/data-table'
import type { TableConfig } from '@/components/shared/data-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { toast } from '@/components/ui/toast'
import { payments as paymentsApi, stores as storesApi, users as usersApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { PaymentResponse, PaymentMethod, StoreResponse, UserResponse } from '@/types/api'
import { invoices as invoicesApi, payments as paymentsApi, getApiError, getPaginatedItems } from '@/lib/api/index'
import type { PaymentResponse, PaymentMethod, InvoiceResponse } from '@/types/api'
import { PaymentSheet } from './payment-sheet'
import { PaymentViewSheet } from './payment-view-sheet'
@@ -27,33 +28,39 @@ const PAYMENT_METHOD_VARIANT: Record<PaymentMethod, 'default' | 'secondary'> = {
}
export function PaymentsClient() {
const [invoicesList, setInvoicesList] = useState<InvoiceResponse[]>([])
const [selectedInvoiceId, setSelectedInvoiceId] = useState('')
const [data, setData] = useState<PaymentResponse[]>([])
const [loading, setLoading] = useState(true)
const [loading, setLoading] = useState(false)
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
const [pageSize] = useState(20)
const [sheetOpen, setSheetOpen] = useState(false)
const [viewOpen, setViewOpen] = useState(false)
const [selectedPayment, setSelectedPayment] = useState<PaymentResponse | null>(null)
const [storesList, setStoresList] = useState<StoreResponse[]>([])
const [usersList, setUsersList] = useState<UserResponse[]>([])
const storeNameById = useMemo(
() => new Map(storesList.map((s) => [s.id, s.storeName])),
[storesList]
)
const userNameById = useMemo(
() => new Map(usersList.map((u) => [u.id, u.fullName])),
[usersList]
const invoiceNameById = useMemo(
() => new Map(invoicesList.map((inv) => [inv.id, `${inv.storeName} — ${truncId(inv.id)}`])),
[invoicesList]
)
const fetchData = useCallback(async (p: number, ps: number) => {
useEffect(() => {
invoicesApi.list({ pageSize: 200 })
.then((res) => setInvoicesList(getPaginatedItems(res)))
.catch((err) => toast.add({ title: 'Failed to load invoices', description: getApiError(err), type: 'error' }))
}, [])
const fetchData = useCallback(async (invoiceId: string) => {
if (!invoiceId) {
setData([])
setTotal(0)
return
}
setLoading(true)
try {
const res = await paymentsApi.list({ page: p, pageSize: ps })
setData(getPaginatedItems(res))
setTotal(res.total)
const items = await paymentsApi.listByInvoice(invoiceId)
setData(items)
setTotal(items.length)
} catch (err) {
toast.add({ title: 'Failed to load payments', description: getApiError(err), type: 'error' })
} finally {
@@ -62,17 +69,8 @@ export function PaymentsClient() {
}, [])
useEffect(() => {
fetchData(page, pageSize)
}, [fetchData, page, pageSize])
useEffect(() => {
storesApi.list({ pageSize: 200 })
.then((res) => setStoresList(getPaginatedItems(res)))
.catch((err) => toast.add({ title: 'Failed to load stores', description: getApiError(err), type: 'error' }))
usersApi.list({ pageSize: 200 })
.then((res) => setUsersList(getPaginatedItems(res)))
.catch((err) => toast.add({ title: 'Failed to load users', description: getApiError(err), type: 'error' }))
}, [])
fetchData(selectedInvoiceId)
}, [fetchData, selectedInvoiceId])
function handleView(row: PaymentResponse) {
setSelectedPayment(row)
@@ -81,9 +79,8 @@ export function PaymentsClient() {
const tableConfig = useMemo<TableConfig<PaymentResponse>>(() => ({
rowKey: 'id',
serverSide: true,
stickyHeader: true,
emptyMessage: 'No payments found.',
emptyMessage: selectedInvoiceId ? 'No payments found for this invoice.' : 'Enter an invoice ID to view its payments.',
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
columns: [
{
@@ -96,12 +93,12 @@ export function PaymentsClient() {
),
},
{
key: 'storeId',
title: 'Store',
fields: ['storeId'],
minWidth: 160,
key: 'invoiceId',
title: 'Invoice',
fields: ['invoiceId'],
minWidth: 180,
cellRender: (row) => (
<span className="text-sm">{storeNameById.get(row.storeId) ?? truncId(row.storeId)}</span>
<span className="text-sm">{invoiceNameById.get(row.invoiceId) ?? truncId(row.invoiceId)}</span>
),
},
{
@@ -128,15 +125,6 @@ export function PaymentsClient() {
fields: [{ key: 'collectedAt', transform: (v) => fmtDate(v as string) }],
width: 140,
},
{
key: 'collectedBy',
title: 'Collected By',
fields: ['collectedBy'],
minWidth: 160,
cellRender: (row) => (
<span className="text-sm text-muted-foreground">{userNameById.get(row.collectedBy) ?? truncId(row.collectedBy)}</span>
),
},
],
rowActions: {
actions: () => [
@@ -147,7 +135,7 @@ export function PaymentsClient() {
},
],
},
}), [pageSize, storeNameById, userNameById])
}), [pageSize, invoiceNameById])
return (
<>
@@ -155,7 +143,7 @@ export function PaymentsClient() {
<div>
<h1 className="text-2xl font-semibold text-foreground">Payments</h1>
<p className="text-sm text-muted-foreground mt-0.5">
Cash and credit payments collected from stores
Cash and credit payments collected against invoices
</p>
</div>
<Button onClick={() => setSheetOpen(true)}>
@@ -164,29 +152,38 @@ export function PaymentsClient() {
</Button>
</div>
<div className="flex items-center gap-2 max-w-sm">
<Input
placeholder="Paste invoice ID to filter payments..."
value={selectedInvoiceId}
onChange={(e) => setSelectedInvoiceId(e.target.value.trim())}
/>
{selectedInvoiceId && (
<Button variant="ghost" size="sm" onClick={() => setSelectedInvoiceId('')}>
Clear
</Button>
)}
</div>
<DataTable
config={tableConfig}
data={data}
loading={loading}
totalCount={total}
onServerSideChange={({ page: p }) => {
setPage(p.page)
setPageSize(p.pageSize)
}}
/>
<PaymentSheet
open={sheetOpen}
onClose={() => setSheetOpen(false)}
onSuccess={() => fetchData(page, pageSize)}
onSuccess={() => fetchData(selectedInvoiceId)}
invoices={invoicesList}
/>
<PaymentViewSheet
open={viewOpen}
onClose={() => setViewOpen(false)}
payment={selectedPayment}
storeName={selectedPayment ? storeNameById.get(selectedPayment.storeId) : undefined}
collectedByName={selectedPayment ? userNameById.get(selectedPayment.collectedBy) : undefined}
invoiceName={selectedPayment ? invoiceNameById.get(selectedPayment.invoiceId) : undefined}
/>
</>
)