lambda-erp 1.4.6__tar.gz → 1.4.7__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 (127) hide show
  1. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/PKG-INFO +1 -1
  2. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/chat.py +17 -2
  3. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/main.py +2 -0
  4. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/masters.py +37 -0
  5. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/reports.py +64 -14
  6. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/services.py +4 -1
  7. lambda_erp-1.4.7/api/stock_actions.py +33 -0
  8. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/frontend/src/api/client.ts +3 -0
  9. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/pos_invoice.py +1 -0
  10. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/purchase_invoice.py +1 -0
  11. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/sales_invoice.py +1 -0
  12. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/database.py +45 -0
  13. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/master_integrity.py +2 -0
  14. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/stock/delivery_note.py +1 -0
  15. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/stock/purchase_receipt.py +2 -0
  16. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/stock/stock_entry.py +64 -3
  17. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/stock/stock_ledger.py +92 -23
  18. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/pyproject.toml +1 -1
  19. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/.gitignore +0 -0
  20. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/LICENSE +0 -0
  21. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/README.md +0 -0
  22. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/__init__.py +0 -0
  23. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/attachments.py +0 -0
  24. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/auth.py +0 -0
  25. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/bootstrap.py +0 -0
  26. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/chat_links.py +0 -0
  27. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/demo_limits.py +0 -0
  28. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/deps.py +0 -0
  29. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/erp_context.py +0 -0
  30. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/errors.py +0 -0
  31. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/list_values.py +0 -0
  32. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/llm_provider.py +0 -0
  33. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/mcp_oauth.py +0 -0
  34. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/mentions.py +0 -0
  35. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/menu_layout.py +0 -0
  36. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/oauth.py +0 -0
  37. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/pdf.py +0 -0
  38. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/pdf_contract.py +0 -0
  39. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/pdf_exports.py +0 -0
  40. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/pdf_fonts.py +0 -0
  41. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/pdf_pages.py +0 -0
  42. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/pdf_profiles.py +0 -0
  43. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/pdf_templates.py +0 -0
  44. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/providers.py +0 -0
  45. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/record_notes.py +0 -0
  46. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/remarks_md.py +0 -0
  47. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/__init__.py +0 -0
  48. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/accounting.py +0 -0
  49. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/actions.py +0 -0
  50. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/admin.py +0 -0
  51. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/analytics.py +0 -0
  52. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/availability.py +0 -0
  53. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/bank_reconciliation.py +0 -0
  54. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/bank_statements.py +0 -0
  55. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/chat_api.py +0 -0
  56. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/documents.py +0 -0
  57. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/mcp.py +0 -0
  58. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/pdf_templates.py +0 -0
  59. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/proposals.py +0 -0
  60. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/routers/setup.py +0 -0
  61. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/templates/_proposal_totals.html +0 -0
  62. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/templates/_record_base.html +0 -0
  63. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/templates/delivery_note.html +0 -0
  64. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/templates/document.html +0 -0
  65. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/templates/proposal.html +0 -0
  66. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/templates/record.html +0 -0
  67. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/templates/reservation.html +0 -0
  68. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/time_filters.py +0 -0
  69. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/tool_permissions.py +0 -0
  70. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/api/write_context.py +0 -0
  71. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/docs/agents/README.md +0 -0
  72. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/frontend/LICENSE +0 -0
  73. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/frontend/README.md +0 -0
  74. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/__init__.py +0 -0
  75. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/__init__.py +0 -0
  76. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/bank_account.py +0 -0
  77. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  78. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/bank_statement_import.py +0 -0
  79. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/bank_transaction.py +0 -0
  80. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/budget.py +0 -0
  81. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/camt.py +0 -0
  82. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  83. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/general_ledger.py +0 -0
  84. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/journal_entry.py +0 -0
  85. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/payment_entry.py +0 -0
  86. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/revaluation.py +0 -0
  87. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/settlement.py +0 -0
  88. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/__init__.py +0 -0
  89. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/engine.py +0 -0
  90. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/pack.py +0 -0
  91. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  92. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  93. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  94. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  95. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  96. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  97. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/profiles.py +0 -0
  98. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/setup/spine.py +0 -0
  99. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/accounting/subscription.py +0 -0
  100. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/assets/__init__.py +0 -0
  101. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/assets/asset.py +0 -0
  102. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/assets/lifecycle.py +0 -0
  103. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/assets/reservation.py +0 -0
  104. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/buying/__init__.py +0 -0
  105. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/buying/purchase_order.py +0 -0
  106. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/controllers/__init__.py +0 -0
  107. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/controllers/currency.py +0 -0
  108. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/controllers/defaults.py +0 -0
  109. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/controllers/item_price.py +0 -0
  110. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/controllers/item_prices.py +0 -0
  111. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/controllers/pricing_rule.py +0 -0
  112. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  113. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/exceptions.py +0 -0
  114. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/hooks.py +0 -0
  115. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/model.py +0 -0
  116. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/permissions.py +0 -0
  117. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/selling/__init__.py +0 -0
  118. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/selling/proposal.py +0 -0
  119. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/selling/quotation.py +0 -0
  120. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/selling/sales_order.py +0 -0
  121. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/simulation.py +0 -0
  122. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/stock/__init__.py +0 -0
  123. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/timestamps.py +0 -0
  124. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/utils.py +0 -0
  125. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/validation.py +0 -0
  126. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/lambda_erp/workflow.py +0 -0
  127. {lambda_erp-1.4.6 → lambda_erp-1.4.7}/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.7
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-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,12 @@ 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-detail":
1978
+ from api.routers.reports import _stock_detail
1979
+ return _stock_detail(db, filters.get("item_code"), filters.get("warehouse"), filters.get("location"),
1980
+ filters.get("batch_no"), filters.get("item_prefix"), filters.get("item_group"),
1981
+ filters.get("expiring_before"), filters.get("expiring_after"),
1982
+ bool(filters.get("include_empty")))
1977
1983
  elif report_type == "batch-movements":
1978
1984
  from api.routers.reports import _batch_movements
1979
1985
  if not filters.get("batch_no"):
@@ -2909,6 +2915,14 @@ For a complete sales return (financial + stock): create and submit both a Credit
2909
2915
  - **Material Transfer:** Moves stock between warehouses. No GL impact.
2910
2916
  - **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
2917
 
2918
+ ### Storage locations (places inside a warehouse)
2919
+ - 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.
2920
+ - 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.
2921
+ - Stock is checked per location (and per batch within it). Find the location with the stock-detail report first; never guess one.
2922
+ - 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.
2923
+ - 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.
2924
+ - A disabled location takes no new stock but can still be emptied.
2925
+
2912
2926
  ### Batches (lot numbers)
2913
2927
  - 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
2928
  - 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 +2986,7 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
2972
2986
  - **ar-aging** — Outstanding receivables bucketed by overdue days (Current, 1-30, 31-60, 61-90, 90+). Filters: company, as_of_date.
2973
2987
  - **ap-aging** — Outstanding payables bucketed by overdue days. Filters: company, as_of_date.
2974
2988
  - **stock-balance** — Inventory quantities and valuations. Filters: item_code, warehouse.
2989
+ - **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
2990
  - **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
2991
  - **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
2992
  - **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
@@ -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,77 @@ 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
+ @router.get("/stock-detail")
459
+ def stock_detail(
460
+ item_code: str | None = None,
461
+ warehouse: str | None = None,
462
+ location: str | None = None,
463
+ batch_no: str | None = None,
464
+ item_prefix: str | None = None,
465
+ item_group: str | None = None,
466
+ expiring_before: str | None = None,
467
+ expiring_after: str | None = None,
468
+ include_empty: bool = False,
469
+ ):
470
+ return _stock_detail(get_db(), item_code, warehouse, location, batch_no, item_prefix, item_group,
471
+ expiring_before, expiring_after, include_empty)
472
+
473
+
424
474
  @router.get("/batch-stock")
425
475
  def batch_stock(
426
476
  item_code: str | None = None,
@@ -453,7 +503,7 @@ def _batch_movements(db, batch_no=None, item_code=None, warehouse=None):
453
503
  where.append(f"{column} = ?")
454
504
  params.append(value)
455
505
  rows = db.sql(
456
- 'SELECT s.name, s.posting_date, s.item_code, s.warehouse, s.batch_no, s.actual_qty, '
506
+ 'SELECT s.name, s.posting_date, s.item_code, s.warehouse, s.location, s.batch_no, s.actual_qty, '
457
507
  's.voucher_type, s.voucher_no, s.voucher_detail_no '
458
508
  f'FROM "Stock Ledger Entry" s WHERE {" AND ".join(where)} '
459
509
  'ORDER BY s.posting_date, s.creation, s.name', params)
@@ -87,6 +87,8 @@ MASTER_TABLES = {
87
87
  "cost-center": ("Cost Center", "cost_center_name"),
88
88
  # One row per (item, batch label); the label alone is not unique.
89
89
  "batch": ("Batch", "batch_no"),
90
+ # One row per (warehouse, location label).
91
+ "storage-location": ("Storage Location", "location"),
90
92
  }
91
93
 
92
94
  # Auto-naming prefixes: masters created without an explicit `name` get a
@@ -98,11 +100,12 @@ MASTER_NAME_PREFIXES = {
98
100
  "item": "ITEM",
99
101
  "warehouse": "WH",
100
102
  "batch": "BATCH",
103
+ "storage-location": "LOC",
101
104
  }
102
105
 
103
106
  # Minimum numeric suffix width for sequential plugin master ids. Core masters
104
107
  # retain the historical three-digit form; plugins can opt into e.g. FIDX-0001.
105
- MASTER_NAME_DIGITS: dict[str, int] = {"batch": 5}
108
+ MASTER_NAME_DIGITS: dict[str, int] = {"batch": 5, "storage-location": 5}
106
109
 
107
110
  # High-volume plugin masters can opt out of sequential ids. Sequential naming
108
111
  # must inspect existing suffixes after a process restart; opaque random ids keep
@@ -0,0 +1,33 @@
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
+ def initialize_stock_actions():
26
+ services.register_action(
27
+ "prepare_location_move", prepare_location_move,
28
+ description=(
29
+ "Prepare moving EVERYTHING that lies in one storage location to another location "
30
+ "(same warehouse, or to_warehouse): creates a DRAFT Stock Entry (Material Transfer) with one row "
31
+ "per item and batch found there. Nothing moves until that draft is submitted with submit_document; "
32
+ "show the rows to the user first. For single items create a Material Transfer directly."),
33
+ parameters=MoveLocation.model_json_schema(), minimum_role="manager")
@@ -568,6 +568,9 @@ export const api = {
568
568
  batchStock: (params?: Record<string, string>) =>
569
569
  request<{ rows: any[] }>(`/reports/batch-stock${qs(params)}`),
570
570
 
571
+ stockDetail: (params?: Record<string, string>) =>
572
+ request<{ rows: any[] }>(`/reports/stock-detail${qs(params)}`),
573
+
571
574
  batchMovements: (params: Record<string, string>) =>
572
575
  request<{ rows: any[] }>(`/reports/batch-movements${qs(params)}`),
573
576
 
@@ -338,6 +338,7 @@ def make_pos_return(posi_name):
338
338
  cost_center=item.get("cost_center"),
339
339
  warehouse=item.get("warehouse"),
340
340
  batch_no=item.get("batch_no"),
341
+ location=item.get("location"),
341
342
  ))
342
343
 
343
344
  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
  ))
@@ -459,6 +459,7 @@ def make_sales_return(sinv_name):
459
459
  cost_center=item.get("cost_center"),
460
460
  warehouse=item.get("warehouse"),
461
461
  batch_no=item.get("batch_no"),
462
+ location=item.get("location"),
462
463
  sales_order=item.get("sales_order"),
463
464
  sales_order_item=item.get("sales_order_item"),
464
465
  ))
@@ -3271,6 +3271,50 @@ 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
+
3274
3318
  def _m052_access_profiles(db: "Database") -> None:
3275
3319
  """Access profiles narrow what a user's role allows (lambda_erp.permissions).
3276
3320
  No profile is created and no user is assigned one: nothing changes for
@@ -3363,6 +3407,7 @@ Database.MIGRATIONS = [
3363
3407
  (50, "amount_only_returns", _m050_amount_only_returns),
3364
3408
  (51, "batches", _m051_batches),
3365
3409
  (52, "access_profiles", _m052_access_profiles),
3410
+ (53, "storage_locations", _m053_storage_locations),
3366
3411
  ]
3367
3412
 
3368
3413
 
@@ -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
 
@@ -210,6 +210,7 @@ def make_delivery_return(dn_name):
210
210
  rate=flt(item.get("rate")),
211
211
  warehouse=item.get("warehouse"),
212
212
  batch_no=item.get("batch_no"),
213
+ location=item.get("location"),
213
214
  against_sales_order=item.get("against_sales_order"),
214
215
  so_detail=item.get("so_detail"),
215
216
  ))
@@ -181,6 +181,7 @@ class PurchaseReceipt(Document):
181
181
  voucher_detail_no=item.get("name"),
182
182
  batch_no=item.get("batch_no"),
183
183
  expiry_date=item.get("expiry_date"),
184
+ location=item.get("location"),
184
185
  posting_date=self.posting_date,
185
186
  company=self.company,
186
187
  ))
@@ -312,6 +313,7 @@ def make_purchase_receipt_return(prec_name):
312
313
  rate=flt(item.get("rate")),
313
314
  warehouse=item.get("warehouse"),
314
315
  batch_no=item.get("batch_no"),
316
+ location=item.get("location"),
315
317
  against_purchase_order=item.get("against_purchase_order"),
316
318
  po_detail=item.get("po_detail"),
317
319
  ))
@@ -33,6 +33,7 @@ class StockEntry(Document):
33
33
  "stock_entry_type must be Opening Stock, Material Receipt, Material Issue, Material Transfer or Batch Assignment.",
34
34
  "Every items row requires an existing item_code and a positive finite qty. Receipt/opening need t_warehouse; issue needs s_warehouse; transfer needs two distinct warehouses. Warehouses must belong to company.",
35
35
  "Rows of a batch-tracked item (Item.has_batch_no) require batch_no; a new batch on a receipt/opening row also needs expiry_date when the item has expiry dates. A transfer moves the batch as it is. Items that are not batch-tracked take no batch_no.",
36
+ "In a warehouse with storage locations (Warehouse.use_locations) every row names the location: s_location for the source side, t_location for the target side. A Material Transfer may stay inside one warehouse when the two locations differ; it then changes neither total quantity nor value and posts no GL. In such a move s_location may be left empty to put away stock that has no location yet. Warehouses without storage locations take no location.",
36
37
  "Batch Assignment gives stock that has no batch (from before the item was batch-tracked) its batch without moving it: each row needs the warehouse (s_warehouse or t_warehouse), batch_no and qty; it changes neither total quantity nor value and posts no GL.",
37
38
  )
38
39
 
@@ -86,7 +87,16 @@ class StockEntry(Document):
86
87
  db = get_db()
87
88
  for item in self.get('items'):
88
89
  if self.stock_entry_type == 'Material Transfer' and item.get('s_warehouse') == item.get('t_warehouse'):
89
- raise ValidationError('Source and Target Warehouse must be different')
90
+ # Inside one warehouse a transfer is a move between storage locations.
91
+ uses = db.exists('Warehouse', item['s_warehouse']) and flt(
92
+ db.get_value('Warehouse', item['s_warehouse'], 'use_locations'))
93
+ source, target = (str(item.get(f) or '').strip() for f in ('s_location', 't_location'))
94
+ if not uses:
95
+ raise ValidationError('Source and Target Warehouse must be different')
96
+ if not target or source == target:
97
+ raise ValidationError(
98
+ 'A transfer inside one warehouse moves stock between storage locations: '
99
+ 'give a Target Location that differs from the Source Location')
90
100
  if self.stock_entry_type in ('Opening Stock', 'Material Receipt') and item.get('s_warehouse'):
91
101
  raise ValidationError('A receipt cannot have a Source Warehouse; use Material Transfer')
92
102
  if self.stock_entry_type == 'Material Issue' and item.get('t_warehouse'):
@@ -127,6 +137,10 @@ class StockEntry(Document):
127
137
  raise ValidationError(
128
138
  "Batch Assignment does not move stock: Source and Target Warehouse must be the same")
129
139
  item["s_warehouse"] = item["t_warehouse"] = warehouse
140
+ # The stock stays in its storage location unless both are given
141
+ # (an empty source then means stock that has no location yet).
142
+ if not item.get("t_location"):
143
+ item["t_location"] = item.get("s_location")
130
144
  if not str(item.get("batch_no") or "").strip():
131
145
  raise ValidationError(
132
146
  f"Batch is required for Batch Assignment (Item: {item.get('item_code')})")
@@ -188,14 +202,19 @@ class StockEntry(Document):
188
202
  # and puts it back, at the same value, under the batch.
189
203
  source_batch = ({'batch_no': None, 'allow_unassigned_batch': True}
190
204
  if self.stock_entry_type == 'Batch Assignment' else batch)
205
+ # A move inside one warehouse may take stock that has no storage
206
+ # location yet (from before the warehouse used them) and put it away.
207
+ same_warehouse = bool(item.get('s_warehouse')) and item.get('s_warehouse') == item.get('t_warehouse')
208
+ source_location = {'location': item.get('s_location'),
209
+ 'allow_unassigned_location': same_warehouse and not item.get('s_location')}
191
210
  if item.get('s_warehouse'):
192
- make_sl_entries([{**base, **source_batch, 'warehouse': item['s_warehouse'], 'actual_qty': -flt(item['qty']), 'outgoing_rate': 0}])
211
+ make_sl_entries([{**base, **source_batch, **source_location, 'warehouse': item['s_warehouse'], 'actual_qty': -flt(item['qty']), 'outgoing_rate': 0}])
193
212
  posted = db.get_value('Stock Ledger Entry', {'voucher_type': self.DOCTYPE, 'voucher_no': self.name, 'voucher_detail_no': item['name'], 'warehouse': item['s_warehouse']}, ['stock_value_difference'])
194
213
  value = -flt(posted.stock_value_difference)
195
214
  rate = value / flt(item['qty'])
196
215
  outgoing += value
197
216
  if item.get('t_warehouse'):
198
- make_sl_entries([{**base, **batch, 'expiry_date': item.get('expiry_date'), 'warehouse': item['t_warehouse'], 'actual_qty': flt(item['qty']), 'incoming_rate': rate, 'incoming_rate_is_explicit': True}])
217
+ make_sl_entries([{**base, **batch, 'expiry_date': item.get('expiry_date'), 'location': item.get('t_location'), 'warehouse': item['t_warehouse'], 'actual_qty': flt(item['qty']), 'incoming_rate': rate, 'incoming_rate_is_explicit': True}])
199
218
  incoming += flt(item['qty']) * rate
200
219
  item['basic_rate'] = rate
201
220
  item['basic_amount'] = item['amount'] = flt(flt(item['qty']) * rate, 2)
@@ -253,3 +272,45 @@ class StockEntry(Document):
253
272
  cost_center=cost_center, voucher_type=self.DOCTYPE, voucher_no=self.name,
254
273
  posting_date=self.posting_date, company=self.company, remarks=f'{self.stock_entry_type} via {self.name}')
255
274
  for account, value in amounts.items() if flt(value, 2)]
275
+
276
+
277
+ def make_location_move(warehouse, from_location, to_location, to_warehouse=None):
278
+ """A draft Material Transfer that moves everything in one storage location
279
+ to another: one row per item and batch found there. Nothing is posted
280
+ until the draft is submitted, and it posts completely or not at all.
281
+
282
+ `to_warehouse` defaults to the same warehouse (a move between locations).
283
+ """
284
+ from lambda_erp.stock.stock_ledger import get_stock_details, get_storage_location
285
+
286
+ db = get_db()
287
+ from_location = str(from_location or '').strip()
288
+ to_location = str(to_location or '').strip()
289
+ target_warehouse = to_warehouse or warehouse
290
+ if not db.exists('Warehouse', warehouse) or not db.exists('Warehouse', target_warehouse):
291
+ raise ValidationError('Warehouse not found')
292
+ if not flt(db.get_value('Warehouse', warehouse, 'use_locations')):
293
+ raise ValidationError(f'Warehouse {warehouse} does not use storage locations')
294
+ if not get_storage_location(warehouse, from_location):
295
+ raise ValidationError(f'Unknown storage location {from_location} in warehouse {warehouse}')
296
+ target_uses = flt(db.get_value('Warehouse', target_warehouse, 'use_locations'))
297
+ if target_uses and not get_storage_location(target_warehouse, to_location):
298
+ raise ValidationError(f'Unknown storage location {to_location} in warehouse {target_warehouse}')
299
+ if not target_uses and to_location:
300
+ raise ValidationError(f'Warehouse {target_warehouse} does not use storage locations')
301
+ if target_warehouse == warehouse and from_location == to_location:
302
+ raise ValidationError('Source and target storage location are the same')
303
+ rows = [row for row in get_stock_details(warehouse=warehouse, location=from_location)
304
+ if flt(row['actual_qty']) > 0]
305
+ if not rows:
306
+ raise ValidationError(f'Storage location {from_location} in warehouse {warehouse} is empty')
307
+ entry = StockEntry(company=db.get_value('Warehouse', warehouse, 'company'),
308
+ stock_entry_type='Material Transfer', posting_date=nowdate(),
309
+ from_warehouse=warehouse, to_warehouse=target_warehouse)
310
+ for row in sorted(rows, key=lambda r: (r['item_code'], r['batch_no'])):
311
+ entry.append('items', _dict(
312
+ item_code=row['item_code'], qty=flt(row['actual_qty']),
313
+ s_warehouse=warehouse, t_warehouse=target_warehouse,
314
+ s_location=from_location, t_location=to_location or None,
315
+ batch_no=row['batch_no'] or None))
316
+ return entry
@@ -47,6 +47,7 @@ def make_sl_entries(sl_entries, allow_negative_stock=False):
47
47
  continue
48
48
 
49
49
  batch_no = resolve_entry_batch(sle)
50
+ location = resolve_entry_location(sle)
50
51
 
51
52
  # Create the SLE record
52
53
  sle_doc = _dict(
@@ -62,6 +63,7 @@ def make_sl_entries(sl_entries, allow_negative_stock=False):
62
63
  voucher_no=sle.get("voucher_no"),
63
64
  voucher_detail_no=sle.get("voucher_detail_no"),
64
65
  batch_no=batch_no or None,
66
+ location=location or None,
65
67
  serial_no=sle.get("serial_no"),
66
68
  company=sle.get("company"),
67
69
  is_cancelled=0,
@@ -81,7 +83,7 @@ def make_sl_entries(sl_entries, allow_negative_stock=False):
81
83
 
82
84
  # Update Bin (summary table) and the per-batch quantity under it
83
85
  update_bin(sle_doc)
84
- update_stock_balance_detail(sle_doc, batch_no, allow_negative_stock)
86
+ update_stock_balance_detail(sle_doc, batch_no, allow_negative_stock, location)
85
87
 
86
88
  if not db._in_transaction:
87
89
  db.commit()
@@ -98,7 +100,11 @@ def make_cancel_sl_entries(sl_entries):
98
100
  # A voucher posted before its item became batch-tracked has no batch on
99
101
  # its lines; its reversal goes back to (or comes out of) stock without a
100
102
  # batch, never to an invented one.
101
- sl_entries = [sle if sle.get("batch_no") else _dict({**sle, "allow_unassigned_batch": True})
103
+ # The same holds for storage locations, and a reversal may put stock back
104
+ # into a location that has been disabled since.
105
+ sl_entries = [_dict({**sle, "is_reversal": True,
106
+ "allow_unassigned_batch": not sle.get("batch_no"),
107
+ "allow_unassigned_location": not sle.get("location")})
102
108
  for sle in sl_entries]
103
109
  try:
104
110
  make_sl_entries(sl_entries, allow_negative_stock=False)
@@ -188,37 +194,96 @@ def resolve_entry_batch(sle):
188
194
  return batch_no
189
195
 
190
196
 
191
- def update_stock_balance_detail(sle, batch_no, allow_negative_stock=False):
192
- """Apply an entry to the quantity of its item x warehouse x batch.
197
+ def get_storage_location(warehouse, location):
198
+ """The Storage Location master row for (warehouse, label), or None."""
199
+ return get_db().get_value(
200
+ "Storage Location", {"warehouse": warehouse, "location": location},
201
+ ["name", "location", "warehouse", "disabled"])
202
+
203
+
204
+ def resolve_entry_location(sle):
205
+ """Check one stock ledger entry's storage location against its warehouse
206
+ and return the label ('' when the entry carries none).
193
207
 
194
- This is where a batch cannot be over-drawn: 2 of batch A and 8 of batch B
195
- is 10 in the Bin, but an issue of 3 from A is refused. For stock without a
196
- batch the row mirrors the Bin."""
208
+ - a warehouse that does not use locations takes none;
209
+ - a warehouse that uses them needs one on every movement (the explicit
210
+ exceptions are the reversal of a voucher from before, and the source
211
+ side of a move within the warehouse: that is how stock without a
212
+ location is put away);
213
+ - the location must exist in that warehouse, and a disabled location
214
+ takes no new stock.
215
+ """
216
+ db = get_db()
217
+ warehouse = sle["warehouse"]
218
+ location = str(sle.get("location") or "").strip()
219
+ uses = flt(db.get_value("Warehouse", warehouse, "use_locations"))
220
+ if not uses:
221
+ if location:
222
+ raise ValidationError(
223
+ f"Warehouse {warehouse} does not use storage locations: remove location {location} "
224
+ f"from the line, or switch the warehouse to storage locations first")
225
+ return ""
226
+ if not location:
227
+ if sle.get("allow_unassigned_location"):
228
+ return ""
229
+ raise ValidationError(
230
+ f"Storage location is required in warehouse {warehouse} (item {sle['item_code']})")
231
+ row = get_storage_location(warehouse, location)
232
+ if not row:
233
+ raise ValidationError(f"Unknown storage location {location} in warehouse {warehouse}")
234
+ if flt(sle["actual_qty"]) > 0 and row.get("disabled") and not sle.get("is_reversal"):
235
+ raise ValidationError(f"Storage location {location} in warehouse {warehouse} is disabled: no stock can be put there")
236
+ return location
237
+
238
+
239
+ def update_stock_balance_detail(sle, batch_no, allow_negative_stock=False, location=""):
240
+ """Apply an entry to the quantity of its item x warehouse x batch x location.
241
+
242
+ This is where a batch or a location cannot be over-drawn: 2 of batch A and
243
+ 8 of batch B is 10 in the Bin, but an issue of 3 from A is refused. For
244
+ stock without a batch and location the row mirrors the Bin."""
197
245
  import uuid
198
246
 
199
247
  db = get_db()
200
- key = [sle["item_code"], sle["warehouse"], batch_no]
201
- db.sql('INSERT INTO "Stock Balance Detail" (name, item_code, warehouse, batch_no, actual_qty) '
202
- 'VALUES (?, ?, ?, ?, 0) ON CONFLICT DO NOTHING', [uuid.uuid4().hex, *key])
248
+ key = [sle["item_code"], sle["warehouse"], batch_no, location]
249
+ db.sql('INSERT INTO "Stock Balance Detail" (name, item_code, warehouse, batch_no, location, actual_qty) '
250
+ 'VALUES (?, ?, ?, ?, ?, 0) ON CONFLICT DO NOTHING', [uuid.uuid4().hex, *key])
203
251
  lock = ' FOR UPDATE' if db.dialect == 'postgres' else ''
204
252
  row = db.sql('SELECT name, actual_qty FROM "Stock Balance Detail" '
205
- 'WHERE item_code = ? AND warehouse = ? AND batch_no = ?' + lock, key)[0]
253
+ 'WHERE item_code = ? AND warehouse = ? AND batch_no = ? AND location = ?' + lock, key)[0]
206
254
  available = flt(row["actual_qty"])
207
255
  new_qty = available + flt(sle["actual_qty"])
208
256
  if new_qty < -1e-9 and not allow_negative_stock:
209
257
  what = f"batch {batch_no} of item" if batch_no else "stock without a batch of item"
258
+ where = f"warehouse {sle['warehouse']}"
259
+ if location:
260
+ where = f"storage location {location} of {where}"
261
+ elif flt(db.get_value("Warehouse", sle["warehouse"], "use_locations")):
262
+ where = f"{where} without a storage location"
210
263
  raise NegativeStockError(
211
- f"Not enough of {what} {sle['item_code']} in warehouse {sle['warehouse']}. "
264
+ f"Not enough of {what} {sle['item_code']} in {where}. "
212
265
  f"Available: {available}, requested: {abs(flt(sle['actual_qty']))}")
213
266
  db.set_value("Stock Balance Detail", row["name"], "actual_qty", flt(new_qty))
214
267
 
215
268
 
216
- def get_batch_balances(item_code=None, warehouse=None, batch_no=None):
217
- """Quantities per item x warehouse x batch (batch_no '' = without batch)."""
269
+ def get_stock_details(item_code=None, warehouse=None, batch_no=None, location=None):
270
+ """Quantities per item x warehouse x batch x location ('' = without)."""
218
271
  filters = {key: value for key, value in
219
- (("item_code", item_code), ("warehouse", warehouse), ("batch_no", batch_no)) if value is not None}
272
+ (("item_code", item_code), ("warehouse", warehouse), ("batch_no", batch_no), ("location", location))
273
+ if value is not None}
220
274
  return get_db().get_all("Stock Balance Detail", filters=filters or None,
221
- fields=["item_code", "warehouse", "batch_no", "actual_qty"])
275
+ fields=["item_code", "warehouse", "batch_no", "location", "actual_qty"])
276
+
277
+
278
+ def get_batch_balances(item_code=None, warehouse=None, batch_no=None):
279
+ """Quantities per item x warehouse x batch (batch_no '' = without batch),
280
+ added up over the storage locations of the warehouse."""
281
+ totals = {}
282
+ for row in get_stock_details(item_code, warehouse, batch_no):
283
+ key = (row["item_code"], row["warehouse"], row["batch_no"])
284
+ totals[key] = totals.get(key, 0) + flt(row["actual_qty"])
285
+ return [_dict(item_code=key[0], warehouse=key[1], batch_no=key[2], actual_qty=qty)
286
+ for key, qty in sorted(totals.items())]
222
287
 
223
288
 
224
289
  def stock_ledger_agreement():
@@ -230,17 +295,19 @@ def stock_ledger_agreement():
230
295
  db = get_db()
231
296
  problems = []
232
297
  ledger, detail = {}, {}
233
- for row in db.sql('SELECT item_code, warehouse, COALESCE(batch_no, \'\') AS batch_no, SUM(actual_qty) AS qty '
234
- 'FROM "Stock Ledger Entry" GROUP BY item_code, warehouse, COALESCE(batch_no, \'\')'):
235
- ledger[(row["item_code"], row["warehouse"], row["batch_no"])] = flt(row["qty"])
236
- for row in db.sql('SELECT item_code, warehouse, batch_no, actual_qty FROM "Stock Balance Detail"'):
237
- detail[(row["item_code"], row["warehouse"], row["batch_no"])] = flt(row["actual_qty"])
298
+ for row in db.sql('SELECT item_code, warehouse, COALESCE(batch_no, \'\') AS batch_no, '
299
+ 'COALESCE(location, \'\') AS location, SUM(actual_qty) AS qty '
300
+ 'FROM "Stock Ledger Entry" '
301
+ 'GROUP BY item_code, warehouse, COALESCE(batch_no, \'\'), COALESCE(location, \'\')'):
302
+ ledger[(row["item_code"], row["warehouse"], row["batch_no"], row["location"])] = flt(row["qty"])
303
+ for row in db.sql('SELECT item_code, warehouse, batch_no, location, actual_qty FROM "Stock Balance Detail"'):
304
+ detail[(row["item_code"], row["warehouse"], row["batch_no"], row["location"])] = flt(row["actual_qty"])
238
305
  for key in sorted(set(ledger) | set(detail)):
239
306
  if abs(ledger.get(key, 0) - detail.get(key, 0)) > 1e-6:
240
- problems.append({"item_code": key[0], "warehouse": key[1], "batch_no": key[2],
307
+ problems.append({"item_code": key[0], "warehouse": key[1], "batch_no": key[2], "location": key[3],
241
308
  "ledger_qty": ledger.get(key, 0), "detail_qty": detail.get(key, 0)})
242
309
  totals = {}
243
- for (item, warehouse, _), qty in detail.items():
310
+ for (item, warehouse, _, _), qty in detail.items():
244
311
  totals[(item, warehouse)] = totals.get((item, warehouse), 0) + qty
245
312
  bins = {(row["item_code"], row["warehouse"]): flt(row["actual_qty"])
246
313
  for row in db.sql('SELECT item_code, warehouse, actual_qty FROM "Bin"')}
@@ -401,6 +468,7 @@ def build_sell_side_sles(doc, items):
401
468
  voucher_no=doc.name,
402
469
  voucher_detail_no=item.get("name"),
403
470
  batch_no=item.get("batch_no"),
471
+ location=item.get("location"),
404
472
  posting_date=doc.posting_date,
405
473
  company=doc.company,
406
474
  ))
@@ -436,6 +504,7 @@ def build_buy_side_sles(doc, items):
436
504
  voucher_detail_no=item.get("name"),
437
505
  batch_no=item.get("batch_no"),
438
506
  expiry_date=item.get("expiry_date"),
507
+ location=item.get("location"),
439
508
  posting_date=doc.posting_date,
440
509
  company=doc.company,
441
510
  ))
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "lambda-erp"
3
- version = "1.4.6"
3
+ version = "1.4.7"
4
4
  description = "Core ERP logic - accounting, sales, purchasing, inventory"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes