Added inward and stock ledger stuff

This commit is contained in:
Prashant Shendre 2026-10-17 12:29:16 +05:30
parent 5ec1106174
commit 95b5aeb52f
5 changed files with 115 additions and 21 deletions

View File

@ -109,7 +109,16 @@ class InventoryController:
continue
if commodity_id and e.get("commodity_id") != commodity_id:
continue
filtered.append(e)
item = dict(e)
item.setdefault("entry_id", item.get("id"))
item.setdefault("entry_type", item.get("transaction_type"))
item.setdefault("bag_count", item.get("bags", 0))
item.setdefault("running_balance_mt", item.get("closing_mt", 0.0))
if item.get("warehouse_id") == "godown-demo-indore":
item.setdefault("warehouse_name", "Central Warehouse Indore")
if "c0a80123-demo" in str(item.get("commodity_id")):
item.setdefault("commodity_name", "Soybean Yellow FAQ")
filtered.append(item)
return {"status_code": 200, "count": len(filtered), "entries": filtered}

View File

@ -104,7 +104,16 @@ class ReceivingController:
# Validate Sauda exists and is open
sauda = self.store.get("procurement_sauda", tenant_id, sauda_id)
if not sauda:
return {"error": "INVALID_SAUDA", "message": "Purchase sauda not found in tenant", "status_code": 404}
matches = self.store.query(
"procurement_sauda",
tenant_id,
lambda s: s.get("sauda_number") == sauda_id or s.get("id") == sauda_id
)
if matches:
sauda = matches[0]
sauda_id = sauda["id"]
else:
return {"error": "INVALID_SAUDA", "message": "Purchase sauda not found in tenant", "status_code": 404}
if sauda.get("status") in {"FULFILLED", "CANCELLED"}:
return {
"error": "SAUDA_CLOSED",
@ -117,7 +126,8 @@ class ReceivingController:
active_entries = self.store.query(
"inward_gate_entries",
tenant_id,
lambda e: (e.get("vehicle_number") == clean_vehicle or e.get("vehicle_number") == vehicle_number) and e.get("status") != "GATE_OUT"
lambda e: (e.get("vehicle_number", "").replace("-", "").replace(" ", "").upper() == clean_vehicle)
and e.get("status") not in {"GATE_OUT", "GRN_ISSUED"}
)
if active_entries:
return {
@ -180,10 +190,17 @@ class ReceivingController:
tenant_id = auth_res["tenant_id"]
records = self.store.list("inward_gate_entries", tenant_id)
enriched = []
for r in records:
item = dict(r)
item.setdefault("gate_pass_id", item.get("id"))
item.setdefault("pass_number", item.get("gate_pass_number"))
item.setdefault("bag_count", item.get("supplier_dispatch_bags", 0))
enriched.append(item)
return {
"success": True,
"count": len(records),
"gate_entries": records,
"count": len(enriched),
"gate_entries": enriched,
"status_code": 200
}

View File

@ -23,6 +23,7 @@ from backend.app.models.market import MarketObservation
from backend.app.models.procurement import ProcurementSauda
from backend.app.models.receiving import InwardGateEntry, WeighbridgeSlip, GoodsReceiptNote
from backend.app.models.quality import InventoryLot, QualityInspection
from backend.app.models.inventory import StockLedgerEntry
from backend.app.models.sales import CustomerSalesOrder, SalesOrderAllocation
from backend.app.models.logistics import TransportVehicle, OutboundDispatch, OutwardWeighment, DispatchBilty
from backend.app.models.finance import PartySubLedgerEntry, SupplierPayable, MandiExpenseVoucher
@ -47,6 +48,9 @@ CASCADE_PURGE_ORDER = [
("outbound_dispatches", "Outbound Dispatch Consignments"),
("sales_order_allocations", "Sales Lot Allocations"),
("customer_sales_orders", "Customer Sales Contracts"),
("stock_ledger_entries", "Double-Entry Stock Ledger"),
("stock_adjustments", "Warehouse Stock Adjustments"),
("inter_godown_transfers", "Inter-Godown Transfers"),
("quality_inspections", "Laboratory Quality Assays"),
("inventory_lots", "Warehouse Inventory Lots"),
("goods_receipt_notes", "Goods Receipt Notes (GRN)"),
@ -559,8 +563,19 @@ def seed_demo_dataset(store: Any, tenant_id: str = DEFAULT_TENANT_ID) -> Dict[st
supplier_dispatch_bags=500,
entry_id="gate-entry-demo-001"
)
gate_entry.transition_status("WEIGHED_TARE")
store.insert("inward_gate_entries", tenant_id, gate_entry.to_dict())
gate_entry.transition_status("GRN_ISSUED")
ge_dict = gate_entry.to_dict()
ge_dict.update({
"gate_pass_id": gate_entry.id,
"pass_number": gate_entry.gate_pass_number,
"gross_weight_mt": 35.0,
"tare_weight_mt": 10.0,
"net_weight_mt": 25.0,
"bag_count": 500,
"lot_id": "LOT-SOY-2026-001",
"grn_id": "GRN-2026-001",
})
store.insert("inward_gate_entries", tenant_id, ge_dict)
wb_slip = WeighbridgeSlip(
tenant_id=tenant_id,
@ -695,6 +710,39 @@ def seed_demo_dataset(store: Any, tenant_id: str = DEFAULT_TENANT_ID) -> Dict[st
)
store.insert("dispatch_bilties", tenant_id, bilty.to_dict())
# 8b. Double-Entry Stock Ledger Movements (GRN Inward + Bilty Outward)
sle_inward = StockLedgerEntry(
tenant_id=tenant_id,
warehouse_id="godown-demo-indore",
commodity_id="c0a80123-demo-0000-0000-000000000001",
variety="Yellow FAQ",
grade="FAQ",
transaction_type="INWARD",
reference_id=grn.grn_number,
opening_mt=Decimal("3125.375"),
opening_bags=62500,
quantity_mt=Decimal("24.625"),
bags=500,
entry_id="sle-demo-inward-001"
)
store.insert("stock_ledger_entries", tenant_id, sle_inward.to_dict())
sle_outward = StockLedgerEntry(
tenant_id=tenant_id,
warehouse_id="godown-demo-indore",
commodity_id="c0a80123-demo-0000-0000-000000000001",
variety="Yellow FAQ",
grade="FAQ",
transaction_type="OUTWARD",
reference_id=bilty.bilty_number,
opening_mt=Decimal("3150.000"),
opening_bags=63000,
quantity_mt=Decimal("24.000"),
bags=480,
entry_id="sle-demo-outward-001"
)
store.insert("stock_ledger_entries", tenant_id, sle_outward.to_dict())
# 9. Subledgers, Payables, Cess Voucher
customer_invoice = PartySubLedgerEntry(
tenant_id=tenant_id,
@ -795,6 +843,7 @@ def seed_demo_dataset(store: Any, tenant_id: str = DEFAULT_TENANT_ID) -> Dict[st
"weighbridge_slips": 1,
"goods_receipt_notes": 1,
"inventory_lots": 1,
"stock_ledger_entries": 2,
"quality_inspections": 1,
"sales_orders": 1,
"dispatches": 1,

View File

@ -147,9 +147,22 @@ export const StockLedgerView: React.FC = () => {
}
// 2. Fetch Ledger
const ledRes = await apiClient.get<{ entries: StockEntry[] }>('/api/v1/inventory/ledger');
const ledRes = await apiClient.get<{ entries: any[] }>('/api/v1/inventory/ledger');
if (ledRes && ledRes.entries && ledRes.entries.length > 0) {
setEntries(ledRes.entries);
const normalized: StockEntry[] = ledRes.entries.map((e: any) => ({
entry_id: e.entry_id || e.id || `LED-${Math.random().toString(36).substring(2, 7)}`,
warehouse_id: e.warehouse_id || '',
warehouse_name: e.warehouse_name || (e.warehouse_id === 'godown-demo-indore' ? 'Central Warehouse Indore' : e.warehouse_id),
commodity_id: e.commodity_id || '',
commodity_name: e.commodity_name || (String(e.commodity_id).includes('demo') ? 'Soybean Yellow FAQ' : e.commodity_id),
entry_type: (e.entry_type || e.transaction_type || 'INWARD') as any,
quantity_mt: Number(e.quantity_mt || 0),
bag_count: Number(e.bag_count ?? e.bags ?? 0),
running_balance_mt: Number(e.running_balance_mt ?? e.closing_mt ?? 0),
reference_id: e.reference_id || '',
created_at: e.created_at || new Date().toISOString(),
}));
setEntries(normalized);
} else {
setEntries([
{
@ -390,24 +403,24 @@ export const StockLedgerView: React.FC = () => {
</thead>
<tbody className="divide-y divide-card-border">
{entries.map((e) => (
<tr key={e.entry_id} className="hover:bg-surface/50 transition">
<td className="py-3 px-4 font-mono font-medium text-text-primary">{e.entry_id}</td>
<tr key={e.entry_id || (e as any).id} className="hover:bg-surface/50 transition">
<td className="py-3 px-4 font-mono font-medium text-text-primary">{e.entry_id || (e as any).id}</td>
<td className="py-3 px-4 font-semibold text-text-primary">{e.warehouse_name || e.warehouse_id}</td>
<td className="py-3 px-4">{e.commodity_name || e.commodity_id}</td>
<td className="py-3 px-4 font-mono text-[11px]">
<span className={`inline-flex items-center gap-1 font-semibold ${
e.entry_type === 'INWARD' || e.entry_type === 'TRANSFER_IN' ? 'text-status-normal-text' : 'text-amber-800'
(e.entry_type || '').includes('IN') ? 'text-status-normal-text' : 'text-amber-800'
}`}>
{e.entry_type === 'INWARD' ? <TrendingUp className="w-3 h-3" /> : <TrendingDown className="w-3 h-3" />}
{e.entry_type}
{(e.entry_type || '').includes('IN') ? <TrendingUp className="w-3 h-3" /> : <TrendingDown className="w-3 h-3" />}
{e.entry_type || 'ENTRY'}
</span>
</td>
<td className="py-3 px-4 text-right font-mono font-bold text-text-primary">
{e.entry_type.includes('OUT') ? '-' : '+'}{Number(e.quantity_mt).toFixed(3)} MT
{(e.entry_type || '').includes('OUT') ? '-' : '+'}{Number(e.quantity_mt || 0).toFixed(3)} MT
</td>
<td className="py-3 px-4 text-right font-mono">{e.bag_count} Bags</td>
<td className="py-3 px-4 text-right font-mono">{e.bag_count || 0} Bags</td>
<td className="py-3 px-4 text-right font-mono font-bold text-sidebar-surface">
{Number(e.running_balance_mt).toFixed(3)} MT
{Number(e.running_balance_mt || 0).toFixed(3)} MT
</td>
<td className="py-3 px-4 font-mono text-[11px] text-text-muted">{e.reference_id}</td>
</tr>

View File

@ -89,9 +89,15 @@ export const GateEntryView: React.FC = () => {
const fetchGatePasses = useCallback(async () => {
setIsLoading(true);
try {
const response = await apiClient.get<{ gate_entries: GatePassRecord[] }>('/api/v1/receiving/gate-entries');
const response = await apiClient.get<{ gate_entries: any[] }>('/api/v1/receiving/gate-entries');
if (response && response.gate_entries) {
setGatePasses(response.gate_entries);
const normalized: GatePassRecord[] = (response.gate_entries || []).map((p: any) => ({
...p,
gate_pass_id: p.gate_pass_id || p.id || '',
pass_number: p.pass_number || p.gate_pass_number || (p.gate_pass_id || p.id || '').slice(0, 8),
bag_count: p.bag_count ?? p.supplier_dispatch_bags ?? 0,
}));
setGatePasses(normalized);
} else {
setGatePasses([]);
}
@ -340,9 +346,9 @@ export const GateEntryView: React.FC = () => {
</tr>
) : (
filteredPasses.map((p) => (
<tr key={p.gate_pass_id} className="hover:bg-surface/50 transition">
<tr key={p.gate_pass_id || (p as any).id || p.pass_number} className="hover:bg-surface/50 transition">
<td className="py-3 px-4 font-mono font-medium text-text-primary">
{p.pass_number || p.gate_pass_id.slice(0, 8)}
{p.pass_number || (p as any).gate_pass_number || (p.gate_pass_id || (p as any).id || '').slice(0, 8)}
{p.lot_id && (
<div className="mt-1">
<span className="inline-flex items-center gap-1 font-mono text-[10px] bg-sidebar-surface text-accent-ochre px-1.5 py-0.2 rounded font-semibold">