c_agri_trade_code/frontend/src/features/bardana/BardanaLedgerView.tsx

499 lines
21 KiB
TypeScript

/**
* SCREEN-BARDANA-001: Bardana (Packaging Bags) Inventory Ledger & Commercials.
*
* Fulfills:
* - STORY-BARDANA-001 (FR-BARDANA-001, FR-BARDANA-002, FR-BARDANA-003):
* Double-entry packaging bag stock ledger, non-negative invariants, and packaging commercials.
*
* Styled per DESIGN.md: AgriTrade Mercantile (Tactile Corporate Minimalism).
*/
import React, { useState, useEffect, useCallback } from 'react';
import { Card } from '../../components/ui/Card';
import { Button } from '../../components/ui/Button';
import { StatusPill } from '../../components/ui/StatusPill';
import { apiClient } from '../../services/api';
import {
Package,
Layers,
ArrowDownLeft,
ArrowUpRight,
Calculator,
Plus,
RefreshCw,
AlertTriangle,
CheckCircle2,
ShieldCheck,
Building2,
} from 'lucide-react';
export interface BardanaBalance {
godown_id: string;
bag_type: string;
current_closing_count: number;
last_reference_id?: string;
last_updated?: string;
}
export interface StockEntryRecord {
id: string;
godown_id: string;
bag_type: string;
transaction_type: string;
reference_id: string;
opening_count: number;
inward_count: number;
outward_count: number;
damaged_count: number;
closing_count: number;
created_at: string;
}
export const BardanaLedgerView: React.FC = () => {
const [balances, setBalances] = useState<BardanaBalance[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const [activeGodown, setActiveGodown] = useState<string>('ALL');
// Modal states
const [isEntryModalOpen, setIsEntryModalOpen] = useState<boolean>(false);
const [isCalcModalOpen, setIsCalcModalOpen] = useState<boolean>(false);
// Form states
const [entryGodown, setEntryGodown] = useState<string>('WH-01');
const [entryBagType, setEntryBagType] = useState<string>('NEW_JUTE_50KG');
const [entryTxType, setEntryTxType] = useState<string>('PURCHASE_RECEIPT');
const [entryRefId, setEntryRefId] = useState<string>('');
const [entryOpening, setEntryOpening] = useState<number>(0);
const [entryInward, setEntryInward] = useState<number>(0);
const [entryOutward, setEntryOutward] = useState<number>(0);
const [entryDamaged, setEntryDamaged] = useState<number>(0);
// Calculator states
const [calcTerm, setCalcTerm] = useState<string>('BARDANA_ALAG');
const [calcCount, setCalcCount] = useState<number>(500);
const [calcRate, setCalcRate] = useState<number>(65.0);
const [calcResult, setCalcResult] = useState<any>(null);
const fetchBalances = useCallback(async () => {
setLoading(true);
setError(null);
try {
const url = activeGodown !== 'ALL'
? `/api/v1/bardana/balances?godown_id=${activeGodown}`
: '/api/v1/bardana/balances';
const res = await apiClient.get<{ balances: BardanaBalance[] }>(url);
setBalances(res.balances || []);
} catch (err: any) {
setError(err?.message || 'Failed to fetch bardana balances');
} finally {
setLoading(false);
}
}, [activeGodown]);
useEffect(() => {
fetchBalances();
}, [fetchBalances]);
const handleCreateEntry = async (e: React.FormEvent) => {
e.preventDefault();
try {
await apiClient.post('/api/v1/bardana/stock-entries', {
godown_id: entryGodown,
bag_type: entryBagType,
transaction_type: entryTxType,
reference_id: entryRefId,
opening_count: entryOpening,
inward_count: entryInward,
outward_count: entryOutward,
damaged_count: entryDamaged,
});
setIsEntryModalOpen(false);
fetchBalances();
} catch (err: any) {
alert(err?.message || 'Failed to record stock entry');
}
};
const handleCalculateCommercials = async () => {
try {
const res = await apiClient.post('/api/v1/bardana/calculate-commercials', {
packaging_term: calcTerm,
bag_count: calcCount,
bag_type: entryBagType,
bag_unit_rate: calcTerm === 'BARDANA_ALAG' ? calcRate : 0,
filling_rate_per_bag: 2.5,
stitching_rate_per_bag: 1.5,
marking_rate_per_bag: 0.5,
});
setCalcResult(res.commercials || res);
} catch (err: any) {
alert(err?.message || 'Calculation error');
}
};
const totalBags = balances.reduce((sum, b) => sum + b.current_closing_count, 0);
const juteBags = balances
.filter((b) => b.bag_type.includes('JUTE'))
.reduce((sum, b) => sum + b.current_closing_count, 0);
const syntheticBags = balances
.filter((b) => b.bag_type.includes('HDPE') || b.bag_type.includes('PP'))
.reduce((sum, b) => sum + b.current_closing_count, 0);
return (
<div className="space-y-6">
{/* View Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 pb-4 border-b border-card-border">
<div>
<div className="flex items-center space-x-2">
<h2 className="text-xl font-bold text-text-primary tracking-tight">Bardana Inventory Ledger</h2>
<StatusPill status="ACTIVE" label="Double-Entry Guarded" />
</div>
<p className="text-xs text-text-muted mt-1">
Tactile sub-ledger for packaging bags (New/Old Jute, HDPE, PP) and commercial billing reconciliation.
</p>
</div>
<div className="flex items-center space-x-3">
<Button variant="secondary" onClick={() => setIsCalcModalOpen(true)}>
<Calculator className="w-4 h-4 mr-1.5" />
Packaging Calculator
</Button>
<Button variant="primary" onClick={() => setIsEntryModalOpen(true)}>
<Plus className="w-4 h-4 mr-1.5" />
Record Movement
</Button>
<Button variant="secondary" onClick={fetchBalances} disabled={loading}>
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
</Button>
</div>
</div>
{/* Summary KPI Cards */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<Card className="p-4 border-l-4 border-l-accent-ochre">
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-text-muted">Total Closing Bags</span>
<Package className="w-4 h-4 text-accent-ochre" />
</div>
<div className="text-2xl font-bold font-mono text-text-primary mt-2">
{totalBags.toLocaleString()}
</div>
<p className="text-[11px] text-text-muted mt-1">Across all storage godowns</p>
</Card>
<Card className="p-4 border-l-4 border-l-emerald-600">
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-text-muted">Jute Packaging</span>
<Layers className="w-4 h-4 text-emerald-600" />
</div>
<div className="text-2xl font-bold font-mono text-text-primary mt-2">
{juteBags.toLocaleString()}
</div>
<p className="text-[11px] text-text-muted mt-1">50kg & 100kg Gunny standard</p>
</Card>
<Card className="p-4 border-l-4 border-l-blue-600">
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-text-muted">Synthetic (HDPE / PP)</span>
<ShieldCheck className="w-4 h-4 text-blue-600" />
</div>
<div className="text-2xl font-bold font-mono text-text-primary mt-2">
{syntheticBags.toLocaleString()}
</div>
<p className="text-[11px] text-text-muted mt-1">Moisture barrier bags</p>
</Card>
<Card className="p-4 border-l-4 border-l-amber-600">
<div className="flex items-center justify-between">
<span className="text-xs font-mono uppercase text-text-muted">Active Godowns</span>
<Building2 className="w-4 h-4 text-amber-600" />
</div>
<div className="text-2xl font-bold font-mono text-text-primary mt-2">
{new Set(balances.map((b) => b.godown_id)).size || 1}
</div>
<p className="text-[11px] text-text-muted mt-1">Storage centres configured</p>
</Card>
</div>
{/* Main Stock Table */}
<Card className="overflow-hidden">
<div className="p-4 border-b border-card-border flex items-center justify-between bg-card-surface/50">
<div className="flex items-center space-x-2">
<Package className="w-4 h-4 text-accent-ochre" />
<h3 className="text-sm font-semibold text-text-primary">Physical Bag Balances by Godown</h3>
</div>
<div className="flex items-center space-x-2">
<span className="text-xs text-text-muted font-mono">Filter Godown:</span>
<select
value={activeGodown}
onChange={(e) => setActiveGodown(e.target.value)}
className="text-xs bg-sidebar-surface text-white border border-sidebar-active rounded px-2 py-1"
>
<option value="ALL">All Godowns</option>
<option value="WH-01">Central Godown 01 (WH-01)</option>
<option value="WH-02">Mandi Yard Shed B (WH-02)</option>
</select>
</div>
</div>
{error && (
<div className="p-4 bg-red-950/20 border-b border-red-800/40 text-red-400 text-xs flex items-center space-x-2">
<AlertTriangle className="w-4 h-4 flex-shrink-0" />
<span>{error}</span>
</div>
)}
<div className="overflow-x-auto">
<table className="w-full text-left text-xs">
<thead className="bg-card-surface border-b border-card-border text-text-muted uppercase font-mono text-[10px]">
<tr>
<th className="p-3">Godown</th>
<th className="p-3">Bag Type</th>
<th className="p-3 text-right">Closing Count</th>
<th className="p-3">Last Reference</th>
<th className="p-3">Last Movement</th>
<th className="p-3 text-center">Invariant Status</th>
</tr>
</thead>
<tbody className="divide-y divide-card-border font-mono">
{balances.length === 0 ? (
<tr>
<td colSpan={6} className="p-8 text-center text-text-muted">
No bardana balance records found for selected godown. Click "Record Movement" to initialize stock.
</td>
</tr>
) : (
balances.map((b, idx) => (
<tr key={idx} className="hover:bg-card-surface/50 transition">
<td className="p-3 font-semibold text-text-primary">{b.godown_id}</td>
<td className="p-3">
<span className="px-2 py-0.5 rounded text-[11px] bg-sidebar-active text-gray-200">
{b.bag_type}
</span>
</td>
<td className="p-3 text-right font-bold text-text-primary text-sm">
{b.current_closing_count.toLocaleString()}
</td>
<td className="p-3 text-text-muted">{b.last_reference_id || 'INITIAL'}</td>
<td className="p-3 text-text-muted">
{b.last_updated ? new Date(b.last_updated).toLocaleString() : 'N/A'}
</td>
<td className="p-3 text-center">
<span className="inline-flex items-center text-[10px] text-emerald-400 gap-1 bg-emerald-950/30 px-2 py-0.5 rounded border border-emerald-800/40">
<CheckCircle2 className="w-3 h-3" />
Closing ≥ 0
</span>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</Card>
{/* Commercial Terms Calculator Modal */}
{isCalcModalOpen && (
<div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
<Card className="max-w-md w-full p-6 space-y-4">
<div className="flex items-center justify-between border-b border-card-border pb-3">
<h3 className="text-sm font-bold text-text-primary flex items-center gap-2">
<Calculator className="w-4 h-4 text-accent-ochre" />
Packaging Commercial Terms Calculator
</h3>
<button
onClick={() => setIsCalcModalOpen(false)}
className="text-text-muted hover:text-white"
>
&times;
</button>
</div>
<div className="space-y-3 text-xs">
<div>
<label className="block text-text-muted font-mono mb-1">Packaging Commercial Term</label>
<select
value={calcTerm}
onChange={(e) => setCalcTerm(e.target.value)}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
>
<option value="BARDANA_ALAG">BARDANA_ALAG (Billed Extra Line-Item)</option>
<option value="BARDANA_SAHIT">BARDANA_SAHIT (Included in Grain Rate)</option>
<option value="BARDANA_WAPSI">BARDANA_WAPSI (Returnable Bags)</option>
</select>
</div>
<div>
<label className="block text-text-muted font-mono mb-1">Bag Count</label>
<input
type="number"
value={calcCount}
onChange={(e) => setCalcCount(Number(e.target.value))}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
/>
</div>
{calcTerm === 'BARDANA_ALAG' && (
<div>
<label className="block text-text-muted font-mono mb-1">Bag Rate (₹ / Bag)</label>
<input
type="number"
value={calcRate}
onChange={(e) => setCalcRate(Number(e.target.value))}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
/>
</div>
)}
<Button variant="primary" className="w-full" onClick={handleCalculateCommercials}>
Execute Calculation
</Button>
{calcResult && (
<div className="p-3 bg-sidebar-surface border border-accent-ochre/30 rounded font-mono text-xs space-y-1">
<div className="flex justify-between">
<span>Bag Billing Amount:</span>
<span className="font-bold text-white">₹{calcResult.bag_billing_amount?.toFixed(2)}</span>
</div>
<div className="flex justify-between">
<span>Handling Labor (Fill/Stitch/Mark):</span>
<span className="text-white">₹{calcResult.packaging_labor_amount?.toFixed(2)}</span>
</div>
<div className="flex justify-between border-t border-card-border pt-1 font-bold text-accent-ochre">
<span>Total Landed Packaging:</span>
<span>₹{calcResult.total_packaging_cost?.toFixed(2)}</span>
</div>
</div>
)}
</div>
</Card>
</div>
)}
{/* Record Stock Movement Modal */}
{isEntryModalOpen && (
<div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
<Card className="max-w-lg w-full p-6 space-y-4">
<div className="flex items-center justify-between border-b border-card-border pb-3">
<h3 className="text-sm font-bold text-text-primary flex items-center gap-2">
<Plus className="w-4 h-4 text-accent-ochre" />
Record Packaging Bag Movement
</h3>
<button
onClick={() => setIsEntryModalOpen(false)}
className="text-text-muted hover:text-white"
>
&times;
</button>
</div>
<form onSubmit={handleCreateEntry} className="space-y-3 text-xs">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-text-muted font-mono mb-1">Godown</label>
<input
type="text"
value={entryGodown}
onChange={(e) => setEntryGodown(e.target.value)}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
required
/>
</div>
<div>
<label className="block text-text-muted font-mono mb-1">Bag Type</label>
<select
value={entryBagType}
onChange={(e) => setEntryBagType(e.target.value)}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
>
<option value="NEW_JUTE_50KG">NEW_JUTE_50KG</option>
<option value="OLD_JUTE_50KG">OLD_JUTE_50KG</option>
<option value="NEW_JUTE_100KG">NEW_JUTE_100KG</option>
<option value="HDPE_50KG">HDPE_50KG</option>
<option value="PP_25KG">PP_25KG</option>
</select>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-text-muted font-mono mb-1">Transaction Type</label>
<select
value={entryTxType}
onChange={(e) => setEntryTxType(e.target.value)}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
>
<option value="PURCHASE_RECEIPT">PURCHASE_RECEIPT</option>
<option value="FARMER_DECANTED">FARMER_DECANTED</option>
<option value="DISPATCH_PACKED">DISPATCH_PACKED</option>
<option value="BURST_WRITEOFF">BURST_WRITEOFF</option>
<option value="INTER_GODOWN_TRANSFER">INTER_GODOWN_TRANSFER</option>
</select>
</div>
<div>
<label className="block text-text-muted font-mono mb-1">Reference ID</label>
<input
type="text"
placeholder="e.g. PO-BAG-001"
value={entryRefId}
onChange={(e) => setEntryRefId(e.target.value)}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
required
/>
</div>
</div>
<div className="grid grid-cols-4 gap-2">
<div>
<label className="block text-text-muted font-mono mb-1">Opening</label>
<input
type="number"
value={entryOpening}
onChange={(e) => setEntryOpening(Number(e.target.value))}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
/>
</div>
<div>
<label className="block text-text-muted font-mono mb-1">Inward</label>
<input
type="number"
value={entryInward}
onChange={(e) => setEntryInward(Number(e.target.value))}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
/>
</div>
<div>
<label className="block text-text-muted font-mono mb-1">Outward</label>
<input
type="number"
value={entryOutward}
onChange={(e) => setEntryOutward(Number(e.target.value))}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
/>
</div>
<div>
<label className="block text-text-muted font-mono mb-1">Damaged</label>
<input
type="number"
value={entryDamaged}
onChange={(e) => setEntryDamaged(Number(e.target.value))}
className="w-full bg-sidebar-surface text-white border border-card-border rounded p-2"
/>
</div>
</div>
<div className="pt-2">
<Button variant="primary" type="submit" className="w-full">
Commit Stock Entry
</Button>
</div>
</form>
</Card>
</div>
)}
</div>
);
};
export default BardanaLedgerView;