Audit pass: cookie auth migration, route guards, GP% clamp, CSV export, OCR transaction safety, N+1 fix, and cleanup
- Migrated all 435 frontend fetch calls from Authorization Bearer header to credentials: 'include' (cookie auth) - Removed ?token= from all file/image URLs (browser history exposure) - Added ProtectedRoute wrapper to all capability-gated routes in App.tsx - OCR background task: added transaction boundary, improved error handling and status rollback - DuplicateDetector: wrapped in non-fatal try/except so crashes don't abort invoice processing - File upload: commit DB row before writing to disk to prevent orphaned files - GP% clamped to 100% in GPReport (credit notes can inflate above 100%) - Added CSV export to GPReport (suppliers, daily data, allowances breakdown) - Backend file-serving endpoints: cookie auth with ?token= fallback for backward compatibility - DATA_DIR: moved from hardcoded /app/data to os.getenv in invoices.py and recipes.py - N+1 fix in list_recipes: batch-loads latest cost snapshot in 1 query (was N) - Zero-yield sub-recipe: logs warning instead of silently zeroing cost contribution - Budget spend rate input: rejects negative values - GPReport allowances toggle: persisted to localStorage across page loads - DB pool_size/max_overflow: configurable via DB_POOL_SIZE/DB_MAX_OVERFLOW env vars - Fixed SyntaxWarning from \\d in invoices.py docstring Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
6f6e16c88f
commit
ba075276b1
57 changed files with 15427 additions and 15274 deletions
|
|
@ -158,14 +158,22 @@ export default function GPReport() {
|
|||
const monthOptions = getMonthOptions()
|
||||
|
||||
// Allowances checkbox state - default: all checked EXCEPT wastage
|
||||
const [allowancesSelection, setAllowancesSelection] = useState({
|
||||
wastage: false, // Wastage: unchecked by default
|
||||
transfer: true, // Transfer: checked by default
|
||||
staffFood: true, // Staff Food: checked by default
|
||||
manualAdjustment: true, // Manual Adjustment: checked by default
|
||||
disputes: true, // Open Disputes: checked by default
|
||||
cdDeductions: true, // Distributed Deductions: checked by default
|
||||
cdReallocations: true // Distributed Reallocations: checked by default
|
||||
const _defaultAllowances = {
|
||||
wastage: false,
|
||||
transfer: true,
|
||||
staffFood: true,
|
||||
manualAdjustment: true,
|
||||
disputes: true,
|
||||
cdDeductions: true,
|
||||
cdReallocations: true,
|
||||
}
|
||||
const [allowancesSelection, setAllowancesSelection] = useState(() => {
|
||||
try {
|
||||
const stored = localStorage.getItem('gpreport_allowances_v1')
|
||||
return stored ? { ..._defaultAllowances, ...JSON.parse(stored) } : _defaultAllowances
|
||||
} catch {
|
||||
return _defaultAllowances
|
||||
}
|
||||
})
|
||||
|
||||
// Track if dates have changed since last generation
|
||||
|
|
@ -318,7 +326,7 @@ export default function GPReport() {
|
|||
queryKey: ['gp-range', submittedFromDate, submittedToDate],
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/kitchen/api/reports/gp/range?from_date=${submittedFromDate}&to_date=${submittedToDate}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch GP data')
|
||||
return res.json()
|
||||
|
|
@ -332,7 +340,7 @@ export default function GPReport() {
|
|||
queryKey: ['gp-daily', submittedFromDate, submittedToDate],
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/kitchen/api/reports/gp/daily?from_date=${submittedFromDate}&to_date=${submittedToDate}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch chart data')
|
||||
return res.json()
|
||||
|
|
@ -346,7 +354,7 @@ export default function GPReport() {
|
|||
queryKey: ['gp-top-sellers', submittedFromDate, submittedToDate],
|
||||
queryFn: async () => {
|
||||
const res = await fetch(`/kitchen/api/reports/gp/top-sellers?from_date=${submittedFromDate}&to_date=${submittedToDate}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
credentials: 'include',
|
||||
})
|
||||
if (!res.ok) {
|
||||
// Don't throw for top sellers - just return empty data
|
||||
|
|
@ -554,12 +562,62 @@ export default function GPReport() {
|
|||
|
||||
// Calculate GP with selected allowances + CD adjustments
|
||||
const gpWithSelectedAllowances = salesNum > 0
|
||||
? ((salesNum - adjustedPurchases + selectedAllowancesTotal) / salesNum * 100)
|
||||
? Math.min((salesNum - adjustedPurchases + selectedAllowancesTotal) / salesNum * 100, 100)
|
||||
: 0
|
||||
|
||||
const downloadCSV = () => {
|
||||
if (!data) return
|
||||
const rows: string[][] = [
|
||||
['Kitchen Flash GP Report'],
|
||||
['Period', period_label],
|
||||
[],
|
||||
['Metric', 'Value'],
|
||||
['Net Food Sales', net_food_sales.toString()],
|
||||
['Net Food Purchases', net_food_purchases.toString()],
|
||||
['Gross Profit', gross_profit.toString()],
|
||||
['Gross Profit %', Number(gross_profit_percent).toFixed(2)],
|
||||
]
|
||||
if (hasAnyAllowancesData) {
|
||||
rows.push([])
|
||||
rows.push(['Adjustments', ''])
|
||||
if (hasWastage) rows.push(['Wastage', (wastage_total ?? 0).toString()])
|
||||
if (hasTransfer) rows.push(['Transfers', (transfer_total ?? 0).toString()])
|
||||
if (hasStaffFood) rows.push(['Staff Food', (staff_food_total ?? 0).toString()])
|
||||
if (hasManualAdjustment) rows.push(['Manual Adjustments', (manual_adjustment_total ?? 0).toString()])
|
||||
if (hasDisputes) rows.push(['Disputes', (disputes_total ?? 0).toString()])
|
||||
rows.push(['GP with Adjustments %', gpWithSelectedAllowances.toFixed(2)])
|
||||
}
|
||||
if (data.supplier_breakdown?.length) {
|
||||
rows.push([])
|
||||
rows.push(['Supplier', 'Net Purchases', '% of Total'])
|
||||
data.supplier_breakdown.forEach(s => {
|
||||
rows.push([s.supplier_name, s.net_purchases.toString(), s.percentage.toFixed(1)])
|
||||
})
|
||||
}
|
||||
if (chartData?.data?.length) {
|
||||
rows.push([])
|
||||
rows.push(['Date', 'Net Sales', 'Net Purchases', 'Covers'])
|
||||
chartData.data.forEach(d => {
|
||||
rows.push([d.date, d.net_sales.toString(), d.net_purchases.toString(), (d.total_covers ?? '').toString()])
|
||||
})
|
||||
}
|
||||
const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n')
|
||||
const blob = new Blob([csv], { type: 'text/csv' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `kitchen-flash-${submittedFromDate}-to-${submittedToDate}.csv`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
// Toggle checkbox handler
|
||||
const toggleAllowance = (key: keyof typeof allowancesSelection) => {
|
||||
setAllowancesSelection(prev => ({ ...prev, [key]: !prev[key] }))
|
||||
setAllowancesSelection(prev => {
|
||||
const next = { ...prev, [key]: !prev[key] }
|
||||
try { localStorage.setItem('gpreport_allowances_v1', JSON.stringify(next)) } catch {}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
@ -626,7 +684,14 @@ export default function GPReport() {
|
|||
</div>
|
||||
|
||||
{/* Period Label */}
|
||||
<div style={styles.periodLabel}>{getPeriodPrefix()}{period_label}</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '1rem' }}>
|
||||
<div style={styles.periodLabel}>{getPeriodPrefix()}{period_label}</div>
|
||||
{data && (
|
||||
<button onClick={downloadCSV} style={styles.csvBtn}>
|
||||
Download CSV
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Main Content - GP Estimate and Chart side by side */}
|
||||
<div style={styles.mainContent}>
|
||||
|
|
@ -1252,9 +1317,18 @@ const styles: Record<string, React.CSSProperties> = {
|
|||
fontSize: '1.1rem',
|
||||
fontWeight: 'bold',
|
||||
color: '#1a1a2e',
|
||||
marginBottom: '1rem',
|
||||
textAlign: 'center',
|
||||
},
|
||||
csvBtn: {
|
||||
padding: '0.4rem 0.9rem',
|
||||
fontSize: '0.8rem',
|
||||
background: 'transparent',
|
||||
border: '1px solid #1a1a2e',
|
||||
color: '#1a1a2e',
|
||||
borderRadius: '6px',
|
||||
cursor: 'pointer',
|
||||
whiteSpace: 'nowrap' as const,
|
||||
},
|
||||
mainContent: {
|
||||
display: 'flex',
|
||||
gap: '1.5rem',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue