# Arsitektur Backend Sistem Inventory Walet

## 1. Tujuan
Dokumen ini menjelaskan rancangan arsitektur backend untuk sistem inventory sarang burung walet berbasis lot, sorting, partial allocation, costing, dan traceability.

## 2. Prinsip Arsitektur
- modular per domain bisnis
- transaction-safe untuk operasi stok
- audit trail wajib untuk semua mutasi lot
- source of truth ada pada lot dan movement ledger
- costing dihitung dari allocation aktual
- siap dikembangkan bertahap dari MVP ke skala lebih besar

## 3. Modul Backend Utama
### A. Auth & Access Control
Tanggung jawab:
- login
- session/jwt
- role permission
- route guard
- audit identity

### B. Master Data Module
Tanggung jawab:
- supplier
- customer
- item types
- item grades
- warehouses
- locations
- units
- adjustment reasons

### C. Purchasing Module
Tanggung jawab:
- purchase header/lines
- purchase workflow
- histori harga beli

### D. Receiving Module
Tanggung jawab:
- receipt header/lines
- qty accepted/rejected
- create lot awal
- generate label metadata

### E. Inventory Lot Module
Tanggung jawab:
- detail lot
- stock summary
- lot status
- hold/release
- transfer
- location update

### F. Sorting & Regrade Module
Tanggung jawab:
- sorting session
- child lot creation
- shrinkage recording
- regrade logic

### G. Sales Module
Tanggung jawab:
- sales header/lines
- sales workflow
- picking confirmation
- finalize sales

### H. Allocation Engine Module
Tanggung jawab:
- manual allocation validation
- FIFO suggestion
- future FEFO/hybrid strategy
- costing by allocation

### I. Inventory Movement Ledger Module
Tanggung jawab:
- record all inventory movements
- balance validation
- immutable movement history

### J. Adjustment & Return Module
Tanggung jawab:
- stock adjustment
- shrinkage
- purchase returns
- sales returns
- damage/reject flows

### K. Traceability Module
Tanggung jawab:
- backward trace
- forward trace
- lot lineage
- trace report builder

### L. Reporting Module
Tanggung jawab:
- stock summary report
- sales report
- purchase report
- margin report
- shrinkage report
- supplier quality report

### M. Barcode / QR Module
Tanggung jawab:
- label generation
- reprint tracking
- lookup by scanned value

## 4. Struktur Layer yang Disarankan
```text
src/
  modules/
  common/
  infrastructure/
  database/
  jobs/
```

### Per module internal
```text
modules/
  purchases/
    controllers/
    services/
    repositories/
    dtos/
    entities/
    validators/
```

## 5. Service Boundaries Penting
### PurchaseService
- createPurchase
- updatePurchase
- submitPurchase
- cancelPurchase

### ReceiptService
- createReceipt
- finalizeReceipt
- generateLotsFromReceipt

### LotService
- getLotDetail
- holdLot
- releaseLot
- transferLot
- getStockSummary

### SortingService
- createSortingSession
- validateSortingBalance
- createChildLots

### RegradeService
- regradeLot
- splitLotForRegrade

### SalesService
- createSales
- updateSales
- finalizeSales
- confirmPicking

### AllocationService
- autoAllocateFIFO
- validateManualAllocation
- calculateAllocationCost

### MovementService
- recordReceiptMovement
- recordSortingMovement
- recordSalesMovement
- recordAdjustmentMovement
- recordTransferMovement

### TraceService
- traceBySales
- traceByLot
- buildLotLineage

## 6. Transaksi Database yang Wajib Atomic
Operasi berikut wajib berada dalam database transaction:
- finalize receipt + create lots + create movement
- sorting submit + child lot creation + source lot reduction + movement insert
- regrade + lot split + movement insert
- sales allocation submit + costing update
- picking confirm + lot quantity reduction + movement insert
- stock adjustment + balance update + movement insert
- returns + lot mutation + movement insert

Kalau tidak atomic, stok akan gampang kacau.

## 7. Source of Truth Rules
- inventory_lots menyimpan posisi qty aktif saat ini
- inventory_movements menyimpan histori mutasi yang tidak boleh hilang
- sales_allocations menyimpan asal costing penjualan
- sorting_results dan parent_lot relation menyimpan lineage hasil sortasi

## 8. Validasi Domain Penting
### Receipt
- qty accepted + qty rejected <= qty received

### Sorting
- total result + shrinkage <= input qty

### Allocation
- total allocation = qty sales line
- lot status harus ACTIVE
- available qty harus cukup

### Picking
- qty picked tidak boleh melebihi qty allocated tanpa override rule

### Adjustment
- qty_after tidak boleh negatif

### Regrade
- qty regrade tidak boleh melebihi available qty lot sumber

## 9. Event / Hook Internal yang Disarankan
Walau MVP belum perlu event bus besar, internal hooks bagus untuk:
- afterReceiptFinalized
- afterSortingCompleted
- afterSalesAllocated
- afterPickingConfirmed
- afterAdjustmentCreated

Hook bisa dipakai untuk:
- recalculation summary
- audit log tambahan
- notification
- async report cache refresh

## 10. Caching Strategy
- stock summary boleh dicache ringan
- lot detail sebaiknya fresh atau cache sangat pendek
- reports boleh async/precomputed bila sudah besar
- traceability query perlu index bagus, jangan terlalu mengandalkan cache dulu

## 11. Database Index Priorities
Index penting:
- inventory_lots(item_type_id, item_grade_id, warehouse_id)
- inventory_lots(status)
- sales_allocations(sales_line_id)
- sales_allocations(inventory_lot_id)
- inventory_movements(inventory_lot_id, movement_date)
- purchases(supplier_id, purchase_date)
- sales(customer_id, sales_date)

## 12. Background Jobs yang Bisa Ditambahkan
- nightly stock summary refresh
- report materialization
- aging recalculation
- QR label batch generation
- alert stok menipis

## 13. Security & Audit
- semua endpoint protected
- role permission check di service layer, bukan UI saja
- audit log simpan user, waktu, aksi, reference
- label reprint dan stock adjustment harus ekstra jelas auditnya

## 14. Rekomendasi Stack Backend
Pilihan aman:
- Node.js + NestJS / Express terstruktur
- PostgreSQL
- Prisma / TypeORM / Knex sesuai preferensi
- Redis opsional untuk cache dan queue

Kalau mau lebih enterprise, NestJS cocok karena modular dan rapi.

## 15. Kesimpulan
Backend sistem walet ini harus dibangun dengan fokus utama pada integritas transaksi stok. Modul paling kritis adalah inventory lot, allocation engine, movement ledger, sorting/regrade, dan traceability. Kalau lima bagian ini kuat, sisanya relatif mengikuti.