Add Stock catalog (items/warehouses) and fix session persistence

Stock is scoped to a catalog + cost centers only, per direction that
physical GRV/stock-take/recipe transactions belong in an external
system (Matrix), not this accounting app. Stock Control/GRN/Variance/
PPV GL accounts are now plain postable accounts rather than locked
control accounts.

Also fixes session loss on page refresh: auth stores now persist to
localStorage, and ProtectedRoute waits for rehydration before deciding
to redirect to login.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JWqiUSojMLUoN7mrJqdEbN
This commit is contained in:
Joshua Oosthuizen
2026-09-04 10:35:04 +02:00
co-authored by Claude Sonnet 5
parent 4acbc03b35
commit b137176c40
35 changed files with 1199 additions and 46 deletions
+33
View File
@@ -0,0 +1,33 @@
import { apiClient } from './client';
import type { StockItem, StockLevel } from '../types/api';
export async function fetchStockItems(): Promise<StockItem[]> {
const response = await apiClient.get<StockItem[]>('/stock/items');
return response.data;
}
export async function fetchStockItem(id: number): Promise<StockItem> {
const response = await apiClient.get<StockItem>(`/stock/items/${id}`);
return response.data;
}
export async function fetchStockLevels(warehouseId?: number): Promise<StockLevel[]> {
const response = await apiClient.get<StockLevel[]>('/stock/items/levels', { params: { warehouseId } });
return response.data;
}
export interface StockItemInput {
code: string;
name: string;
unitOfMeasure: string;
}
export async function createStockItem(input: StockItemInput): Promise<StockItem> {
const response = await apiClient.post<StockItem>('/stock/items', input);
return response.data;
}
export async function updateStockItem(id: number, input: Partial<StockItemInput> & { isActive?: boolean }): Promise<StockItem> {
const response = await apiClient.put<StockItem>(`/stock/items/${id}`, input);
return response.data;
}
+26
View File
@@ -0,0 +1,26 @@
import { apiClient } from './client';
import type { Warehouse } from '../types/api';
import type { BranchSelection } from '../store/branchStore';
export async function fetchWarehouses(branchScope: BranchSelection): Promise<Warehouse[]> {
const response = await apiClient.get<Warehouse[]>('/stock/warehouses', {
params: { branchScope: branchScope === 'MAIN' ? 'MAIN' : String(branchScope) },
});
return response.data;
}
export interface WarehouseInput {
code: string;
name: string;
branchSegmentValueId: number;
}
export async function createWarehouse(input: WarehouseInput): Promise<Warehouse> {
const response = await apiClient.post<Warehouse>('/stock/warehouses', input);
return response.data;
}
export async function updateWarehouse(id: number, input: Partial<WarehouseInput> & { isActive?: boolean }): Promise<Warehouse> {
const response = await apiClient.put<Warehouse>(`/stock/warehouses/${id}`, input);
return response.data;
}
@@ -17,7 +17,7 @@ import type { GLAccountType, DebitCredit, ControlAccountType } from '../../../ty
const ACCOUNT_TYPES: GLAccountType[] = ['ASSET', 'LIABILITY', 'EQUITY', 'INCOME', 'EXPENSE'];
const DEBIT_CREDIT: DebitCredit[] = ['DEBIT', 'CREDIT'];
const CONTROL_TYPES: ControlAccountType[] = ['AR', 'AP', 'STOCK', 'TAX_OUTPUT', 'TAX_INPUT', 'BANK', 'RETAINED_EARNINGS'];
const CONTROL_TYPES: ControlAccountType[] = ['AR', 'AP', 'TAX_OUTPUT', 'TAX_INPUT', 'BANK', 'RETAINED_EARNINGS'];
export function GLAccountDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const { data: definitions } = useSegmentDefinitions();
@@ -0,0 +1,42 @@
import { useState } from 'react';
import { Box, Button, Card, Stack, Typography } from '@mui/material';
import { DataGrid, type GridColDef } from '@mui/x-data-grid';
import { useWarehouses } from '../../../hooks/useWarehouses';
import { useAuth } from '../../../hooks/useAuth';
import { StatusChip } from '../../../components/common/StatusChip';
import type { Warehouse } from '../../../types/api';
import { WarehouseDialog } from './WarehouseDialog';
export function AdminWarehousesPage() {
const { data: warehouses, isLoading } = useWarehouses('MAIN');
const { hasPermission } = useAuth();
const [dialogOpen, setDialogOpen] = useState(false);
const columns: GridColDef<Warehouse>[] = [
{ field: 'code', headerName: 'Code', width: 140 },
{ field: 'name', headerName: 'Name', flex: 1 },
{
field: 'isActive',
headerName: 'Status',
width: 100,
renderCell: (params) => <StatusChip status={params.row.isActive ? 'ACTIVE' : 'CLOSED'} />,
},
];
return (
<Box>
<Stack direction="row" sx={{ mb: 2, justifyContent: 'space-between', alignItems: 'center' }}>
<Typography variant="h5">Warehouses</Typography>
{hasPermission('stock.warehouse.manage') && (
<Button variant="contained" onClick={() => setDialogOpen(true)}>
New Warehouse
</Button>
)}
</Stack>
<Card sx={{ height: 500 }}>
<DataGrid rows={warehouses ?? []} columns={columns} loading={isLoading} density="compact" disableRowSelectionOnClick sx={{ border: 'none' }} />
</Card>
<WarehouseDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
</Box>
);
}
@@ -0,0 +1,63 @@
import { useState } from 'react';
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField } from '@mui/material';
import { useCreateWarehouse } from '../../../hooks/useWarehouses';
import { useSegmentDefinitions } from '../../../hooks/useSegments';
export function WarehouseDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const createWarehouse = useCreateWarehouse();
const { data: definitions } = useSegmentDefinitions();
const branchDef = (definitions ?? []).find((def) => def.isBranchSegment);
const [code, setCode] = useState('');
const [name, setName] = useState('');
const [branchSegmentValueId, setBranchSegmentValueId] = useState<number | ''>('');
const [error, setError] = useState<string | null>(null);
const handleSubmit = async () => {
setError(null);
if (!branchSegmentValueId) {
setError('Select a branch');
return;
}
try {
await createWarehouse.mutateAsync({ code, name, branchSegmentValueId });
onClose();
setCode('');
setName('');
setBranchSegmentValueId('');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create warehouse');
}
};
return (
<Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<DialogTitle>New Warehouse</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
<TextField label="Code" value={code} onChange={(e) => setCode(e.target.value)} />
<TextField label="Name" value={name} onChange={(e) => setName(e.target.value)} />
<TextField
select
label="Branch"
value={branchSegmentValueId}
onChange={(e) => setBranchSegmentValueId(Number(e.target.value))}
>
{(branchDef?.values ?? []).map((value) => (
<MenuItem key={value.id} value={value.id}>
{value.code} — {value.description}
</MenuItem>
))}
</TextField>
{error && <span style={{ color: 'red' }}>{error}</span>}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Cancel</Button>
<Button variant="contained" onClick={handleSubmit} disabled={createWarehouse.isPending}>
Create
</Button>
</DialogActions>
</Dialog>
);
}
@@ -0,0 +1,45 @@
import { useState } from 'react';
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Stack, TextField } from '@mui/material';
import { useCreateStockItem } from '../../../hooks/useStockItems';
export function StockItemDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const createStockItem = useCreateStockItem();
const [code, setCode] = useState('');
const [name, setName] = useState('');
const [unitOfMeasure, setUnitOfMeasure] = useState('');
const [error, setError] = useState<string | null>(null);
const handleSubmit = async () => {
setError(null);
try {
await createStockItem.mutateAsync({ code, name, unitOfMeasure });
onClose();
setCode('');
setName('');
setUnitOfMeasure('');
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create stock item');
}
};
return (
<Dialog open={open} onClose={onClose} maxWidth="xs" fullWidth>
<DialogTitle>New Stock Item</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
<TextField label="Code" value={code} onChange={(e) => setCode(e.target.value)} />
<TextField label="Name" value={name} onChange={(e) => setName(e.target.value)} />
<TextField label="Unit of measure" value={unitOfMeasure} onChange={(e) => setUnitOfMeasure(e.target.value)} helperText="e.g. EACH, KG, LOAF" />
{error && <span style={{ color: 'red' }}>{error}</span>}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Cancel</Button>
<Button variant="contained" onClick={handleSubmit} disabled={createStockItem.isPending}>
Create
</Button>
</DialogActions>
</Dialog>
);
}
@@ -0,0 +1,78 @@
import { useState } from 'react';
import { Box, Button, Card, Stack, Tab, Tabs, Typography } from '@mui/material';
import { DataGrid, type GridColDef } from '@mui/x-data-grid';
import { useStockItems, useStockLevels } from '../../../hooks/useStockItems';
import { useAuth } from '../../../hooks/useAuth';
import { StatusChip } from '../../../components/common/StatusChip';
import { MoneyCell } from '../../../components/common/MoneyCell';
import type { StockItem, StockLevel } from '../../../types/api';
import { StockItemDialog } from './StockItemDialog';
export function StockItemsListPage() {
const { data: items, isLoading: itemsLoading } = useStockItems();
const { data: levels, isLoading: levelsLoading } = useStockLevels();
const { hasPermission } = useAuth();
const [dialogOpen, setDialogOpen] = useState(false);
const [tab, setTab] = useState(0);
const itemColumns: GridColDef<StockItem>[] = [
{ field: 'code', headerName: 'Code', width: 140 },
{ field: 'name', headerName: 'Name', flex: 1 },
{ field: 'unitOfMeasure', headerName: 'UoM', width: 100 },
{
field: 'isActive',
headerName: 'Status',
width: 100,
renderCell: (params) => <StatusChip status={params.row.isActive ? 'ACTIVE' : 'CLOSED'} />,
},
];
const levelColumns: GridColDef<StockLevel>[] = [
{ field: 'item', headerName: 'Item', flex: 1, valueGetter: (_v, row) => row.item?.name },
{ field: 'warehouse', headerName: 'Warehouse', width: 200, valueGetter: (_v, row) => row.warehouse?.name },
{
field: 'quantityOnHand',
headerName: 'Qty On Hand',
width: 140,
align: 'right',
headerAlign: 'right',
renderCell: (params) => <MoneyCell value={params.row.quantityOnHand} />,
},
];
return (
<Box>
<Stack direction="row" sx={{ mb: 2, justifyContent: 'space-between', alignItems: 'center' }}>
<Typography variant="h5">Stock Items</Typography>
{hasPermission('stock.item.manage') && (
<Button variant="contained" onClick={() => setDialogOpen(true)}>
New Stock Item
</Button>
)}
</Stack>
<Tabs value={tab} onChange={(_e, value) => setTab(value)} sx={{ mb: 2 }}>
<Tab label="Items" />
<Tab label="Stock Levels" />
</Tabs>
{tab === 0 && (
<Card sx={{ height: 650 }}>
<DataGrid rows={items ?? []} columns={itemColumns} loading={itemsLoading} density="compact" disableRowSelectionOnClick sx={{ border: 'none' }} />
</Card>
)}
{tab === 1 && (
<Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 1.5 }}>
Quantities on hand are reported by your external stock system — nothing is entered here.
</Typography>
<Card sx={{ height: 600 }}>
<DataGrid rows={levels ?? []} columns={levelColumns} loading={levelsLoading} density="compact" disableRowSelectionOnClick sx={{ border: 'none' }} />
</Card>
</Box>
)}
<StockItemDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
</Box>
);
}
+41
View File
@@ -0,0 +1,41 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
createStockItem,
fetchStockItem,
fetchStockItems,
fetchStockLevels,
updateStockItem,
type StockItemInput,
} from '../api/stockItems.api';
export function useStockItems() {
return useQuery({ queryKey: ['stockItems'], queryFn: fetchStockItems });
}
export function useStockItem(id: number | undefined) {
return useQuery({
queryKey: ['stockItem', id],
queryFn: () => fetchStockItem(id as number),
enabled: id !== undefined,
});
}
export function useStockLevels(warehouseId?: number) {
return useQuery({ queryKey: ['stockLevels', warehouseId], queryFn: () => fetchStockLevels(warehouseId) });
}
export function useCreateStockItem() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: createStockItem,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['stockItems'] }),
});
}
export function useUpdateStockItem() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, input }: { id: number; input: Partial<StockItemInput> & { isActive?: boolean } }) => updateStockItem(id, input),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['stockItems'] }),
});
}
+23
View File
@@ -0,0 +1,23 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { createWarehouse, fetchWarehouses, updateWarehouse, type WarehouseInput } from '../api/warehouses.api';
import type { BranchSelection } from '../store/branchStore';
export function useWarehouses(branchScope: BranchSelection) {
return useQuery({ queryKey: ['warehouses', branchScope], queryFn: () => fetchWarehouses(branchScope) });
}
export function useCreateWarehouse() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: createWarehouse,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['warehouses'] }),
});
}
export function useUpdateWarehouse() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, input }: { id: number; input: Partial<WarehouseInput> & { isActive?: boolean } }) => updateWarehouse(id, input),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['warehouses'] }),
});
}
+12
View File
@@ -33,6 +33,8 @@ import PercentOutlinedIcon from '@mui/icons-material/PercentOutlined';
import StorefrontOutlinedIcon from '@mui/icons-material/StorefrontOutlined';
import RequestQuoteOutlinedIcon from '@mui/icons-material/RequestQuoteOutlined';
import PriceCheckOutlinedIcon from '@mui/icons-material/PriceCheckOutlined';
import Inventory2OutlinedIcon from '@mui/icons-material/Inventory2Outlined';
import WarehouseOutlinedIcon from '@mui/icons-material/WarehouseOutlined';
import { BranchSwitcher } from '../components/common/BranchSwitcher';
import { useAuth } from '../hooks/useAuth';
import { NAVY, NAVY_SURFACE, ACCENT_BLUE } from '../theme';
@@ -68,6 +70,10 @@ const NAV_SECTIONS: { title: string; items: NavItem[] }[] = [
{ label: 'Payments', path: '/ap/payments', icon: <PriceCheckOutlinedIcon fontSize="small" /> },
],
},
{
title: 'Stock',
items: [{ label: 'Stock Items', path: '/stock/items', icon: <Inventory2OutlinedIcon fontSize="small" /> }],
},
{
title: 'General Ledger',
items: [
@@ -108,6 +114,12 @@ const NAV_SECTIONS: { title: string; items: NavItem[] }[] = [
},
{ label: 'Users & Roles', path: '/admin/users', icon: <GroupOutlinedIcon fontSize="small" />, permission: 'admin.users.manage' },
{ label: 'Tax Codes', path: '/admin/tax-codes', icon: <PercentOutlinedIcon fontSize="small" />, permission: 'admin.tax.manage' },
{
label: 'Warehouses',
path: '/admin/warehouses',
icon: <WarehouseOutlinedIcon fontSize="small" />,
permission: 'stock.warehouse.manage',
},
],
},
];
+7
View File
@@ -33,6 +33,8 @@ import { DebitNoteDetailPage } from '../features/ap/debitNotes/DebitNoteDetailPa
import { PaymentsListPage } from '../features/ap/payments/PaymentsListPage';
import { PaymentFormPage } from '../features/ap/payments/PaymentFormPage';
import { PaymentDetailPage } from '../features/ap/payments/PaymentDetailPage';
import { AdminWarehousesPage } from '../features/admin/warehouses/AdminWarehousesPage';
import { StockItemsListPage } from '../features/stock/items/StockItemsListPage';
export function AppRouter() {
return (
@@ -68,6 +70,9 @@ export function AppRouter() {
<Route element={<ProtectedRoute permission="admin.tax.manage" />}>
<Route path="/admin/tax-codes" element={<AdminTaxCodesPage />} />
</Route>
<Route element={<ProtectedRoute permission="stock.warehouse.manage" />}>
<Route path="/admin/warehouses" element={<AdminWarehousesPage />} />
</Route>
<Route path="/ar/customers" element={<CustomersListPage />} />
<Route path="/ar/customers/:id" element={<CustomerDetailPage />} />
@@ -102,6 +107,8 @@ export function AppRouter() {
<Route element={<ProtectedRoute permission="ap.payment.manage" />}>
<Route path="/ap/payments/new" element={<PaymentFormPage />} />
</Route>
<Route path="/stock/items" element={<StockItemsListPage />} />
</Route>
</Route>
+14 -4
View File
@@ -1,7 +1,8 @@
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import { Outlet } from 'react-router-dom';
import { Alert, Box, CircularProgress } from '@mui/material';
import { useAuth } from '../hooks/useAuth';
import { useAuthStore } from '../store/authStore';
interface ProtectedRouteProps {
permission?: string;
@@ -11,14 +12,23 @@ const managerUrl = import.meta.env.VITE_MANAGER_URL ?? 'http://localhost:5174';
export function ProtectedRoute({ permission }: ProtectedRouteProps) {
const { isAuthenticated, hasPermission } = useAuth();
// The auth store rehydrates from localStorage asynchronously — without waiting for that,
// isAuthenticated reads false on the very first render after a page reload and this would
// bounce straight to the Manager before the persisted session ever gets a chance to load.
const [hasHydrated, setHasHydrated] = useState(useAuthStore.persist.hasHydrated());
useEffect(() => {
if (!isAuthenticated) {
if (hasHydrated) return;
return useAuthStore.persist.onFinishHydration(() => setHasHydrated(true));
}, [hasHydrated]);
useEffect(() => {
if (hasHydrated && !isAuthenticated) {
window.location.href = managerUrl;
}
}, [isAuthenticated]);
}, [hasHydrated, isAuthenticated]);
if (!isAuthenticated) {
if (!hasHydrated || !isAuthenticated) {
return (
<Box sx={{ display: 'flex', minHeight: '100vh', alignItems: 'center', justifyContent: 'center' }}>
<CircularProgress />
+16 -11
View File
@@ -1,4 +1,5 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export interface AuthUser {
id: number;
@@ -19,14 +20,18 @@ interface AuthState {
hasPermission: (permissionKey: string) => boolean;
}
// Tokens are kept in memory only (not localStorage) to limit XSS exposure — a page reload
// requires signing in again in Phase 1. See the implementation plan §4.5.
export const useAuthStore = create<AuthState>((set, get) => ({
accessToken: null,
refreshToken: null,
user: null,
setSession: ({ accessToken, refreshToken, user }) => set({ accessToken, refreshToken, user }),
setAccessToken: (accessToken) => set({ accessToken }),
clearSession: () => set({ accessToken: null, refreshToken: null, user: null }),
hasPermission: (permissionKey) => get().user?.permissions.includes(permissionKey) ?? false,
}));
// Persisted to localStorage so a page reload doesn't force signing in again via the Manager.
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
accessToken: null,
refreshToken: null,
user: null,
setSession: ({ accessToken, refreshToken, user }) => set({ accessToken, refreshToken, user }),
setAccessToken: (accessToken) => set({ accessToken }),
clearSession: () => set({ accessToken: null, refreshToken: null, user: null }),
hasPermission: (permissionKey) => get().user?.permissions.includes(permissionKey) ?? false,
}),
{ name: 'cfm-auth-session' },
),
);
+32 -1
View File
@@ -1,6 +1,6 @@
export type GLAccountType = 'ASSET' | 'LIABILITY' | 'EQUITY' | 'INCOME' | 'EXPENSE';
export type DebitCredit = 'DEBIT' | 'CREDIT';
export type ControlAccountType = 'AR' | 'AP' | 'STOCK' | 'TAX_OUTPUT' | 'TAX_INPUT' | 'BANK' | 'RETAINED_EARNINGS';
export type ControlAccountType = 'AR' | 'AP' | 'TAX_OUTPUT' | 'TAX_INPUT' | 'BANK' | 'RETAINED_EARNINGS';
export type SegmentFormat = 'NUMERIC' | 'ALPHA' | 'ALPHANUMERIC';
export type JournalType = 'GENERAL' | 'SALES' | 'PURCHASES' | 'CASH_RECEIPT' | 'CASH_PAYMENT' | 'STOCK' | 'BANK' | 'CUSTOM';
export type JournalEntryStatus = 'DRAFT' | 'POSTED' | 'REVERSED';
@@ -377,3 +377,34 @@ export interface AppUser {
roles: { role: Role }[];
branchRestrictions: { branchSegmentValueId: number }[];
}
// Deliberately minimal: a catalog (StockItem) + cost centers (Warehouse) + a SOH view
// (StockLevel) for a future external stock system to populate — no transactional stock
// documents (GRV, stock takes, recipes) live in this app. See prisma/schema.prisma.
export interface Warehouse {
id: number;
code: string;
name: string;
branchSegmentValueId: number;
isActive: boolean;
}
export interface StockLevel {
id: number;
itemId: number;
item?: StockItem;
warehouseId: number;
warehouse?: Warehouse;
quantityOnHand: string;
updatedAt: string;
}
export interface StockItem {
id: number;
code: string;
name: string;
unitOfMeasure: string;
isActive: boolean;
stockLevels?: StockLevel[];
createdAt: string;
}