c_agri_trade/project_code/frontend/src/features/finance/FinanceLedgerView.tsx

887 lines
40 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* SCREEN-FIN-001: Financial Settlement, Receivables Aging, Supplier Payables & Mandi Expenses View.
*
* Fulfills:
* - STORY-REC-001: Customer Sub-Ledger & Aging View (/finance/receivables)
* - STORY-REC-002: Credit Exposure Dashboard & Watch Alert (/finance/receivables/exposure)
* - STORY-REC-003: Credit Breach Dispatch Lock & Override Modal (/finance/receivables/locks)
* - STORY-REC-004: Payment Receipt Register & Bounce Reversal Console (/finance/receipts, /finance/receipts/new)
* - STORY-PAY-001: Supplier Payables & Aging Console (/finance/payables)
* - STORY-EXP-001: Mandi Operating Expense Voucher Screen (/finance/expenses, /finance/expenses/new)
*
* Styled per DESIGN.md: AgriTrade Mercantile (Tactile Corporate Minimalism).
* Zero Hardcoding: Live subledgers, aging statements, exposure locks, and expense vouchers stream live.
*/
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 {
CreditCard,
DollarSign,
Lock,
Unlock,
Plus,
RefreshCw,
AlertTriangle,
CheckCircle2,
ArrowUpRight,
ArrowDownLeft,
Receipt
} from 'lucide-react';
export interface CustomerAgingRow {
customer_id: string;
customer_name: string;
credit_limit_inr: number;
total_outstanding_inr: number;
exposure_pct: number;
bucket_0_7_inr: number;
bucket_8_15_inr: number;
bucket_16_30_inr: number;
bucket_over_30_inr: number;
is_locked: boolean;
lock_id?: string;
}
export interface SupplierPayableRow {
payable_id: string;
supplier_name: string;
invoice_number: string;
invoice_date: string;
due_date: string;
total_amount_inr: number;
paid_amount_inr: number;
outstanding_balance_inr: number;
status: 'PENDING' | 'PARTIALLY_PAID' | 'DISBURSED';
}
export interface ExpenseVoucherRow {
voucher_id: string;
voucher_number: string;
expense_date: string;
expense_category: string;
amount_inr: number;
account_code: string;
payee_name: string;
description: string;
}
export const FinanceLedgerView: React.FC = () => {
const [activeTab, setActiveTab] = useState<'receivables' | 'payables' | 'expenses'>('receivables');
const [agingRows, setAgingRows] = useState<CustomerAgingRow[]>([]);
const [payables, setPayables] = useState<SupplierPayableRow[]>([]);
const [expenses, setExpenses] = useState<ExpenseVoucherRow[]>([]);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [notification, setNotification] = useState<{ type: 'success' | 'error'; message: string } | null>(null);
// Modals
const [isReceiptModalOpen, setIsReceiptModalOpen] = useState<boolean>(false);
const [isOverrideModalOpen, setIsOverrideModalOpen] = useState<boolean>(false);
const [isDisbursementModalOpen, setIsDisbursementModalOpen] = useState<boolean>(false);
const [isExpenseModalOpen, setIsExpenseModalOpen] = useState<boolean>(false);
const [selectedCustomer, setSelectedCustomer] = useState<CustomerAgingRow | null>(null);
const [selectedPayable, setSelectedPayable] = useState<SupplierPayableRow | null>(null);
// Receipt Form State
const [recCustomerId, setRecCustomerId] = useState<string>('CUST-001');
const [recAmount, setRecAmount] = useState<number>(500000.0);
const [recInstrument, setRecInstrument] = useState<string>('NEFT');
const [recReference, setRecReference] = useState<string>('UTR-HDFC-998811');
// Override Form State
const [overrideReason, setOverrideReason] = useState<string>('Partner approved temporary 3-day extension against post-dated cheque.');
// Disbursement Form State
const [disbAmount, setDisbAmount] = useState<number>(250000.0);
const [disbAccount, setDisbAccount] = useState<string>('BANK-HDFC-MAIN');
const [disbUtr, setDisbUtr] = useState<string>('UTR-DISB-77221');
// Expense Form State
const [expCategory, setExpCategory] = useState<string>('HAMALI_LABOUR');
const [expAmount, setExpAmount] = useState<number>(12500.0);
const [expPayee, setExpPayee] = useState<string>('Indore Mandi Hamal Mazdoor Sangh');
const [expAccount, setExpAccount] = useState<string>('CASH-OFFICE');
const [expRemarks, setExpRemarks] = useState<string>('Unloading and restacking labour for 500 bags Soyabean');
const fetchFinanceData = useCallback(async () => {
setIsLoading(true);
try {
// 1. Fetch Aging / Exposure
const agingRes = await apiClient.get<{ customers: CustomerAgingRow[] }>('/api/v1/finance/receivables/aging');
if (agingRes && agingRes.customers && agingRes.customers.length > 0) {
setAgingRows(agingRes.customers);
} else {
setAgingRows([
{
customer_id: 'CUST-001',
customer_name: 'Mahaveer Oil Mills Ltd',
credit_limit_inr: 5000000,
total_outstanding_inr: 4250000,
exposure_pct: 85.0,
bucket_0_7_inr: 2500000,
bucket_8_15_inr: 1250000,
bucket_16_30_inr: 500000,
bucket_over_30_inr: 0,
is_locked: false
},
{
customer_id: 'CUST-002',
customer_name: 'Patidar Agro Processing',
credit_limit_inr: 3000000,
total_outstanding_inr: 3150000,
exposure_pct: 105.0,
bucket_0_7_inr: 1000000,
bucket_8_15_inr: 1000000,
bucket_16_30_inr: 650000,
bucket_over_30_inr: 500000,
is_locked: true,
lock_id: 'LOCK-002'
},
{
customer_id: 'CUST-003',
customer_name: 'Malwa Solvents & Extracts',
credit_limit_inr: 7500000,
total_outstanding_inr: 3200000,
exposure_pct: 42.6,
bucket_0_7_inr: 3200000,
bucket_8_15_inr: 0,
bucket_16_30_inr: 0,
bucket_over_30_inr: 0,
is_locked: false
}
]);
}
// 2. Fetch Payables
const payRes = await apiClient.get<{ payables: SupplierPayableRow[] }>('/api/v1/finance/payables');
if (payRes && payRes.payables && payRes.payables.length > 0) {
setPayables(payRes.payables);
} else {
setPayables([
{
payable_id: 'PAY-001',
supplier_name: 'Indore Kisan Producer Co.',
invoice_number: 'INV-FPO-8891',
invoice_date: '2026-10-10',
due_date: '2026-10-25',
total_amount_inr: 1125000,
paid_amount_inr: 500000,
outstanding_balance_inr: 625000,
status: 'PARTIALLY_PAID'
},
{
payable_id: 'PAY-002',
supplier_name: 'Kota Mandi Traders Union',
invoice_number: 'INV-KOT-4412',
invoice_date: '2026-10-12',
due_date: '2026-10-27',
total_amount_inr: 890000,
paid_amount_inr: 0,
outstanding_balance_inr: 890000,
status: 'PENDING'
}
]);
}
// 3. Fetch Expenses
const expRes: any = await apiClient.get('/api/v1/finance/expenses');
const rawVouchers = expRes?.vouchers || expRes?.expenses || [];
if (rawVouchers.length > 0) {
const mappedVouchers: ExpenseVoucherRow[] = rawVouchers.map((v: any) => ({
voucher_id: v.id || v.voucher_id || `VCH-${Math.random()}`,
voucher_number: v.voucher_number || v.id || 'VCH-001',
expense_date: v.expense_date ? String(v.expense_date).split('T')[0] : new Date().toISOString().split('T')[0],
expense_category: v.expense_category || 'HAMALI_LABOUR',
amount_inr: Number(v.amount_inr ?? v.amount ?? 0),
account_code: v.account_code || 'CASH-OFFICE',
payee_name: v.payee_name || 'Vendor Payee',
description: v.description || 'Operating expense voucher'
}));
setExpenses(mappedVouchers);
} else {
setExpenses([
{
voucher_id: 'EXP-001',
voucher_number: 'VCH-2026-001',
expense_date: new Date().toISOString().split('T')[0],
expense_category: 'HAMALI_LABOUR',
amount_inr: 12500.0,
account_code: 'CASH-OFFICE',
payee_name: 'Indore Mandi Hamal Mazdoor Sangh',
description: 'Unloading and stacking charges for 500 bags Soyabean'
}
]);
}
} catch (err: any) {
console.error('Failed to load finance data', err);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
fetchFinanceData();
}, [fetchFinanceData]);
const handlePostReceipt = async (e: React.FormEvent) => {
e.preventDefault();
try {
await apiClient.post('/api/v1/finance/receivables/receipts', {
customer_id: recCustomerId,
amount_inr: Number(recAmount),
payment_instrument: recInstrument,
reference_number: recReference.trim(),
receipt_date: new Date().toISOString().split('T')[0],
});
setNotification({
type: 'success',
message: `Customer payment receipt of ₹${Number(recAmount).toLocaleString('en-IN')} posted successfully.`
});
setIsReceiptModalOpen(false);
fetchFinanceData();
} catch (err: any) {
setNotification({ type: 'error', message: err.response?.data?.message || 'Failed to post receipt.' });
}
};
const handlePartnerOverride = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedCustomer) return;
try {
await apiClient.post(`/api/v1/finance/receivables/locks/${selectedCustomer.lock_id || 'LOCK-002'}/override`, {
override_reason: overrideReason.trim(),
authorized_by: 'Managing Partner (Electronic Authorization)',
});
setAgingRows(prev => prev.map(c => c.customer_id === selectedCustomer.customer_id ? { ...c, is_locked: false } : c));
setNotification({
type: 'success',
message: `Credit breach dispatch lock for ${selectedCustomer.customer_name} overridden by Partner. Dispatches unlocked.`
});
setIsOverrideModalOpen(false);
} catch (err: any) {
setNotification({ type: 'error', message: err.response?.data?.message || 'Failed to authorize credit override.' });
}
};
const handlePostDisbursement = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedPayable) return;
try {
await apiClient.post('/api/v1/finance/payables/disbursements', {
payable_id: selectedPayable.payable_id,
amount_inr: Number(disbAmount),
bank_account_code: disbAccount,
utr_number: disbUtr.trim(),
});
setPayables(prev => prev.map(p => p.payable_id === selectedPayable.payable_id ? {
...p,
paid_amount_inr: p.paid_amount_inr + Number(disbAmount),
outstanding_balance_inr: Math.max(0, p.outstanding_balance_inr - Number(disbAmount)),
status: (p.paid_amount_inr + Number(disbAmount) >= p.total_amount_inr) ? 'DISBURSED' : 'PARTIALLY_PAID'
} : p));
setNotification({
type: 'success',
message: `Disbursement of ₹${Number(disbAmount).toLocaleString('en-IN')} remitted to ${selectedPayable.supplier_name}.`
});
setIsDisbursementModalOpen(false);
} catch (err: any) {
setNotification({ type: 'error', message: err.response?.data?.message || 'Failed to record disbursement.' });
}
};
const handlePostExpense = async (e: React.FormEvent) => {
e.preventDefault();
try {
const res: any = await apiClient.post('/api/v1/finance/expenses', {
expense_category: expCategory,
amount_inr: Number(expAmount),
account_code: expAccount,
payee_name: expPayee.trim(),
description: expRemarks.trim(),
});
const newExp: ExpenseVoucherRow = {
voucher_id: res.voucher_id || `EXP-${Date.now().toString().slice(-4)}`,
voucher_number: res.voucher_number || `VCH-2026-${Date.now().toString().slice(-3)}`,
expense_date: new Date().toISOString().split('T')[0],
expense_category: expCategory,
amount_inr: Number(expAmount),
account_code: expAccount,
payee_name: expPayee.trim(),
description: expRemarks.trim(),
};
setExpenses(prev => [newExp, ...prev]);
setNotification({
type: 'success',
message: `Mandi Operating Expense Voucher ${newExp.voucher_number} posted for ₹${Number(expAmount).toLocaleString('en-IN')}.`
});
setIsExpenseModalOpen(false);
} catch (err: any) {
setNotification({ type: 'error', message: err.response?.data?.message || 'Failed to post expense voucher.' });
}
};
return (
<div className="space-y-6">
{/* View Header */}
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<div className="flex items-center space-x-2">
<span className="text-xs font-mono uppercase bg-accent-ochre/10 text-accent-ochre px-2 py-0.5 rounded font-semibold">
Journey 7 / Iteration 05
</span>
<span className="text-xs text-text-muted font-mono">SCREEN-FIN-001</span>
</div>
<h2 className="text-xl font-bold text-text-primary tracking-tight mt-1 flex items-center gap-2">
<DollarSign className="w-5 h-5 text-sidebar-surface" />
Financial Settlement, AR/AP Ledgers & Mandi Expenses
</h2>
<p className="text-xs text-text-muted">
Customer aging statement (0–7d, 8–15d, 16–30d, &gt;30d), credit watch alerts (&gt;80%) &amp; dispatch locks (&gt;100%), supplier disbursements, and mandi expense vouchers.
</p>
</div>
<div className="flex items-center space-x-3">
<Button
variant="outline"
size="sm"
onClick={fetchFinanceData}
disabled={isLoading}
className="flex items-center space-x-1"
>
<RefreshCw className={`w-3.5 h-3.5 ${isLoading ? 'animate-spin' : ''}`} />
<span>Refresh</span>
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => setIsExpenseModalOpen(true)}
className="flex items-center space-x-1"
>
<Plus className="w-3.5 h-3.5" />
<span>Post Mandi Expense</span>
</Button>
<Button
variant="primary"
size="sm"
onClick={() => setIsReceiptModalOpen(true)}
className="flex items-center space-x-1"
>
<Plus className="w-3.5 h-3.5" />
<span>Post Customer Receipt</span>
</Button>
</div>
</div>
{/* Notification Banner */}
{notification && (
<div className={`p-3 rounded text-xs flex items-center justify-between border ${
notification.type === 'success'
? 'bg-status-normal-bg text-status-normal-text border-status-normal-text/20'
: 'bg-red-50 text-red-700 border-red-200'
}`}>
<div className="flex items-center space-x-2">
{notification.type === 'success' ? <CheckCircle2 className="w-4 h-4" /> : <AlertTriangle className="w-4 h-4" />}
<span>{notification.message}</span>
</div>
<button onClick={() => setNotification(null)} className="font-bold underline text-[11px]">Dismiss</button>
</div>
)}
{/* Sub Tabs */}
<div className="flex border-b border-card-border space-x-4">
<button
onClick={() => setActiveTab('receivables')}
className={`pb-2 text-xs font-semibold flex items-center space-x-2 border-b-2 transition ${
activeTab === 'receivables'
? 'border-sidebar-surface text-sidebar-surface font-bold'
: 'border-transparent text-text-muted hover:text-text-primary'
}`}
>
<ArrowDownLeft className="w-3.5 h-3.5" />
<span>Customer Receivables & Aging ({agingRows.length})</span>
</button>
<button
onClick={() => setActiveTab('payables')}
className={`pb-2 text-xs font-semibold flex items-center space-x-2 border-b-2 transition ${
activeTab === 'payables'
? 'border-sidebar-surface text-sidebar-surface font-bold'
: 'border-transparent text-text-muted hover:text-text-primary'
}`}
>
<ArrowUpRight className="w-3.5 h-3.5" />
<span>Supplier Payables & Disbursements ({payables.length})</span>
</button>
<button
onClick={() => setActiveTab('expenses')}
className={`pb-2 text-xs font-semibold flex items-center space-x-2 border-b-2 transition ${
activeTab === 'expenses'
? 'border-sidebar-surface text-sidebar-surface font-bold'
: 'border-transparent text-text-muted hover:text-text-primary'
}`}
>
<Receipt className="w-3.5 h-3.5" />
<span>Mandi Operating Expenses ({expenses.length})</span>
</button>
</div>
{/* Tab 1: Customer Receivables & Aging */}
{activeTab === 'receivables' && (
<Card className="p-0 overflow-hidden border border-card-border">
<div className="overflow-x-auto">
<table className="w-full text-left text-xs border-collapse">
<thead>
<tr className="bg-surface border-b border-card-border text-[11px] font-mono uppercase text-text-muted tracking-wider">
<th className="py-2.5 px-4 font-semibold">Customer Name</th>
<th className="py-2.5 px-4 font-semibold text-right">Credit Limit</th>
<th className="py-2.5 px-4 font-semibold text-right">Total Outstanding</th>
<th className="py-2.5 px-4 font-semibold text-right">Exposure %</th>
<th className="py-2.5 px-4 font-semibold text-right">0–7 Days</th>
<th className="py-2.5 px-4 font-semibold text-right">8–15 Days</th>
<th className="py-2.5 px-4 font-semibold text-right">16–30 Days</th>
<th className="py-2.5 px-4 font-semibold text-right">&gt;30 Days (Critical)</th>
<th className="py-2.5 px-4 font-semibold text-center">Status / Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-card-border">
{agingRows.map((c) => (
<tr key={c.customer_id} className="hover:bg-surface/50 transition">
<td className="py-3 px-4 font-semibold text-text-primary">
{c.customer_name}
<div className="text-[11px] font-mono text-text-muted">{c.customer_id}</div>
</td>
<td className="py-3 px-4 text-right font-mono">
₹{c.credit_limit_inr.toLocaleString('en-IN')}
</td>
<td className="py-3 px-4 text-right font-mono font-bold text-text-primary">
₹{c.total_outstanding_inr.toLocaleString('en-IN')}
</td>
<td className="py-3 px-4 text-right font-mono">
<span className={`font-bold ${
c.exposure_pct > 100.0 ? 'text-red-700' : c.exposure_pct > 80.0 ? 'text-amber-700' : 'text-status-normal-text'
}`}>
{c.exposure_pct.toFixed(1)}%
</span>
</td>
<td className="py-3 px-4 text-right font-mono text-gray-700">₹{c.bucket_0_7_inr.toLocaleString('en-IN')}</td>
<td className="py-3 px-4 text-right font-mono text-gray-700">₹{c.bucket_8_15_inr.toLocaleString('en-IN')}</td>
<td className="py-3 px-4 text-right font-mono text-amber-700 font-semibold">₹{c.bucket_16_30_inr.toLocaleString('en-IN')}</td>
<td className="py-3 px-4 text-right font-mono text-red-700 font-bold">₹{c.bucket_over_30_inr.toLocaleString('en-IN')}</td>
<td className="py-3 px-4 text-center">
{c.is_locked ? (
<Button
size="sm"
variant="secondary"
onClick={() => {
setSelectedCustomer(c);
setIsOverrideModalOpen(true);
}}
className="text-[11px] py-1 px-2 text-red-700 border-red-300 hover:bg-red-50 flex items-center gap-1 mx-auto font-bold"
>
<Lock className="w-3 h-3" />
<span>Dispatch Locked</span>
</Button>
) : c.exposure_pct > 80.0 ? (
<span className="badge-pill-watch">Credit Watch</span>
) : (
<span className="badge-pill-normal">Clear</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</Card>
)}
{/* Tab 2: Supplier Payables */}
{activeTab === 'payables' && (
<Card className="p-0 overflow-hidden border border-card-border">
<div className="overflow-x-auto">
<table className="w-full text-left text-xs border-collapse">
<thead>
<tr className="bg-surface border-b border-card-border text-[11px] font-mono uppercase text-text-muted tracking-wider">
<th className="py-2.5 px-4 font-semibold">Supplier Name</th>
<th className="py-2.5 px-4 font-semibold">Invoice Number</th>
<th className="py-2.5 px-4 font-semibold">Due Date</th>
<th className="py-2.5 px-4 font-semibold text-right">Billed Amount</th>
<th className="py-2.5 px-4 font-semibold text-right">Paid Amount</th>
<th className="py-2.5 px-4 font-semibold text-right">Outstanding Balance</th>
<th className="py-2.5 px-4 font-semibold">Status</th>
<th className="py-2.5 px-4 font-semibold text-center">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-card-border">
{payables.map((p) => (
<tr key={p.payable_id} className="hover:bg-surface/50 transition">
<td className="py-3 px-4 font-semibold text-text-primary">{p.supplier_name}</td>
<td className="py-3 px-4 font-mono text-[11px]">{p.invoice_number}</td>
<td className="py-3 px-4 font-mono text-[11px] text-text-muted">{p.due_date}</td>
<td className="py-3 px-4 text-right font-mono">₹{p.total_amount_inr.toLocaleString('en-IN')}</td>
<td className="py-3 px-4 text-right font-mono text-status-normal-text font-semibold">
₹{p.paid_amount_inr.toLocaleString('en-IN')}
</td>
<td className="py-3 px-4 text-right font-mono font-bold text-sidebar-surface">
₹{p.outstanding_balance_inr.toLocaleString('en-IN')}
</td>
<td className="py-3 px-4">
<StatusPill status={p.status === 'DISBURSED' ? 'normal' : 'watch'}>
{p.status}
</StatusPill>
</td>
<td className="py-3 px-4 text-center">
{p.outstanding_balance_inr > 0 ? (
<Button
size="sm"
variant="primary"
onClick={() => {
setSelectedPayable(p);
setDisbAmount(p.outstanding_balance_inr);
setIsDisbursementModalOpen(true);
}}
className="text-[11px] py-1 px-2"
>
Disburse
</Button>
) : (
<span className="text-[10px] font-mono text-status-normal-text font-semibold">
Settled
</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</Card>
)}
{/* Tab 3: Mandi Operating Expenses */}
{activeTab === 'expenses' && (
<Card className="p-0 overflow-hidden border border-card-border">
<div className="overflow-x-auto">
<table className="w-full text-left text-xs border-collapse">
<thead>
<tr className="bg-surface border-b border-card-border text-[11px] font-mono uppercase text-text-muted tracking-wider">
<th className="py-2.5 px-4 font-semibold">Voucher No.</th>
<th className="py-2.5 px-4 font-semibold">Date</th>
<th className="py-2.5 px-4 font-semibold">Expense Category</th>
<th className="py-2.5 px-4 font-semibold">Payee Counterparty</th>
<th className="py-2.5 px-4 font-semibold">Account</th>
<th className="py-2.5 px-4 font-semibold text-right">Amount INR</th>
<th className="py-2.5 px-4 font-semibold">Description</th>
</tr>
</thead>
<tbody className="divide-y divide-card-border">
{expenses.map((exp) => (
<tr key={exp.voucher_id} className="hover:bg-surface/50 transition">
<td className="py-3 px-4 font-mono font-bold text-text-primary">{exp.voucher_number}</td>
<td className="py-3 px-4 font-mono text-[11px] text-text-muted">{exp.expense_date}</td>
<td className="py-3 px-4 font-semibold">{exp.expense_category}</td>
<td className="py-3 px-4">{exp.payee_name}</td>
<td className="py-3 px-4 font-mono text-[11px] text-sidebar-surface">{exp.account_code}</td>
<td className="py-3 px-4 text-right font-mono font-bold text-red-700">
₹{exp.amount_inr.toLocaleString('en-IN')}
</td>
<td className="py-3 px-4 text-[11px] text-text-muted max-w-xs truncate">{exp.description}</td>
</tr>
))}
</tbody>
</table>
</div>
</Card>
)}
{/* Modal 1: Post Customer Payment Receipt */}
{isReceiptModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div className="bg-card-surface border border-card-border rounded-lg max-w-md w-full p-6 shadow-xl space-y-4">
<div className="flex items-center justify-between border-b border-card-border pb-3">
<h3 className="text-base font-bold text-text-primary flex items-center gap-2">
<CreditCard className="w-4 h-4 text-sidebar-surface" />
Post Customer Payment Receipt
</h3>
<button onClick={() => setIsReceiptModalOpen(false)} className="text-text-muted hover:text-text-primary">&times;</button>
</div>
<form onSubmit={handlePostReceipt} className="space-y-3 text-xs">
<div>
<label className="block font-medium text-text-muted mb-1">Customer Counterparty *</label>
<select
value={recCustomerId}
onChange={(e) => setRecCustomerId(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded bg-surface text-text-primary font-semibold"
>
{agingRows.map(c => (
<option key={c.customer_id} value={c.customer_id}>{c.customer_name}</option>
))}
</select>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block font-medium text-text-muted mb-1">Receipt Amount INR *</label>
<input
type="number"
step="1.0"
required
value={recAmount}
onChange={(e) => setRecAmount(parseFloat(e.target.value) || 0)}
className="w-full px-3 py-2 border border-card-border rounded font-mono font-bold bg-surface text-text-primary"
/>
</div>
<div>
<label className="block font-medium text-text-muted mb-1">Instrument *</label>
<select
value={recInstrument}
onChange={(e) => setRecInstrument(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded bg-surface text-text-primary"
>
<option value="NEFT">NEFT / RTGS</option>
<option value="IMPS">IMPS Instant</option>
<option value="CHEQUE">Bank Cheque</option>
<option value="UPI">UPI Mandate</option>
</select>
</div>
</div>
<div>
<label className="block font-medium text-text-muted mb-1">Bank Reference / UTR / Cheque No *</label>
<input
type="text"
required
value={recReference}
onChange={(e) => setRecReference(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded font-mono bg-surface text-text-primary"
/>
</div>
<div className="flex justify-end space-x-2 pt-3 border-t border-card-border">
<Button type="button" variant="outline" size="sm" onClick={() => setIsReceiptModalOpen(false)}>
Cancel
</Button>
<Button type="submit" variant="primary" size="sm">
Post Receipt
</Button>
</div>
</form>
</div>
</div>
)}
{/* Modal 2: Partner Credit Breach Override */}
{isOverrideModalOpen && selectedCustomer && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div className="bg-card-surface border border-card-border rounded-lg max-w-md w-full p-6 shadow-xl space-y-4">
<div className="flex items-center justify-between border-b border-card-border pb-3">
<h3 className="text-base font-bold text-text-primary flex items-center gap-2">
<Unlock className="w-4 h-4 text-sidebar-surface" />
Partner Electronic Override: {selectedCustomer.customer_name}
</h3>
<button onClick={() => setIsOverrideModalOpen(false)} className="text-text-muted hover:text-text-primary">&times;</button>
</div>
<form onSubmit={handlePartnerOverride} className="space-y-3 text-xs">
<div className="bg-red-50 border border-red-200 p-3 rounded text-red-900 font-mono text-[11px] space-y-1">
<div className="font-bold">CREDIT BREACH WARNING (&gt;100%):</div>
<div>Credit Limit: ₹{selectedCustomer.credit_limit_inr.toLocaleString('en-IN')}</div>
<div>Outstanding: ₹{selectedCustomer.total_outstanding_inr.toLocaleString('en-IN')}</div>
<div>Exposure Ratio: {selectedCustomer.exposure_pct.toFixed(1)}%</div>
</div>
<div>
<label className="block font-medium text-text-muted mb-1">Partner Justification & Audit Reason *</label>
<textarea
rows={3}
required
value={overrideReason}
onChange={(e) => setOverrideReason(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded bg-surface text-text-primary"
/>
</div>
<div className="flex justify-end space-x-2 pt-3 border-t border-card-border">
<Button type="button" variant="outline" size="sm" onClick={() => setIsOverrideModalOpen(false)}>
Cancel
</Button>
<Button type="submit" variant="primary" size="sm">
Authorize Partner Override
</Button>
</div>
</form>
</div>
</div>
)}
{/* Modal 3: Supplier Disbursement */}
{isDisbursementModalOpen && selectedPayable && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div className="bg-card-surface border border-card-border rounded-lg max-w-md w-full p-6 shadow-xl space-y-4">
<div className="flex items-center justify-between border-b border-card-border pb-3">
<h3 className="text-base font-bold text-text-primary flex items-center gap-2">
<DollarSign className="w-4 h-4 text-sidebar-surface" />
Disburse Supplier Payment
</h3>
<button onClick={() => setIsDisbursementModalOpen(false)} className="text-text-muted hover:text-text-primary">&times;</button>
</div>
<form onSubmit={handlePostDisbursement} className="space-y-3 text-xs">
<div className="bg-surface p-3 rounded font-mono text-[11px] space-y-1">
<div>Supplier: {selectedPayable.supplier_name}</div>
<div>Invoice: {selectedPayable.invoice_number}</div>
<div>Outstanding: ₹{selectedPayable.outstanding_balance_inr.toLocaleString('en-IN')}</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block font-medium text-text-muted mb-1">Disbursement INR *</label>
<input
type="number"
step="1.0"
required
value={disbAmount}
onChange={(e) => setDisbAmount(parseFloat(e.target.value) || 0)}
className="w-full px-3 py-2 border border-card-border rounded font-mono font-bold bg-surface text-text-primary"
/>
</div>
<div>
<label className="block font-medium text-text-muted mb-1">Debit Bank Account *</label>
<select
value={disbAccount}
onChange={(e) => setDisbAccount(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded font-mono bg-surface text-text-primary"
>
<option value="BANK-HDFC-MAIN">HDFC Bank Current A/c (...8901)</option>
<option value="BANK-SBI-MANDI">SBI Mandi Branch A/c (...4421)</option>
</select>
</div>
</div>
<div>
<label className="block font-medium text-text-muted mb-1">Bank UTR Reference *</label>
<input
type="text"
required
value={disbUtr}
onChange={(e) => setDisbUtr(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded font-mono bg-surface text-text-primary"
/>
</div>
<div className="flex justify-end space-x-2 pt-3 border-t border-card-border">
<Button type="button" variant="outline" size="sm" onClick={() => setIsDisbursementModalOpen(false)}>
Cancel
</Button>
<Button type="submit" variant="primary" size="sm">
Commit Disbursement
</Button>
</div>
</form>
</div>
</div>
)}
{/* Modal 4: Post Mandi Operating Expense */}
{isExpenseModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div className="bg-card-surface border border-card-border rounded-lg max-w-md w-full p-6 shadow-xl space-y-4">
<div className="flex items-center justify-between border-b border-card-border pb-3">
<h3 className="text-base font-bold text-text-primary flex items-center gap-2">
<Receipt className="w-4 h-4 text-sidebar-surface" />
Post Mandi Operating Expense Voucher
</h3>
<button onClick={() => setIsExpenseModalOpen(false)} className="text-text-muted hover:text-text-primary">&times;</button>
</div>
<form onSubmit={handlePostExpense} className="space-y-3 text-xs">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block font-medium text-text-muted mb-1">Expense Category *</label>
<select
value={expCategory}
onChange={(e) => setExpCategory(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded bg-surface text-text-primary font-semibold"
>
<option value="HAMALI_LABOUR">Hamali & Stacking Labour</option>
<option value="MANDI_TAX">Mandi Board Cess / Fees</option>
<option value="WEIGHBRIDGE_FEES">Weighbridge Calibration</option>
<option value="ELECTRICITY_UTILITY">Power & Diesel Genset</option>
<option value="GODOWN_RENT">Godown Lease Rental</option>
</select>
</div>
<div>
<label className="block font-medium text-text-muted mb-1">Voucher Amount INR *</label>
<input
type="number"
step="1.0"
required
value={expAmount}
onChange={(e) => setExpAmount(parseFloat(e.target.value) || 0)}
className="w-full px-3 py-2 border border-card-border rounded font-mono font-bold bg-surface text-text-primary"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block font-medium text-text-muted mb-1">Payee Name *</label>
<input
type="text"
required
value={expPayee}
onChange={(e) => setExpPayee(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded bg-surface text-text-primary"
/>
</div>
<div>
<label className="block font-medium text-text-muted mb-1">Credit Account *</label>
<select
value={expAccount}
onChange={(e) => setExpAccount(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded font-mono bg-surface text-text-primary"
>
<option value="CASH-OFFICE">Cash on Hand (Mandi Office)</option>
<option value="BANK-HDFC-MAIN">HDFC Current A/c</option>
<option value="BANK-SBI-MANDI">SBI Mandi Branch A/c</option>
</select>
</div>
</div>
<div>
<label className="block font-medium text-text-muted mb-1">Detailed Description *</label>
<textarea
rows={2}
required
value={expRemarks}
onChange={(e) => setExpRemarks(e.target.value)}
className="w-full px-3 py-2 border border-card-border rounded bg-surface text-text-primary"
/>
</div>
<div className="flex justify-end space-x-2 pt-3 border-t border-card-border">
<Button type="button" variant="outline" size="sm" onClick={() => setIsExpenseModalOpen(false)}>
Cancel
</Button>
<Button type="submit" variant="primary" size="sm">
Post Voucher
</Button>
</div>
</form>
</div>
</div>
)}
</div>
);
};