lambda-erp 1.4.6__tar.gz → 1.4.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/PKG-INFO +1 -1
  2. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/chat.py +28 -2
  3. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/main.py +2 -0
  4. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/pdf_profiles.py +3 -0
  5. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/masters.py +37 -0
  6. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/reports.py +90 -14
  7. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/services.py +7 -1
  8. lambda_erp-1.4.8/api/stock_actions.py +79 -0
  9. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/frontend/src/api/client.ts +6 -0
  10. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/pos_invoice.py +3 -0
  11. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/purchase_invoice.py +1 -0
  12. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/sales_invoice.py +3 -0
  13. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/database.py +84 -0
  14. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/master_integrity.py +2 -0
  15. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/model.py +8 -0
  16. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/stock/delivery_note.py +40 -11
  17. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/stock/purchase_receipt.py +2 -0
  18. lambda_erp-1.4.8/lambda_erp/stock/reservation.py +545 -0
  19. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/stock/stock_entry.py +64 -3
  20. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/stock/stock_ledger.py +92 -23
  21. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/workflow.py +4 -0
  22. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/pyproject.toml +1 -1
  23. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/.gitignore +0 -0
  24. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/LICENSE +0 -0
  25. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/README.md +0 -0
  26. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/__init__.py +0 -0
  27. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/attachments.py +0 -0
  28. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/auth.py +0 -0
  29. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/bootstrap.py +0 -0
  30. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/chat_links.py +0 -0
  31. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/demo_limits.py +0 -0
  32. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/deps.py +0 -0
  33. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/erp_context.py +0 -0
  34. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/errors.py +0 -0
  35. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/list_values.py +0 -0
  36. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/llm_provider.py +0 -0
  37. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/mcp_oauth.py +0 -0
  38. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/mentions.py +0 -0
  39. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/menu_layout.py +0 -0
  40. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/oauth.py +0 -0
  41. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/pdf.py +0 -0
  42. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/pdf_contract.py +0 -0
  43. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/pdf_exports.py +0 -0
  44. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/pdf_fonts.py +0 -0
  45. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/pdf_pages.py +0 -0
  46. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/pdf_templates.py +0 -0
  47. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/providers.py +0 -0
  48. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/record_notes.py +0 -0
  49. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/remarks_md.py +0 -0
  50. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/__init__.py +0 -0
  51. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/accounting.py +0 -0
  52. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/actions.py +0 -0
  53. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/admin.py +0 -0
  54. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/analytics.py +0 -0
  55. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/availability.py +0 -0
  56. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/bank_reconciliation.py +0 -0
  57. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/bank_statements.py +0 -0
  58. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/chat_api.py +0 -0
  59. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/documents.py +0 -0
  60. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/mcp.py +0 -0
  61. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/pdf_templates.py +0 -0
  62. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/proposals.py +0 -0
  63. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/routers/setup.py +0 -0
  64. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/templates/_proposal_totals.html +0 -0
  65. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/templates/_record_base.html +0 -0
  66. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/templates/delivery_note.html +0 -0
  67. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/templates/document.html +0 -0
  68. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/templates/proposal.html +0 -0
  69. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/templates/record.html +0 -0
  70. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/templates/reservation.html +0 -0
  71. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/time_filters.py +0 -0
  72. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/tool_permissions.py +0 -0
  73. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/api/write_context.py +0 -0
  74. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/docs/agents/README.md +0 -0
  75. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/frontend/LICENSE +0 -0
  76. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/frontend/README.md +0 -0
  77. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/__init__.py +0 -0
  78. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/__init__.py +0 -0
  79. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/bank_account.py +0 -0
  80. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  81. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/bank_statement_import.py +0 -0
  82. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/bank_transaction.py +0 -0
  83. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/budget.py +0 -0
  84. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/camt.py +0 -0
  85. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  86. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/general_ledger.py +0 -0
  87. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/journal_entry.py +0 -0
  88. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/payment_entry.py +0 -0
  89. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/revaluation.py +0 -0
  90. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/settlement.py +0 -0
  91. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/__init__.py +0 -0
  92. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/engine.py +0 -0
  93. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/pack.py +0 -0
  94. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  95. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  96. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  97. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  98. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  99. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  100. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/profiles.py +0 -0
  101. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/setup/spine.py +0 -0
  102. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/accounting/subscription.py +0 -0
  103. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/assets/__init__.py +0 -0
  104. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/assets/asset.py +0 -0
  105. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/assets/lifecycle.py +0 -0
  106. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/assets/reservation.py +0 -0
  107. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/buying/__init__.py +0 -0
  108. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/buying/purchase_order.py +0 -0
  109. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/controllers/__init__.py +0 -0
  110. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/controllers/currency.py +0 -0
  111. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/controllers/defaults.py +0 -0
  112. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/controllers/item_price.py +0 -0
  113. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/controllers/item_prices.py +0 -0
  114. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/controllers/pricing_rule.py +0 -0
  115. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  116. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/exceptions.py +0 -0
  117. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/hooks.py +0 -0
  118. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/permissions.py +0 -0
  119. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/selling/__init__.py +0 -0
  120. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/selling/proposal.py +0 -0
  121. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/selling/quotation.py +0 -0
  122. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/selling/sales_order.py +0 -0
  123. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/simulation.py +0 -0
  124. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/stock/__init__.py +0 -0
  125. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/timestamps.py +0 -0
  126. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/utils.py +0 -0
  127. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/lambda_erp/validation.py +0 -0
  128. {lambda_erp-1.4.6 → lambda_erp-1.4.8}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.6
3
+ Version: 1.4.8
4
4
  Summary: Core ERP logic - accounting, sales, purchasing, inventory
5
5
  Author: TORUS INVESTMENTS AG
6
6
  License-Expression: Apache-2.0
@@ -878,8 +878,8 @@ TOOLS = [
878
878
  "parameters": {
879
879
  "type": "object",
880
880
  "properties": {
881
- "report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "batch-stock", "batch-movements", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
882
- "filters": {"type": "object", "description": "Optional filters: company, account, from_date, to_date, item_code, warehouse; for batch-stock also batch_no, item_prefix, expiring_before, include_empty; batch-movements requires batch_no. For trial-balance / profit-and-loss / balance-sheet you may also pass `presentation_currency` (e.g. \"EUR\") to view the report translated from the company's base currency at the period's closing rate — display only, the ledger stays in base currency.", "default": {}},
881
+ "report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "stock-availability", "stock-detail", "batch-stock", "batch-movements", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
882
+ "filters": {"type": "object", "description": "Optional filters: company, account, from_date, to_date, item_code, warehouse; for batch-stock also batch_no, item_prefix, expiring_before, include_empty; for stock-detail also location, batch_no, item_prefix, item_group, expiring_before, expiring_after, include_empty; batch-movements requires batch_no. For trial-balance / profit-and-loss / balance-sheet you may also pass `presentation_currency` (e.g. \"EUR\") to view the report translated from the company's base currency at the period's closing rate — display only, the ledger stays in base currency.", "default": {}},
883
883
  },
884
884
  "required": ["report_type"],
885
885
  },
@@ -1974,6 +1974,15 @@ def _handle_get_report(args):
1974
1974
  return _batch_stock(db, filters.get("item_code"), filters.get("warehouse"), filters.get("batch_no"),
1975
1975
  filters.get("item_prefix"), filters.get("expiring_before"),
1976
1976
  bool(filters.get("include_empty")))
1977
+ elif report_type == "stock-availability":
1978
+ from api.routers.reports import _stock_availability
1979
+ return _stock_availability(db, filters.get("item_code"), filters.get("warehouse"), filters.get("item_prefix"))
1980
+ elif report_type == "stock-detail":
1981
+ from api.routers.reports import _stock_detail
1982
+ return _stock_detail(db, filters.get("item_code"), filters.get("warehouse"), filters.get("location"),
1983
+ filters.get("batch_no"), filters.get("item_prefix"), filters.get("item_group"),
1984
+ filters.get("expiring_before"), filters.get("expiring_after"),
1985
+ bool(filters.get("include_empty")))
1977
1986
  elif report_type == "batch-movements":
1978
1987
  from api.routers.reports import _batch_movements
1979
1988
  if not filters.get("batch_no"):
@@ -2909,6 +2918,21 @@ For a complete sales return (financial + stock): create and submit both a Credit
2909
2918
  - **Material Transfer:** Moves stock between warehouses. No GL impact.
2910
2919
  - **Batch Assignment:** Gives stock that has no batch (from before the item was batch-tracked) its batch, in place: row = item_code, qty, t_warehouse, batch_no (+ expiry_date for a new batch). No GL impact, no quantity or value change.
2911
2920
 
2921
+ ### Reservations, availability and picking (FEFO)
2922
+ - available = in stock − blocked (expired or blocked batches) − reserved. Check it with the stock-availability report before promising a delivery.
2923
+ - A **Stock Reservation** (doctype `stock-reservation`) sets stock aside: for a sales order line (use the `reserve_sales_order` action, or set `reserve_stock=1` on the Sales Order before submitting it), or free-standing with `remarks` saying what it is for. It is hard: a delivery, issue or transfer that would take reserved stock for someone else is refused with the orders it is reserved for. Deliveries against the order consume its reservation automatically; cancelling the order cancels it; set status Released to give stock back early.
2924
+ - Picking is first expired, first out. Converting a Sales Order to a Delivery Note already proposes batch and storage location per line that way (splitting a line over batches when needed). For anything else use the `suggest_picks` action; it is read-only.
2925
+ - A sale never ships an expired or blocked batch. If the item has a minimum shelf life (`min_shelf_life_days`) and the batch has less left, the line needs `shelf_life_exception` with the approved reason; do not write one unless the user gives it.
2926
+ - Expired or blocked stock can still be moved, returned to the supplier or written off with a Stock Entry.
2927
+
2928
+ ### Storage locations (places inside a warehouse)
2929
+ - A warehouse with `use_locations=1` has storage locations (master `storage-location`: warehouse + location label, e.g. "A12"). The same label may exist in several warehouses.
2930
+ - In such a warehouse every stock-moving line names its location: `location` on Delivery Note, Purchase Receipt and invoice lines (with update_stock=1); on Stock Entry lines `s_location` for the source side and `t_location` for the target side. Drafts may be saved without it; submit is refused. A warehouse without storage locations takes no location.
2931
+ - Stock is checked per location (and per batch within it). Find the location with the stock-detail report first; never guess one.
2932
+ - Moving stock between two locations of the SAME warehouse is a Material Transfer with s_warehouse = t_warehouse and different s_location / t_location (no GL, no value change). Leave s_location empty only to put away stock that has no location yet.
2933
+ - Moving EVERYTHING in one location: use the `prepare_location_move` action (warehouse, from_location, to_location); it creates a draft Stock Entry to review and submit.
2934
+ - A disabled location takes no new stock but can still be emptied.
2935
+
2912
2936
  ### Batches (lot numbers)
2913
2937
  - An item with `has_batch_no=1` is batch-tracked; `has_expiry_date=1` additionally requires an expiry date on each batch. Switch these on the Item master.
2914
2938
  - Every stock-moving line of a tracked item needs `batch_no` (Stock Entry, Delivery Note, Purchase Receipt, and invoices with update_stock=1). One batch per line: a quantity from two batches is two lines. Drafts may be saved without it; submit is refused until every such line has one.
@@ -2972,6 +2996,8 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
2972
2996
  - **ar-aging** — Outstanding receivables bucketed by overdue days (Current, 1-30, 31-60, 61-90, 90+). Filters: company, as_of_date.
2973
2997
  - **ap-aging** — Outstanding payables bucketed by overdue days. Filters: company, as_of_date.
2974
2998
  - **stock-balance** — Inventory quantities and valuations. Filters: item_code, warehouse.
2999
+ - **stock-availability** — Per item × warehouse: physical_qty (in stock), blocked_qty (expired or blocked batches), reserved_qty (open Stock Reservations), available_qty (= physical − blocked − reserved), plus open_sales_order_qty (ordered by customers, not yet delivered) and on_purchase_order_qty (ordered from suppliers, not yet received). Filters: item_code, warehouse, item_prefix. Use this to answer "can we deliver X" and "is it already on order".
3000
+ - **stock-detail** — Where stock is, in one view: item, warehouse, storage location, batch, expiry date, quantity. Filters: item_code, warehouse, location, batch_no, item_prefix, item_group, expiring_before, expiring_after, include_empty. Use this for "what is in location B4", "where is item X", "what expires in the next 3 months in warehouse Y".
2975
3001
  - **batch-stock** — Quantity per item × warehouse × batch with the batch's expiry date (batch-tracked items only). Filters: item_code, warehouse, batch_no, item_prefix (item codes starting with…), expiring_before (date), include_empty. A batch label is NOT unique: the same label can exist on several items, so a batch_no-only lookup can return several items — show them all, never pick one.
2976
3002
  - **batch-movements** — Every stock movement of a batch with document, line and customer/supplier: where it came from and who received it (recalls). Filters: batch_no (required), item_code, warehouse.
2977
3003
  - **dashboard-summary** — KPI overview (revenue, receivables, payables, stock value).
@@ -62,6 +62,8 @@ async def lifespan(app: FastAPI):
62
62
  initialize_mentions()
63
63
  from api.record_notes import initialize_record_notes
64
64
  initialize_record_notes()
65
+ from api.stock_actions import initialize_stock_actions
66
+ initialize_stock_actions()
65
67
  from api.menu_layout import initialize_menu_layout
66
68
  initialize_menu_layout()
67
69
  from api.pdf_templates import initialize_pdf_templates
@@ -82,6 +82,9 @@ PROFILES.update({
82
82
  fields=('company', 'party_type', 'party', 'start_date', 'end_date', 'billing_interval', 'current_invoice_start', 'current_invoice_end'),
83
83
  required=('company', 'party_type', 'party', 'start_date', 'billing_interval'),
84
84
  tables=(PDFTable('plans', ('item_code', 'item_name', 'qty', 'rate'), ('item_code', 'qty', 'rate'), True),)),
85
+ 'Stock Reservation': PDFProfile('record', 'Stock reservation overview',
86
+ fields=('item_code', 'warehouse', 'reserved_qty', 'sales_order', 'customer', 'status', 'remarks', 'reserved_by', 'company'),
87
+ required=('item_code', 'warehouse', 'reserved_qty')),
85
88
  'Budget': PDFProfile('record', 'Budget overview',
86
89
  fields=('company', 'budget_against', 'cost_center', 'account', 'fiscal_year', 'budget_amount', 'action_if_exceeded'),
87
90
  required=('company', 'account', 'fiscal_year', 'budget_amount', 'action_if_exceeded'),
@@ -64,6 +64,10 @@ DELETE_REFERENCE_CHECKS = {
64
64
  ('SELECT 1 FROM "Stock Ledger Entry" s JOIN "Batch" b ON b.item_code = s.item_code '
65
65
  'AND b.batch_no = s.batch_no WHERE b.name = ? LIMIT 1', "stock ledger entry"),
66
66
  ],
67
+ "storage-location": [
68
+ ('SELECT 1 FROM "Stock Ledger Entry" s JOIN "Storage Location" l ON l.warehouse = s.warehouse '
69
+ 'AND l.location = s.location WHERE l.name = ? LIMIT 1', "stock ledger entry"),
70
+ ],
67
71
  "customer": [
68
72
  ('SELECT 1 FROM "Quotation" WHERE customer = ? LIMIT 1', "quotation"),
69
73
  ('SELECT 1 FROM "Sales Order" WHERE customer = ? LIMIT 1', "sales order"),
@@ -220,6 +224,7 @@ MASTER_LINK_FIELDS = {
220
224
  'account': {'company': 'Company', 'parent_account': 'Account'},
221
225
  'cost-center': {'company': 'Company', 'parent_cost_center': 'Cost Center'},
222
226
  'batch': {'item_code': 'Item'},
227
+ 'storage-location': {'warehouse': 'Warehouse'},
223
228
  }
224
229
 
225
230
 
@@ -285,6 +290,10 @@ def _validate_master_input(master_type, doctype, data, name=None):
285
290
  _validate_item_batch_flags(db, merged, name)
286
291
  if master_type == 'batch':
287
292
  _validate_batch(db, merged, name)
293
+ if master_type == 'warehouse':
294
+ _validate_warehouse_locations(db, merged, name)
295
+ if master_type == 'storage-location':
296
+ _validate_storage_location(db, merged, name)
288
297
  if master_type == 'company' and data.get('default_sales_tax_template'):
289
298
  template = db.get_value('Tax Template', data['default_sales_tax_template'], ['company', 'tax_type'])
290
299
  if not template or template['company'] != (name or data.get('name')) or template['tax_type'] != 'Sales':
@@ -307,6 +316,34 @@ def _validate_item_batch_flags(db, merged, name):
307
316
  raise ValidationError(f'Item {name}: batch tracking cannot be switched off, the stock ledger has batches of it')
308
317
 
309
318
 
319
+ def _validate_warehouse_locations(db, merged, name):
320
+ """Storage locations can be switched on at any time (stock already there
321
+ stays without a location until it is put away). They cannot be switched
322
+ off while stock lies in a location."""
323
+ if flt(merged.get('use_locations')) and flt(merged.get('is_group')):
324
+ raise ValidationError('Warehouse: a group warehouse holds no stock and cannot use storage locations')
325
+ if name and not flt(merged.get('use_locations')) and db.sql(
326
+ 'SELECT 1 FROM "Stock Balance Detail" WHERE warehouse = ? AND location <> \'\' '
327
+ 'AND actual_qty <> 0 LIMIT 1', [name]):
328
+ raise ValidationError(
329
+ f'Warehouse {name}: storage locations cannot be switched off while stock lies in a location')
330
+
331
+
332
+ def _validate_storage_location(db, merged, name):
333
+ for field in ('warehouse', 'location'):
334
+ if missing(merged.get(field)):
335
+ raise ValidationError(f'Storage Location: {field} is required')
336
+ if str(merged['location']) != str(merged['location']).strip():
337
+ raise ValidationError('Storage Location: location must not start or end with a space')
338
+ warehouse = db.get_value('Warehouse', merged['warehouse'], ['is_group'])
339
+ if warehouse and flt(warehouse.get('is_group')):
340
+ raise ValidationError('Storage Location: a group warehouse holds no stock')
341
+ twin = db.get_value('Storage Location', {'warehouse': merged['warehouse'], 'location': merged['location']}, 'name')
342
+ if twin and twin != name:
343
+ raise ValidationError(
344
+ f'Storage location {merged["location"]} already exists in warehouse {merged["warehouse"]} ({twin})')
345
+
346
+
310
347
  def _validate_batch(db, merged, name):
311
348
  for field in ('item_code', 'batch_no'):
312
349
  if missing(merged.get(field)):
@@ -386,16 +386,11 @@ def stock_balance(
386
386
  return _stock_balance(get_db(), item_code, warehouse)
387
387
 
388
388
 
389
- def _batch_stock(db, item_code=None, warehouse=None, batch_no=None, item_prefix=None,
390
- expiring_before=None, include_empty=False):
391
- """Stock per item x warehouse x batch with the batch's expiry date.
392
-
393
- `batch_no` is the label as printed on the goods: the same label can exist
394
- on several items, so it can return several rows. Stock of a tracked item
395
- that has no batch yet appears with an empty batch_no."""
396
- permissions.require_artifact("report", "batch-stock")
389
+ def _stock_detail_where(item_code=None, warehouse=None, batch_no=None, item_prefix=None, expiring_before=None,
390
+ include_empty=False, location=None, item_group=None, expiring_after=None):
397
391
  where, params = [], []
398
- for column, value in (("d.item_code", item_code), ("d.warehouse", warehouse), ("d.batch_no", batch_no)):
392
+ for column, value in (("d.item_code", item_code), ("d.warehouse", warehouse), ("d.batch_no", batch_no),
393
+ ("d.location", location), ("i.item_group", item_group)):
399
394
  if value:
400
395
  where.append(f"{column} = ?")
401
396
  params.append(value)
@@ -405,22 +400,103 @@ def _batch_stock(db, item_code=None, warehouse=None, batch_no=None, item_prefix=
405
400
  if expiring_before:
406
401
  where.append("b.expiry_date IS NOT NULL AND b.expiry_date <= ?")
407
402
  params.append(expiring_before)
403
+ if expiring_after:
404
+ where.append("b.expiry_date IS NOT NULL AND b.expiry_date >= ?")
405
+ params.append(expiring_after)
408
406
  if not include_empty:
409
407
  where.append("d.actual_qty <> 0")
408
+ return where, params
409
+
410
+
411
+ _STOCK_DETAIL_FROM = (
412
+ 'FROM "Stock Balance Detail" d '
413
+ 'LEFT JOIN "Item" i ON i.name = d.item_code '
414
+ 'LEFT JOIN "Batch" b ON b.item_code = d.item_code AND b.batch_no = d.batch_no ')
415
+
416
+
417
+ def _batch_stock(db, item_code=None, warehouse=None, batch_no=None, item_prefix=None,
418
+ expiring_before=None, include_empty=False):
419
+ """Stock per item x warehouse x batch with the batch's expiry date, added
420
+ up over the warehouse's storage locations (stock-detail shows those).
421
+
422
+ `batch_no` is the label as printed on the goods: the same label can exist
423
+ on several items, so it can return several rows. Stock of a tracked item
424
+ that has no batch yet appears with an empty batch_no."""
425
+ permissions.require_artifact("report", "batch-stock")
426
+ where, params = _stock_detail_where(item_code, warehouse, batch_no, item_prefix, expiring_before, True)
410
427
  if not batch_no:
411
428
  # Untracked items have no batches to show; their stock is in stock-balance.
412
429
  where.append("(d.batch_no <> '' OR COALESCE(i.has_batch_no, 0) = 1)")
413
430
  rows = db.sql(
414
431
  'SELECT d.item_code, i.item_name, d.warehouse, d.batch_no, b.name AS batch, b.expiry_date, '
415
- 'COALESCE(b.disabled, 0) AS batch_disabled, d.actual_qty '
416
- 'FROM "Stock Balance Detail" d '
417
- 'LEFT JOIN "Item" i ON i.name = d.item_code '
418
- 'LEFT JOIN "Batch" b ON b.item_code = d.item_code AND b.batch_no = d.batch_no '
432
+ 'COALESCE(b.disabled, 0) AS batch_disabled, SUM(d.actual_qty) AS actual_qty '
433
+ + _STOCK_DETAIL_FROM
419
434
  + (f"WHERE {' AND '.join(where)} " if where else "")
435
+ + 'GROUP BY d.item_code, i.item_name, d.warehouse, d.batch_no, b.name, b.expiry_date, b.disabled '
436
+ + ('' if include_empty else 'HAVING SUM(d.actual_qty) <> 0 ')
420
437
  + 'ORDER BY d.item_code, b.expiry_date, d.batch_no, d.warehouse', params)
421
438
  return {"rows": [{**dict(row), "actual_qty": flt(row["actual_qty"])} for row in rows]}
422
439
 
423
440
 
441
+ def _stock_detail(db, item_code=None, warehouse=None, location=None, batch_no=None, item_prefix=None,
442
+ item_group=None, expiring_before=None, expiring_after=None, include_empty=False):
443
+ """Where stock is, in one view: item, warehouse, storage location, batch,
444
+ expiry date and quantity. Every stock item appears, with an empty batch_no
445
+ or location where it has none."""
446
+ permissions.require_artifact("report", "stock-detail")
447
+ where, params = _stock_detail_where(item_code, warehouse, batch_no, item_prefix, expiring_before,
448
+ include_empty, location, item_group, expiring_after)
449
+ rows = db.sql(
450
+ 'SELECT d.item_code, i.item_name, i.item_group, d.warehouse, d.location, d.batch_no, b.expiry_date, '
451
+ 'd.actual_qty '
452
+ + _STOCK_DETAIL_FROM
453
+ + (f"WHERE {' AND '.join(where)} " if where else "")
454
+ + 'ORDER BY d.item_code, d.warehouse, d.location, b.expiry_date, d.batch_no', params)
455
+ return {"rows": [{**dict(row), "actual_qty": flt(row["actual_qty"])} for row in rows]}
456
+
457
+
458
+ def _stock_availability(db, item_code=None, warehouse=None, item_prefix=None):
459
+ """Per item and warehouse: in stock, blocked (expired or blocked
460
+ batches), reserved (open reservations) and available = the rest. Also
461
+ what customers have ordered and not yet received, and what is on order
462
+ from suppliers."""
463
+ permissions.require_artifact("report", "stock-availability")
464
+ from lambda_erp.stock.reservation import availability_rows
465
+ rows = []
466
+ for row in availability_rows(item_code, warehouse, item_prefix):
467
+ plan = db.get_value("Bin", {"item_code": row.item_code, "warehouse": row.warehouse},
468
+ ["reserved_qty", "ordered_qty"]) or {}
469
+ rows.append({**row, "item_name": db.get_value("Item", row.item_code, "item_name") or row.item_code,
470
+ "open_sales_order_qty": flt(plan.get("reserved_qty")),
471
+ "on_purchase_order_qty": flt(plan.get("ordered_qty"))})
472
+ return {"rows": rows}
473
+
474
+
475
+ @router.get("/stock-availability")
476
+ def stock_availability(
477
+ item_code: str | None = None,
478
+ warehouse: str | None = None,
479
+ item_prefix: str | None = None,
480
+ ):
481
+ return _stock_availability(get_db(), item_code, warehouse, item_prefix)
482
+
483
+
484
+ @router.get("/stock-detail")
485
+ def stock_detail(
486
+ item_code: str | None = None,
487
+ warehouse: str | None = None,
488
+ location: str | None = None,
489
+ batch_no: str | None = None,
490
+ item_prefix: str | None = None,
491
+ item_group: str | None = None,
492
+ expiring_before: str | None = None,
493
+ expiring_after: str | None = None,
494
+ include_empty: bool = False,
495
+ ):
496
+ return _stock_detail(get_db(), item_code, warehouse, location, batch_no, item_prefix, item_group,
497
+ expiring_before, expiring_after, include_empty)
498
+
499
+
424
500
  @router.get("/batch-stock")
425
501
  def batch_stock(
426
502
  item_code: str | None = None,
@@ -453,7 +529,7 @@ def _batch_movements(db, batch_no=None, item_code=None, warehouse=None):
453
529
  where.append(f"{column} = ?")
454
530
  params.append(value)
455
531
  rows = db.sql(
456
- 'SELECT s.name, s.posting_date, s.item_code, s.warehouse, s.batch_no, s.actual_qty, '
532
+ 'SELECT s.name, s.posting_date, s.item_code, s.warehouse, s.location, s.batch_no, s.actual_qty, '
457
533
  's.voucher_type, s.voucher_no, s.voucher_detail_no '
458
534
  f'FROM "Stock Ledger Entry" s WHERE {" AND ".join(where)} '
459
535
  'ORDER BY s.posting_date, s.creation, s.name', params)
@@ -31,6 +31,7 @@ from lambda_erp.accounting.bank_transaction import BankTransaction
31
31
  from lambda_erp.accounting.bank_account import BankAccount
32
32
  from lambda_erp.assets.asset import Asset
33
33
  from lambda_erp.assets.reservation import Reservation
34
+ from lambda_erp.stock.reservation import StockReservation
34
35
 
35
36
 
36
37
  # --- Doctype registries ---
@@ -60,6 +61,8 @@ DOCUMENT_CLASSES = {
60
61
  # CRUD, the chat tools and MCP drive them like every other doctype.
61
62
  "Asset": Asset,
62
63
  "Reservation": Reservation,
64
+ # Stock set aside for a sales order line (or with a reason); also status-driven.
65
+ "Stock Reservation": StockReservation,
63
66
  }
64
67
 
65
68
  CONVERTERS = {
@@ -87,6 +90,8 @@ MASTER_TABLES = {
87
90
  "cost-center": ("Cost Center", "cost_center_name"),
88
91
  # One row per (item, batch label); the label alone is not unique.
89
92
  "batch": ("Batch", "batch_no"),
93
+ # One row per (warehouse, location label).
94
+ "storage-location": ("Storage Location", "location"),
90
95
  }
91
96
 
92
97
  # Auto-naming prefixes: masters created without an explicit `name` get a
@@ -98,11 +103,12 @@ MASTER_NAME_PREFIXES = {
98
103
  "item": "ITEM",
99
104
  "warehouse": "WH",
100
105
  "batch": "BATCH",
106
+ "storage-location": "LOC",
101
107
  }
102
108
 
103
109
  # Minimum numeric suffix width for sequential plugin master ids. Core masters
104
110
  # retain the historical three-digit form; plugins can opt into e.g. FIDX-0001.
105
- MASTER_NAME_DIGITS: dict[str, int] = {"batch": 5}
111
+ MASTER_NAME_DIGITS: dict[str, int] = {"batch": 5, "storage-location": 5}
106
112
 
107
113
  # High-volume plugin masters can opt out of sequential ids. Sequential naming
108
114
  # must inspect existing suffixes after a process restart; opaque random ids keep
@@ -0,0 +1,79 @@
1
+ """Stock actions that are more than a single document save, available over
2
+ REST (/api/actions/...), chat and MCP."""
3
+ from pydantic import Field
4
+
5
+ from api import mentions, services
6
+ from lambda_erp import permissions
7
+ from lambda_erp.stock.stock_entry import make_location_move
8
+
9
+
10
+ class MoveLocation(mentions.Input):
11
+ warehouse: str = Field(min_length=1, max_length=200)
12
+ from_location: str = Field(min_length=1, max_length=200)
13
+ to_location: str | None = Field(default=None, max_length=200)
14
+ to_warehouse: str | None = Field(default=None, max_length=200)
15
+
16
+
17
+ def prepare_location_move(args):
18
+ data = MoveLocation.model_validate(args)
19
+ permissions.require_writable("Stock Entry", "create")
20
+ entry = make_location_move(data.warehouse, data.from_location, data.to_location, data.to_warehouse)
21
+ entry.save()
22
+ return services.load_document("stock-entry", entry.name)
23
+
24
+
25
+ class ReserveOrder(mentions.Input):
26
+ sales_order: str = Field(min_length=1, max_length=200)
27
+ sales_order_items: list[str] | None = Field(default=None, max_length=500)
28
+
29
+
30
+ class SuggestPicks(mentions.Input):
31
+ item_code: str = Field(min_length=1, max_length=200)
32
+ warehouse: str = Field(min_length=1, max_length=200)
33
+ qty: float = Field(gt=0)
34
+ customer: str | None = Field(default=None, max_length=200)
35
+ sales_order_item: str | None = Field(default=None, max_length=200)
36
+ include_short_dated: bool = False
37
+
38
+
39
+ def reserve_order(args):
40
+ data = ReserveOrder.model_validate(args)
41
+ permissions.require_readable("Sales Order", data.sales_order)
42
+ permissions.require_writable("Stock Reservation", "create")
43
+ from lambda_erp.stock.reservation import reserve_sales_order
44
+ return reserve_sales_order(data.sales_order, data.sales_order_items)
45
+
46
+
47
+ def suggest(args):
48
+ data = SuggestPicks.model_validate(args)
49
+ permissions.require("Stock Reservation", "read")
50
+ from lambda_erp.stock.reservation import suggest_picks
51
+ return suggest_picks(data.item_code, data.warehouse, data.qty, customer=data.customer,
52
+ sales_order_item=data.sales_order_item, include_short_dated=data.include_short_dated)
53
+
54
+
55
+ def initialize_stock_actions():
56
+ services.register_action(
57
+ "reserve_sales_order", reserve_order,
58
+ description=(
59
+ "Reserve stock for the undelivered part of a submitted sales order (all stock lines, or only "
60
+ "sales_order_items). Reserves as much as is available per line and reports short_qty for the rest. "
61
+ "Reserved stock cannot be delivered, issued or transferred away for anyone else. To give stock back, "
62
+ "update the Stock Reservation's status to Released."),
63
+ parameters=ReserveOrder.model_json_schema(), minimum_role="manager")
64
+ services.register_action(
65
+ "suggest_picks", suggest,
66
+ description=(
67
+ "READ-ONLY picking proposal, first expired first out: which batches and storage locations to take a "
68
+ "quantity of an item from in a warehouse. Never proposes blocked or expired batches or stock reserved "
69
+ "for other orders; batches with too little shelf life left are listed under excluded unless "
70
+ "include_short_dated. Changes nothing: no reservation, no stock movement, no invoice."),
71
+ parameters=SuggestPicks.model_json_schema(), minimum_role="viewer")
72
+ services.register_action(
73
+ "prepare_location_move", prepare_location_move,
74
+ description=(
75
+ "Prepare moving EVERYTHING that lies in one storage location to another location "
76
+ "(same warehouse, or to_warehouse): creates a DRAFT Stock Entry (Material Transfer) with one row "
77
+ "per item and batch found there. Nothing moves until that draft is submitted with submit_document; "
78
+ "show the rows to the user first. For single items create a Material Transfer directly."),
79
+ parameters=MoveLocation.model_json_schema(), minimum_role="manager")
@@ -568,6 +568,12 @@ export const api = {
568
568
  batchStock: (params?: Record<string, string>) =>
569
569
  request<{ rows: any[] }>(`/reports/batch-stock${qs(params)}`),
570
570
 
571
+ stockAvailability: (params?: Record<string, string>) =>
572
+ request<{ rows: any[] }>(`/reports/stock-availability${qs(params)}`),
573
+
574
+ stockDetail: (params?: Record<string, string>) =>
575
+ request<{ rows: any[] }>(`/reports/stock-detail${qs(params)}`),
576
+
571
577
  batchMovements: (params: Record<string, string>) =>
572
578
  request<{ rows: any[] }>(`/reports/batch-movements${qs(params)}`),
573
579
 
@@ -172,6 +172,8 @@ class POSInvoice(Document):
172
172
  # GL entries (Dr COGS / Cr Stock In Hand at cost). Without this, stock
173
173
  # leaves physically but the balance sheet never reflects it.
174
174
  if flt(self._data.get("update_stock")):
175
+ from lambda_erp.stock.reservation import validate_sellable
176
+ validate_sellable(self)
175
177
  sl_entries = self._get_sl_entries()
176
178
  if sl_entries:
177
179
  make_sl_entries(sl_entries)
@@ -338,6 +340,7 @@ def make_pos_return(posi_name):
338
340
  cost_center=item.get("cost_center"),
339
341
  warehouse=item.get("warehouse"),
340
342
  batch_no=item.get("batch_no"),
343
+ location=item.get("location"),
341
344
  ))
342
345
 
343
346
  for tax in original.get("taxes") or []:
@@ -475,6 +475,7 @@ def make_purchase_return(pinv_name):
475
475
  cost_center=item.get("cost_center"),
476
476
  warehouse=item.get("warehouse"),
477
477
  batch_no=item.get("batch_no"),
478
+ location=item.get("location"),
478
479
  purchase_order=item.get("purchase_order"),
479
480
  purchase_order_item=item.get("purchase_order_item"),
480
481
  ))
@@ -294,6 +294,8 @@ class SalesInvoice(Document):
294
294
  to_base_currency(gl_entries, self.get("conversion_rate"))
295
295
 
296
296
  if flt(self.get("update_stock")):
297
+ from lambda_erp.stock.reservation import validate_sellable
298
+ validate_sellable(self)
297
299
  sl_entries = self._get_stock_sl_entries()
298
300
  if sl_entries:
299
301
  make_sl_entries(sl_entries)
@@ -459,6 +461,7 @@ def make_sales_return(sinv_name):
459
461
  cost_center=item.get("cost_center"),
460
462
  warehouse=item.get("warehouse"),
461
463
  batch_no=item.get("batch_no"),
464
+ location=item.get("location"),
462
465
  sales_order=item.get("sales_order"),
463
466
  sales_order_item=item.get("sales_order_item"),
464
467
  ))
@@ -3271,6 +3271,88 @@ def _m051_batches(db: "Database") -> None:
3271
3271
  db.conn.commit()
3272
3272
 
3273
3273
 
3274
+ LOCATION_LINE_TABLES = ("Delivery Note Item", "Purchase Receipt Item", "Sales Invoice Item",
3275
+ "Purchase Invoice Item", "POS Invoice Item")
3276
+
3277
+
3278
+ def _m053_storage_locations(db: "Database") -> None:
3279
+ """Storage locations inside a warehouse (see docs/storage-locations.md).
3280
+
3281
+ - Warehouse.use_locations switches them on per warehouse.
3282
+ - "Storage Location" is the master: one row per (warehouse, location label).
3283
+ - "Stock Balance Detail" and the stock ledger get a `location`; '' is stock
3284
+ without a location (every warehouse that does not use them, and stock
3285
+ that was there before a warehouse was switched). Existing rows keep ''.
3286
+ """
3287
+ db.conn.execute(db._ddl(
3288
+ """CREATE TABLE IF NOT EXISTS "Storage Location" (
3289
+ name TEXT PRIMARY KEY,
3290
+ location TEXT NOT NULL,
3291
+ warehouse TEXT NOT NULL,
3292
+ description TEXT,
3293
+ disabled INTEGER DEFAULT 0,
3294
+ creation TEXT,
3295
+ modified TEXT
3296
+ )"""))
3297
+ db.conn.execute(db._ddl(
3298
+ 'CREATE UNIQUE INDEX IF NOT EXISTS "ux_storage_location_warehouse_location" '
3299
+ 'ON "Storage Location" (warehouse, location)'))
3300
+ db.conn.commit()
3301
+ db._col_cache.pop("Storage Location", None)
3302
+ db._text_col_cache.pop("Storage Location", None)
3303
+ db.ensure_column("Warehouse", "use_locations", "INTEGER DEFAULT 0")
3304
+ db.ensure_column("Stock Ledger Entry", "location", "TEXT")
3305
+ db.ensure_column("Stock Balance Detail", "location", "TEXT NOT NULL DEFAULT ''")
3306
+ for table in LOCATION_LINE_TABLES:
3307
+ db.ensure_column(table, "location", "TEXT")
3308
+ db.ensure_column("Stock Entry Detail", "s_location", "TEXT")
3309
+ db.ensure_column("Stock Entry Detail", "t_location", "TEXT")
3310
+ # The balance key grows by the location.
3311
+ db.conn.execute(db._ddl('DROP INDEX IF EXISTS "ux_stock_balance_detail_key"'))
3312
+ db.conn.execute(db._ddl(
3313
+ 'CREATE UNIQUE INDEX IF NOT EXISTS "ux_stock_balance_detail_location_key" '
3314
+ 'ON "Stock Balance Detail" (item_code, warehouse, batch_no, location)'))
3315
+ db.conn.commit()
3316
+
3317
+
3318
+ def _m054_reservations_and_shelf_life(db: "Database") -> None:
3319
+ """Sales reservations, blocked batches and shelf life
3320
+ (see docs/reservations-and-fefo.md). Nothing is reserved or blocked by
3321
+ the migration; orders reserve only when asked to."""
3322
+ db.conn.execute(db._ddl(
3323
+ """CREATE TABLE IF NOT EXISTS "Stock Reservation" (
3324
+ name TEXT PRIMARY KEY,
3325
+ item_code TEXT NOT NULL,
3326
+ warehouse TEXT NOT NULL,
3327
+ reserved_qty REAL DEFAULT 0,
3328
+ sales_order TEXT,
3329
+ sales_order_item TEXT,
3330
+ customer TEXT,
3331
+ remarks TEXT,
3332
+ status TEXT DEFAULT 'Reserved',
3333
+ reserved_by TEXT,
3334
+ company TEXT,
3335
+ discarded INTEGER DEFAULT 0,
3336
+ docstatus INTEGER DEFAULT 0,
3337
+ creation TEXT,
3338
+ modified TEXT
3339
+ )"""))
3340
+ db.conn.execute(db._ddl(
3341
+ 'CREATE INDEX IF NOT EXISTS "ix_stock_reservation_item" ON "Stock Reservation" (item_code, warehouse, status)'))
3342
+ db.conn.execute(db._ddl(
3343
+ 'CREATE INDEX IF NOT EXISTS "ix_stock_reservation_order" ON "Stock Reservation" (sales_order)'))
3344
+ db.conn.commit()
3345
+ db._col_cache.pop("Stock Reservation", None)
3346
+ db._text_col_cache.pop("Stock Reservation", None)
3347
+ db.ensure_column("Batch", "blocked", "INTEGER DEFAULT 0")
3348
+ db.ensure_column("Batch", "blocked_reason", "TEXT")
3349
+ db.ensure_column("Item", "min_shelf_life_days", "INTEGER DEFAULT 0")
3350
+ db.ensure_column("Sales Order", "reserve_stock", "INTEGER DEFAULT 0")
3351
+ for table in ("Delivery Note Item", "Sales Invoice Item", "POS Invoice Item"):
3352
+ db.ensure_column(table, "shelf_life_exception", "TEXT")
3353
+ db.ensure_column(table, "shelf_life_exception_by", "TEXT")
3354
+
3355
+
3274
3356
  def _m052_access_profiles(db: "Database") -> None:
3275
3357
  """Access profiles narrow what a user's role allows (lambda_erp.permissions).
3276
3358
  No profile is created and no user is assigned one: nothing changes for
@@ -3363,6 +3445,8 @@ Database.MIGRATIONS = [
3363
3445
  (50, "amount_only_returns", _m050_amount_only_returns),
3364
3446
  (51, "batches", _m051_batches),
3365
3447
  (52, "access_profiles", _m052_access_profiles),
3448
+ (53, "storage_locations", _m053_storage_locations),
3449
+ (54, "reservations_and_shelf_life", _m054_reservations_and_shelf_life),
3366
3450
  ]
3367
3451
 
3368
3452
 
@@ -8,6 +8,8 @@ STRUCTURAL_FIELDS = {
8
8
  'company': ('default_currency',),
9
9
  # A batch is identified by its item and label once stock has moved on it.
10
10
  'batch': ('item_code', 'batch_no'),
11
+ # A storage location is identified by its warehouse and label once stock has been in it.
12
+ 'storage-location': ('warehouse', 'location'),
11
13
  }
12
14
 
13
15
 
@@ -388,6 +388,10 @@ class Document:
388
388
  from lambda_erp.workflow import lock_workflow_references
389
389
  self._validate_server_managed_fields()
390
390
  lock_workflow_references(self)
391
+ # Stock that is reserved for someone else must still be there
392
+ # afterwards (lambda_erp.stock.reservation).
393
+ from lambda_erp.stock import reservation
394
+ reserved = reservation.begin_guard(self)
391
395
  self._data["modified"] = now()
392
396
  from lambda_erp.controllers.item_prices import normalize_item_prices
393
397
  normalize_item_prices(self)
@@ -405,6 +409,7 @@ class Document:
405
409
  self.on_submit()
406
410
  from lambda_erp.workflow import refresh_order_progress
407
411
  refresh_order_progress(self)
412
+ reservation.finish_guard(self, reserved)
408
413
  except Exception:
409
414
  self._data, self._children, self._persisted, self._loaded_modified = snapshot
410
415
  raise
@@ -423,6 +428,8 @@ class Document:
423
428
  self._check_write_state(SUBMITTED)
424
429
  from lambda_erp.workflow import lock_workflow_references, validate_cancellation, refresh_order_progress
425
430
  lock_workflow_references(self)
431
+ from lambda_erp.stock import reservation
432
+ reserved = reservation.begin_guard(self)
426
433
  from lambda_erp.assets.lifecycle import validate_voucher_release
427
434
  validate_voucher_release(self)
428
435
  validate_cancellation(self)
@@ -433,6 +440,7 @@ class Document:
433
440
  self._persist(commit=False)
434
441
  self.on_cancel()
435
442
  refresh_order_progress(self)
443
+ reservation.finish_guard(self, reserved, cancelling=True)
436
444
  except Exception:
437
445
  self._data, self._children, self._persisted, self._loaded_modified = snapshot
438
446
  raise