Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | import { Injectable, BadRequestException } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { StockLedgerEntry, StockBalance } from '../schemas/ledger.schema'; import { ConfigurationService } from '../../configuration/services/configuration.service'; import { EventBusService } from '../../../../platform/events/event-bus.service'; @Injectable() export class LedgerService { constructor( @InjectModel(StockLedgerEntry.name) private readonly ledgerModel: Model<StockLedgerEntry>, @InjectModel(StockBalance.name) private readonly balanceModel: Model<StockBalance>, private readonly configService: ConfigurationService, private readonly eventBus: EventBusService ) {} async postLedgerEntry(tenantId: string, data: any, userId: string): Promise<StockLedgerEntry> { // 1. Idempotency Check using unique correlationId const existing = await this.ledgerModel.findOne({ tenantId, correlationId: data.correlationId }).exec(); if (existing) { return existing; // Already posted } // 2. Fetch inventory configuration const config = await this.configService.getConfiguration(tenantId); // 3. Verify stock availability if negative stock is not allowed if (!config.negativeStockAllowed && data.quantityChange < 0) { const balance = await this.balanceModel.findOne({ tenantId, itemCode: data.itemCode, warehouseId: data.warehouseId, locationId: data.locationId || null, batchNumber: data.batchNumber || null, serialNumber: data.serialNumber || null, }).exec(); const currentQty = balance ? balance.quantityAvailable : 0; if (currentQty + data.quantityChange < 0) { throw new BadRequestException( `Insufficient stock available for item ${data.itemCode} in warehouse ${data.warehouseId}. Current: ${currentQty}, Requested change: ${data.quantityChange}` ); } } // 4. Create Ledger Entry const entry = await this.ledgerModel.create({ ...data, tenantId, postedBy: userId, postingDate: new Date(), }); // 5. Atomic Stock Balance update with optimistic locking loop let updated = false; let attempts = 0; const qtyChange = data.quantityChange; while (!updated && attempts < 10) { const balance = await this.balanceModel.findOne({ tenantId, itemCode: data.itemCode, warehouseId: data.warehouseId, locationId: data.locationId || null, batchNumber: data.batchNumber || null, serialNumber: data.serialNumber || null, }).exec(); if (!balance) { if (!config.negativeStockAllowed && qtyChange < 0) { throw new BadRequestException(`Insufficient stock for item ${data.itemCode}`); } try { await this.balanceModel.create({ tenantId, itemCode: data.itemCode, warehouseId: data.warehouseId, locationId: data.locationId || null, batchNumber: data.batchNumber || null, serialNumber: data.serialNumber || null, quantityOnHand: qtyChange, quantityAvailable: qtyChange, movingAverageUnitCost: data.unitCost || 0, totalValue: qtyChange * (data.unitCost || 0), version: 1, }); updated = true; } catch (err) { // Fall through to retry on duplicate key insertion } } else { const newOnHand = balance.quantityOnHand + qtyChange; const newAvailable = balance.quantityAvailable + qtyChange; if (!config.negativeStockAllowed && newAvailable < 0) { throw new BadRequestException(`Insufficient stock for item ${data.itemCode}`); } const res = await this.balanceModel.updateOne( { _id: balance._id, version: balance.version }, { $inc: { quantityOnHand: qtyChange, quantityAvailable: qtyChange }, $set: { version: balance.version + 1, movingAverageUnitCost: data.unitCost || balance.movingAverageUnitCost, totalValue: newOnHand * (data.unitCost || balance.movingAverageUnitCost), }, } ).exec(); if (res.modifiedCount > 0) { updated = true; } } attempts++; } if (!updated) { throw new BadRequestException('Failed to update stock balance due to high concurrent requests write conflicts'); } // Publish stock posted event await this.eventBus.publish('inventory.stock-posted.v1', { tenantId, itemCode: data.itemCode, warehouseId: data.warehouseId, quantityChange: qtyChange, correlationId: data.correlationId, }, tenantId); return entry; } async getBalances(tenantId: string, query: any = {}): Promise<StockBalance[]> { const filter: any = { tenantId }; if (query.itemCode) filter.itemCode = query.itemCode; if (query.warehouseId) filter.warehouseId = query.warehouseId; return this.balanceModel.find(filter).exec(); } async getLedgerEntries(tenantId: string, itemCode?: string): Promise<StockLedgerEntry[]> { const filter: any = { tenantId }; if (itemCode) filter.itemCode = itemCode; return this.ledgerModel.find(filter).sort({ postingDate: -1 }).exec(); } } |