lambda-erp 1.4.11__tar.gz → 1.4.12__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 (133) hide show
  1. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/PKG-INFO +1 -1
  2. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/chat.py +20 -1
  3. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/pdf_contract.py +6 -2
  4. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/pdf_profiles.py +5 -0
  5. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/masters.py +4 -0
  6. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/reports.py +93 -0
  7. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/services.py +3 -0
  8. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/stock_actions.py +31 -0
  9. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/frontend/src/api/client.ts +6 -0
  10. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/database.py +67 -0
  11. lambda_erp-1.4.12/lambda_erp/stock/stock_count.py +252 -0
  12. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/stock/stock_ledger.py +39 -0
  13. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/pyproject.toml +1 -1
  14. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/.gitignore +0 -0
  15. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/LICENSE +0 -0
  16. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/README.md +0 -0
  17. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/__init__.py +0 -0
  18. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/attachments.py +0 -0
  19. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/auth.py +0 -0
  20. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/bootstrap.py +0 -0
  21. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/chat_links.py +0 -0
  22. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/demo_limits.py +0 -0
  23. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/deps.py +0 -0
  24. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/erp_context.py +0 -0
  25. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/errors.py +0 -0
  26. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/list_values.py +0 -0
  27. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/llm_provider.py +0 -0
  28. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/main.py +0 -0
  29. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/mcp_oauth.py +0 -0
  30. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/mentions.py +0 -0
  31. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/menu_layout.py +0 -0
  32. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/oauth.py +0 -0
  33. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/pdf.py +0 -0
  34. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/pdf_exports.py +0 -0
  35. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/pdf_fonts.py +0 -0
  36. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/pdf_pages.py +0 -0
  37. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/pdf_templates.py +0 -0
  38. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/pricing_actions.py +0 -0
  39. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/providers.py +0 -0
  40. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/record_notes.py +0 -0
  41. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/remarks_md.py +0 -0
  42. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/__init__.py +0 -0
  43. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/accounting.py +0 -0
  44. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/actions.py +0 -0
  45. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/admin.py +0 -0
  46. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/analytics.py +0 -0
  47. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/availability.py +0 -0
  48. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/bank_reconciliation.py +0 -0
  49. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/bank_statements.py +0 -0
  50. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/chat_api.py +0 -0
  51. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/documents.py +0 -0
  52. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/mcp.py +0 -0
  53. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/pdf_templates.py +0 -0
  54. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/proposals.py +0 -0
  55. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/routers/setup.py +0 -0
  56. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/templates/_proposal_totals.html +0 -0
  57. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/templates/_record_base.html +0 -0
  58. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/templates/delivery_note.html +0 -0
  59. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/templates/document.html +0 -0
  60. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/templates/proposal.html +0 -0
  61. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/templates/record.html +0 -0
  62. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/templates/reservation.html +0 -0
  63. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/time_filters.py +0 -0
  64. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/tool_permissions.py +0 -0
  65. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/api/write_context.py +0 -0
  66. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/docs/agents/README.md +0 -0
  67. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/frontend/LICENSE +0 -0
  68. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/frontend/README.md +0 -0
  69. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/__init__.py +0 -0
  70. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/__init__.py +0 -0
  71. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/bank_account.py +0 -0
  72. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  73. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/bank_statement_import.py +0 -0
  74. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/bank_transaction.py +0 -0
  75. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/budget.py +0 -0
  76. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/camt.py +0 -0
  77. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  78. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/general_ledger.py +0 -0
  79. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/journal_entry.py +0 -0
  80. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/payment_entry.py +0 -0
  81. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/pos_invoice.py +0 -0
  82. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/purchase_invoice.py +0 -0
  83. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/revaluation.py +0 -0
  84. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/sales_invoice.py +0 -0
  85. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/settlement.py +0 -0
  86. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/__init__.py +0 -0
  87. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/engine.py +0 -0
  88. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/pack.py +0 -0
  89. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  90. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  91. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  92. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  93. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  94. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  95. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/profiles.py +0 -0
  96. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/setup/spine.py +0 -0
  97. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/accounting/subscription.py +0 -0
  98. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/assets/__init__.py +0 -0
  99. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/assets/asset.py +0 -0
  100. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/assets/lifecycle.py +0 -0
  101. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/assets/reservation.py +0 -0
  102. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/backlog.py +0 -0
  103. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/buying/__init__.py +0 -0
  104. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/buying/purchase_order.py +0 -0
  105. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/controllers/__init__.py +0 -0
  106. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/controllers/currency.py +0 -0
  107. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/controllers/defaults.py +0 -0
  108. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/controllers/item_price.py +0 -0
  109. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/controllers/item_prices.py +0 -0
  110. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/controllers/price_resolution.py +0 -0
  111. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/controllers/pricing_rule.py +0 -0
  112. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  113. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/exceptions.py +0 -0
  114. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/hooks.py +0 -0
  115. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/master_integrity.py +0 -0
  116. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/model.py +0 -0
  117. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/permissions.py +0 -0
  118. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/selling/__init__.py +0 -0
  119. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/selling/proposal.py +0 -0
  120. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/selling/quotation.py +0 -0
  121. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/selling/sales_order.py +0 -0
  122. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/simulation.py +0 -0
  123. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/stock/__init__.py +0 -0
  124. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/stock/consignment.py +0 -0
  125. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/stock/delivery_note.py +0 -0
  126. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/stock/purchase_receipt.py +0 -0
  127. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/stock/reservation.py +0 -0
  128. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/stock/stock_entry.py +0 -0
  129. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/timestamps.py +0 -0
  130. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/utils.py +0 -0
  131. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/validation.py +0 -0
  132. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/lambda_erp/workflow.py +0 -0
  133. {lambda_erp-1.4.11 → lambda_erp-1.4.12}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.11
3
+ Version: 1.4.12
4
4
  Summary: Core ERP logic - accounting, sales, purchasing, inventory
5
5
  Author: TORUS INVESTMENTS AG
6
6
  License-Expression: Apache-2.0
@@ -878,7 +878,7 @@ TOOLS = [
878
878
  "parameters": {
879
879
  "type": "object",
880
880
  "properties": {
881
- "report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "stock-availability", "stock-detail", "batch-stock", "batch-movements", "sales-backlog", "purchase-backlog", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
881
+ "report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "stock-availability", "stock-detail", "batch-stock", "batch-movements", "batch-recipients", "batch-changes", "sales-backlog", "purchase-backlog", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
882
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"],
@@ -1994,6 +1994,16 @@ def _handle_get_report(args):
1994
1994
  filters.get("expiring_before"), filters.get("expiring_after"),
1995
1995
  bool(filters.get("include_empty")), filters.get("consignment_customer"),
1996
1996
  None if consignment is None else bool(consignment))
1997
+ elif report_type == "batch-recipients":
1998
+ from api.routers.reports import _batch_recipients
1999
+ if not filters.get("batch_no"):
2000
+ return {"error": "batch-recipients needs filters.batch_no"}
2001
+ return _batch_recipients(db, filters.get("batch_no"), filters.get("item_code"))
2002
+ elif report_type == "batch-changes":
2003
+ from api.routers.reports import _batch_changes
2004
+ if not filters.get("batch_no") and not filters.get("item_code"):
2005
+ return {"error": "batch-changes needs filters.batch_no or filters.item_code"}
2006
+ return _batch_changes(db, filters.get("batch_no"), filters.get("item_code"))
1997
2007
  elif report_type == "batch-movements":
1998
2008
  from api.routers.reports import _batch_movements
1999
2009
  if not filters.get("batch_no"):
@@ -2929,6 +2939,13 @@ For a complete sales return (financial + stock): create and submit both a Credit
2929
2939
  - **Material Transfer:** Moves stock between warehouses. No GL impact.
2930
2940
  - **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.
2931
2941
 
2942
+ ### Stock counts (inventory)
2943
+ - A **Stock Count** (doctype `stock-count`) covers one warehouse. Create the draft with the `prepare_stock_count` action; it lists system_qty per item, batch and storage location. Enter `counted_qty` on the lines that were counted (leave it empty on lines that were not) with update_document; add a line for stock the system does not list.
2944
+ - Saving a draft changes NO stock. Submitting posts counted_qty − system_qty per line and requires `reason`. If stock moved since the count was prepared, submitting is refused: refresh with prepare_stock_count(stock_count=…) and have the lines checked again.
2945
+ - When someone tells you what they counted, put it on the draft and report the differences (difference_qty). Do not submit a count unless the user explicitly asks to post it and may do so.
2946
+ - A count corrects quantities from now on. It never changes earlier delivery notes or invoices; do not use it to record where goods are believed to have gone.
2947
+ - Use a Stock Count, not Material Receipt / Issue, when the reason is "what is there differs from what the system says".
2948
+
2932
2949
  ### Consignment (own stock lying at a customer)
2933
2950
  - A **consignment warehouse** is a warehouse with `consignment_customer` set. The goods in it are still ours (in stock and stock value) until the customer uses them.
2934
2951
  - **Stocking** (sending goods to the customer's consignment stock) is NOT a sale and gets NO invoice: use the `prepare_consignment_stocking` action (warehouse, items) to draft the Material Transfer, review it, then submit it.
@@ -3036,6 +3053,8 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
3036
3053
  - **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".
3037
3054
  - **stock-detail** — Where stock is, in one view: item, warehouse, consignment_customer (who it lies with, for consignment warehouses), storage location, batch, expiry date, quantity. Filters: item_code, warehouse, location, batch_no, item_prefix, item_group, expiring_before, expiring_after, include_empty, consignment_customer (one customer's consignment stock), consignment (true = only consignment, false = only own warehouses). Use this for "what is in location B4", "where is item X", "what expires in the next 3 months in warehouse Y".
3038
3055
  - **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.
3056
+ - **batch-recipients** — Who has a batch (recall): one row per customer with delivered_qty, returned_qty, net_qty and the documents; `in_stock` says where the rest lies now (with the customer for consignment stock); `suppliers` where it came from. Filters: batch_no (required), item_code. Use this for "who received lot X" instead of adding up movements yourself.
3057
+ - **batch-changes** — Recorded changes of a batch's expiry date and block (old value, new value, who, when). Filters: batch_no and/or item_code.
3039
3058
  - **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.
3040
3059
  - **dashboard-summary** — KPI overview (revenue, receivables, payables, stock value).
3041
3060
  - **Custom analytics drafts** — reserved for when the user **explicitly asks
@@ -190,13 +190,17 @@ def prepare(doctype, doc):
190
190
  number(row[key], f'{table.key}[{i}].{key}')
191
191
  if table.key in {'items', 'plans'}:
192
192
  _item(row, tokens, i)
193
- _quantity(row, f'{table.key}[{i}].qty', bool(doc.get('is_return')))
193
+ # A count sheet has an expected and a counted quantity (which
194
+ # may be empty or zero), not a line quantity.
195
+ if doctype != 'Stock Count':
196
+ _quantity(row, f'{table.key}[{i}].qty', bool(doc.get('is_return')))
194
197
  if doctype in {'Delivery Note', 'Purchase Receipt'}:
195
198
  if row.get('item_code') and get_db().get_value('Item', row['item_code'], 'is_stock_item'):
196
199
  require(row, ('warehouse',), f'{table.key}[{i}].')
197
200
  if doctype == 'Stock Entry':
198
201
  movement = doc['stock_entry_type']
199
- if movement not in {'Material Receipt', 'Opening Stock', 'Material Issue', 'Material Transfer'}:
202
+ if movement not in {'Material Receipt', 'Opening Stock', 'Material Issue', 'Material Transfer',
203
+ 'Batch Assignment'}:
200
204
  raise PDFError('PDF requires a supported stock_entry_type')
201
205
  keys = ('s_warehouse', 't_warehouse') if movement == 'Material Transfer' else ('s_warehouse',) if movement == 'Material Issue' else ('t_warehouse',)
202
206
  require(row, keys, f'items[{i}].')
@@ -82,6 +82,11 @@ 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 Count': PDFProfile('record', 'Stock count sheet',
86
+ fields=('company', 'warehouse', 'posting_date', 'reason', 'remarks'),
87
+ required=('warehouse', 'posting_date', 'items'),
88
+ tables=(PDFTable('items', ('location', 'item_code', 'item_name', 'batch_no', 'expiry_date', 'system_qty', 'counted_qty'),
89
+ ('item_code',), True),)),
85
90
  'Consignment Withdrawal': PDFProfile('record', 'Consignment withdrawal',
86
91
  fields=('company', 'customer', 'warehouse', 'posting_date', 'external_reference', 'sales_invoice', 'remarks'),
87
92
  required=('customer', 'warehouse', 'posting_date', 'items'),
@@ -509,6 +509,10 @@ def _update_master_record(master_type: str, name: str, data: dict) -> dict:
509
509
  update_fields["modified"] = now()
510
510
  if update_fields:
511
511
  db.set_value(doctype, name, update_fields)
512
+ if master_type == 'batch':
513
+ # A batch's expiry date and block decide what may be sold: keep the trail.
514
+ from lambda_erp.stock.stock_ledger import log_batch_changes
515
+ log_batch_changes(name, stored, update_fields, 'Batch master')
512
516
 
513
517
  rows = db.get_all(doctype, filters={"name": name}, fields=["*"])
514
518
  if not rows:
@@ -602,6 +602,99 @@ def _batch_movements(db, batch_no=None, item_code=None, warehouse=None):
602
602
  return {"rows": result}
603
603
 
604
604
 
605
+ def _batch_recipients(db, batch_no=None, item_code=None):
606
+ """Who has a batch: one row per customer it was delivered to (delivered,
607
+ returned and what they still have of it), where the rest lies now
608
+ (`in_stock`, with the customer for consignment stock) and which suppliers
609
+ it came from (`suppliers`). The first thing a recall needs."""
610
+ permissions.require_artifact("report", "batch-recipients")
611
+ if not batch_no:
612
+ raise HTTPException(status_code=422, detail="batch_no is required")
613
+ where, params = ["s.batch_no = ?"], [batch_no]
614
+ if item_code:
615
+ where.append("s.item_code = ?")
616
+ params.append(item_code)
617
+ rows = db.sql(
618
+ 'SELECT s.item_code, s.posting_date, s.actual_qty, s.voucher_type, s.voucher_no '
619
+ f'FROM "Stock Ledger Entry" s WHERE {" AND ".join(where)} ORDER BY s.posting_date, s.creation, s.name', params)
620
+ parties, recipients, suppliers = {}, {}, {}
621
+ for row in rows:
622
+ field = _BATCH_PARTY.get(row["voucher_type"])
623
+ if not field:
624
+ continue
625
+ key = (row["voucher_type"], row["voucher_no"])
626
+ if key not in parties:
627
+ parties[key] = db.get_value(row["voucher_type"], row["voucher_no"], field[0])
628
+ party, qty = parties[key], flt(row["actual_qty"])
629
+ if not party:
630
+ continue
631
+ target = recipients if field[1] == "Customer" else suppliers
632
+ entry = target.setdefault((row["item_code"], party), {
633
+ "item_code": row["item_code"], field[0]: party, "out_qty": 0.0, "in_qty": 0.0,
634
+ "first_date": row["posting_date"], "last_date": row["posting_date"], "documents": []})
635
+ if qty < 0:
636
+ entry["out_qty"] += -qty
637
+ else:
638
+ entry["in_qty"] += qty
639
+ entry["last_date"] = row["posting_date"]
640
+ if row["voucher_no"] not in entry["documents"]:
641
+ entry["documents"].append(row["voucher_no"])
642
+
643
+ def named(table, field, party):
644
+ return db.get_value(table, party, field) or party
645
+
646
+ delivered = [{
647
+ "item_code": e["item_code"], "customer": e["customer"],
648
+ "customer_name": named("Customer", "customer_name", e["customer"]),
649
+ "delivered_qty": e["out_qty"], "returned_qty": e["in_qty"], "net_qty": e["out_qty"] - e["in_qty"],
650
+ "first_date": e["first_date"], "last_date": e["last_date"], "documents": e["documents"]}
651
+ for e in recipients.values()]
652
+ delivered.sort(key=lambda r: (r["item_code"], -r["net_qty"], r["customer"]))
653
+ result = {"rows": delivered}
654
+ stock_where, stock_params = ["d.batch_no = ?", "d.actual_qty <> 0"], [batch_no]
655
+ if item_code:
656
+ stock_where.append("d.item_code = ?")
657
+ stock_params.append(item_code)
658
+ result["in_stock"] = [{**dict(r), "actual_qty": flt(r["actual_qty"])} for r in db.sql(
659
+ 'SELECT d.item_code, d.warehouse, w.consignment_customer, d.location, d.actual_qty '
660
+ 'FROM "Stock Balance Detail" d LEFT JOIN "Warehouse" w ON w.name = d.warehouse '
661
+ f'WHERE {" AND ".join(stock_where)} ORDER BY d.item_code, d.warehouse, d.location', stock_params)]
662
+ if permissions.can("Supplier", "read"):
663
+ result["suppliers"] = [{
664
+ "item_code": e["item_code"], "supplier": e["supplier"],
665
+ "supplier_name": named("Supplier", "supplier_name", e["supplier"]),
666
+ "received_qty": e["in_qty"], "returned_qty": e["out_qty"], "documents": e["documents"]}
667
+ for e in suppliers.values()]
668
+ return result
669
+
670
+
671
+ @router.get("/batch-recipients")
672
+ def batch_recipients(batch_no: str, item_code: str | None = None):
673
+ return _batch_recipients(get_db(), batch_no, item_code)
674
+
675
+
676
+ def _batch_changes(db, batch_no=None, item_code=None):
677
+ """The recorded changes of a batch's expiry date and block: what it was,
678
+ what it became, who changed it and when."""
679
+ permissions.require_artifact("report", "batch-changes")
680
+ where, params = [], []
681
+ for column, value in (("batch_no", batch_no), ("item_code", item_code)):
682
+ if value:
683
+ where.append(f"{column} = ?")
684
+ params.append(value)
685
+ if not where:
686
+ raise HTTPException(status_code=422, detail="batch_no or item_code is required")
687
+ rows = db.sql(
688
+ 'SELECT batch, item_code, batch_no, field, old_value, new_value, changed_by, changed_at, source '
689
+ f'FROM "Batch Change" WHERE {" AND ".join(where)} ORDER BY changed_at, name', params)
690
+ return {"rows": [dict(row) for row in rows]}
691
+
692
+
693
+ @router.get("/batch-changes")
694
+ def batch_changes(batch_no: str | None = None, item_code: str | None = None):
695
+ return _batch_changes(get_db(), batch_no, item_code)
696
+
697
+
605
698
  @router.get("/batch-movements")
606
699
  def batch_movements(
607
700
  batch_no: str,
@@ -35,6 +35,7 @@ from lambda_erp.assets.asset import Asset
35
35
  from lambda_erp.assets.reservation import Reservation
36
36
  from lambda_erp.stock.reservation import StockReservation
37
37
  from lambda_erp.stock.consignment import ConsignmentWithdrawal
38
+ from lambda_erp.stock.stock_count import StockCount
38
39
 
39
40
 
40
41
  # --- Doctype registries ---
@@ -68,6 +69,8 @@ DOCUMENT_CLASSES = {
68
69
  "Stock Reservation": StockReservation,
69
70
  # What a customer reported as used from their consignment warehouse.
70
71
  "Consignment Withdrawal": ConsignmentWithdrawal,
72
+ # Counted quantities; submitting books the differences with a reason.
73
+ "Stock Count": StockCount,
71
74
  }
72
75
 
73
76
  CONVERTERS = {
@@ -52,6 +52,28 @@ def suggest(args):
52
52
  sales_order_item=data.sales_order_item, include_short_dated=data.include_short_dated)
53
53
 
54
54
 
55
+ class PrepareCount(mentions.Input):
56
+ warehouse: str = Field(min_length=1, max_length=200)
57
+ location: str | None = Field(default=None, max_length=200)
58
+ item_code: str | None = Field(default=None, max_length=200)
59
+ item_prefix: str | None = Field(default=None, max_length=200)
60
+ stock_count: str | None = Field(default=None, max_length=200)
61
+
62
+
63
+ def prepare_count(args):
64
+ data = PrepareCount.model_validate(args)
65
+ from lambda_erp.stock.stock_count import prepare_stock_count
66
+ if data.stock_count:
67
+ permissions.require_writable("Stock Count", "update")
68
+ permissions.require_readable("Stock Count", data.stock_count)
69
+ else:
70
+ permissions.require_writable("Stock Count", "create")
71
+ doc = prepare_stock_count(data.warehouse, location=data.location, item_code=data.item_code,
72
+ item_prefix=data.item_prefix, stock_count=data.stock_count)
73
+ doc.save()
74
+ return services.load_document("stock-count", doc.name)
75
+
76
+
55
77
  class ConsignmentLine(mentions.Input):
56
78
  item_code: str = Field(min_length=1, max_length=200)
57
79
  qty: float | None = Field(default=None, gt=0)
@@ -141,6 +163,15 @@ def confirm_purchase_order(args, user=None):
141
163
 
142
164
 
143
165
  def initialize_stock_actions():
166
+ services.register_action(
167
+ "prepare_stock_count", prepare_count,
168
+ description=(
169
+ "Create a DRAFT Stock Count for a warehouse (an own one or a customer's consignment warehouse) with one "
170
+ "line per item, batch and storage location and the quantity the system expects (system_qty); optionally "
171
+ "only one location, one item_code or an item_prefix. The counter then enters counted_qty per line with "
172
+ "update_document. Saving changes no stock; submitting posts the differences and needs a reason. With "
173
+ "stock_count (an existing draft) it refreshes the system quantities instead and keeps what was counted."),
174
+ parameters=PrepareCount.model_json_schema(), minimum_role="manager")
144
175
  services.register_action(
145
176
  "record_consignment_withdrawal", record_consignment_withdrawal,
146
177
  description=(
@@ -583,6 +583,12 @@ export const api = {
583
583
  batchMovements: (params: Record<string, string>) =>
584
584
  request<{ rows: any[] }>(`/reports/batch-movements${qs(params)}`),
585
585
 
586
+ batchRecipients: (params: Record<string, string>) =>
587
+ request<{ rows: any[]; in_stock: any[]; suppliers?: any[] }>(`/reports/batch-recipients${qs(params)}`),
588
+
589
+ batchChanges: (params: Record<string, string>) =>
590
+ request<{ rows: any[] }>(`/reports/batch-changes${qs(params)}`),
591
+
586
592
  // --- Rentals: availability + fleet calendar ---
587
593
  availability: (params: { item_code: string; from: string; to: string; warehouse?: string; exclude?: string }) =>
588
594
  request<AvailabilityResult>(`/availability${qs(params)}`),
@@ -3436,6 +3436,71 @@ def _m057_consignment(db: "Database") -> None:
3436
3436
  db._text_col_cache.pop(table, None)
3437
3437
 
3438
3438
 
3439
+ def _m058_stock_count(db: "Database") -> None:
3440
+ """Stock Count: counted quantities per item, batch and storage location,
3441
+ posted as a correction with a reason (see docs/stock-counts.md)."""
3442
+ db.conn.execute(db._ddl(
3443
+ """CREATE TABLE IF NOT EXISTS "Stock Count" (
3444
+ name TEXT PRIMARY KEY,
3445
+ company TEXT,
3446
+ warehouse TEXT NOT NULL,
3447
+ posting_date TEXT,
3448
+ reason TEXT,
3449
+ remarks TEXT,
3450
+ counted_lines INTEGER DEFAULT 0,
3451
+ difference_lines INTEGER DEFAULT 0,
3452
+ status TEXT DEFAULT 'Draft',
3453
+ docstatus INTEGER DEFAULT 0,
3454
+ discarded INTEGER DEFAULT 0,
3455
+ creation TEXT,
3456
+ modified TEXT
3457
+ )"""))
3458
+ db.conn.execute(db._ddl(
3459
+ """CREATE TABLE IF NOT EXISTS "Stock Count Item" (
3460
+ name TEXT PRIMARY KEY,
3461
+ parent TEXT NOT NULL,
3462
+ idx INTEGER DEFAULT 0,
3463
+ item_code TEXT,
3464
+ item_name TEXT,
3465
+ warehouse TEXT,
3466
+ location TEXT,
3467
+ batch_no TEXT,
3468
+ expiry_date TEXT,
3469
+ system_qty REAL DEFAULT 0,
3470
+ counted_qty REAL,
3471
+ difference_qty REAL,
3472
+ remarks TEXT
3473
+ )"""))
3474
+ db.conn.execute(db._ddl(
3475
+ 'CREATE INDEX IF NOT EXISTS "ix_stock_count_item_parent" ON "Stock Count Item" (parent)'))
3476
+ db.conn.commit()
3477
+ for table in ("Stock Count", "Stock Count Item"):
3478
+ db._col_cache.pop(table, None)
3479
+ db._text_col_cache.pop(table, None)
3480
+
3481
+
3482
+ def _m059_batch_change_log(db: "Database") -> None:
3483
+ """Who changed a batch's expiry date or block, when, and from what
3484
+ (see docs/batches.md). Changes made before this migration are not known."""
3485
+ db.conn.execute(db._ddl(
3486
+ """CREATE TABLE IF NOT EXISTS "Batch Change" (
3487
+ name TEXT PRIMARY KEY,
3488
+ batch TEXT NOT NULL,
3489
+ item_code TEXT,
3490
+ batch_no TEXT,
3491
+ field TEXT NOT NULL,
3492
+ old_value TEXT,
3493
+ new_value TEXT,
3494
+ changed_by TEXT,
3495
+ changed_at TEXT,
3496
+ source TEXT
3497
+ )"""))
3498
+ db.conn.execute(db._ddl('CREATE INDEX IF NOT EXISTS "ix_batch_change_batch" ON "Batch Change" (batch)'))
3499
+ db.conn.commit()
3500
+ db._col_cache.pop("Batch Change", None)
3501
+ db._text_col_cache.pop("Batch Change", None)
3502
+
3503
+
3439
3504
  def _m052_access_profiles(db: "Database") -> None:
3440
3505
  """Access profiles narrow what a user's role allows (lambda_erp.permissions).
3441
3506
  No profile is created and no user is assigned one: nothing changes for
@@ -3533,6 +3598,8 @@ Database.MIGRATIONS = [
3533
3598
  (55, "price_decisions", _m055_price_decisions),
3534
3599
  (56, "order_progress", _m056_order_progress),
3535
3600
  (57, "consignment", _m057_consignment),
3601
+ (58, "stock_count", _m058_stock_count),
3602
+ (59, "batch_change_log", _m059_batch_change_log),
3536
3603
  ]
3537
3604
 
3538
3605
 
@@ -0,0 +1,252 @@
1
+ """Stock Count: compare what is there with what the system says, and correct
2
+ the difference with a reason.
3
+
4
+ prepare a draft for one warehouse lists what the system expects per
5
+ item, batch and storage location (system_qty)
6
+ count the counter enters counted_qty per line and saves the draft;
7
+ lines for stock the system does not know can be added
8
+ post submitting books the differences into the stock ledger, with
9
+ the count as the voucher and its reason on record
10
+
11
+ Counting and posting are separate on purpose. Saving a draft changes no
12
+ stock, so someone who may create and update a Stock Count but not submit it
13
+ can hand in a count without being able to correct stock.
14
+
15
+ A count corrects quantities from now on. It does not rewrite earlier
16
+ documents: where the goods went is not something a count can know.
17
+
18
+ The document carries quantities only, no cost: differences are valued at the
19
+ item's current moving-average cost in the warehouse.
20
+
21
+ See docs/stock-counts.md.
22
+ """
23
+ from lambda_erp.accounting.general_ledger import make_gl_entries, make_reverse_gl_entries
24
+ from lambda_erp.database import get_db
25
+ from lambda_erp.exceptions import ValidationError
26
+ from lambda_erp.model import Document
27
+ from lambda_erp.stock.stock_ledger import (
28
+ get_stock_details, make_cancel_sl_entries, make_sl_entries, reverse_stock_sles, stock_account_for,
29
+ )
30
+ from lambda_erp.utils import _dict, flt, nowdate
31
+
32
+ EPSILON = 1e-9
33
+
34
+
35
+ def _key(row):
36
+ return (row.get("item_code"), str(row.get("batch_no") or ""), str(row.get("location") or ""))
37
+
38
+
39
+ def _system_quantities(warehouse):
40
+ return {(row["item_code"], row["batch_no"] or "", row["location"] or ""): flt(row["actual_qty"])
41
+ for row in get_stock_details(warehouse=warehouse)}
42
+
43
+
44
+ class StockCount(Document):
45
+ DOCTYPE = "Stock Count"
46
+ SUBMITTABLE = True
47
+ CHILD_TABLES = {"items": ("Stock Count Item", None)}
48
+ PREFIX = "SCNT"
49
+ REQUIRED_FIELDS = ("warehouse", "items")
50
+ CHILD_REQUIREMENTS = {"items": {"required": ["item_code"]}}
51
+ CONDITIONAL_REQUIREMENTS = (
52
+ "One count covers one warehouse. Use the prepare_stock_count action to create the draft with a line per item, "
53
+ "batch and storage location and the quantity the system expects (system_qty).",
54
+ "Enter counted_qty on the lines that were counted and save; leave it empty on lines that were not counted "
55
+ "(they are not changed). Add a line for stock the system does not know (system_qty is filled in). A new batch "
56
+ "on such a line needs expiry_date when the item has expiry dates.",
57
+ "Saving a draft changes no stock. Submitting books counted_qty - system_qty per line into the stock ledger "
58
+ "and needs a reason. It is refused when stock on a counted line has moved since the count was prepared: "
59
+ "refresh the count (prepare_stock_count with stock_count) and check those lines again.",
60
+ "A count does not change earlier documents. Do not use it to record where goods are believed to have gone.",
61
+ )
62
+ LINK_FIELDS = {"warehouse": "Warehouse", "company": "Company"}
63
+ CHILD_LINK_FIELDS = {"items": {"item_code": "Item"}}
64
+
65
+ def validate(self):
66
+ db = get_db()
67
+ warehouse = db.get_value("Warehouse", self.warehouse, ["company", "is_group"]) if self.warehouse else None
68
+ if not warehouse or flt(warehouse.get("is_group")):
69
+ raise ValidationError("Stock Count: Warehouse must be a warehouse that holds stock")
70
+ self._data["company"] = warehouse.get("company")
71
+ if not self.posting_date:
72
+ self.posting_date = nowdate()
73
+ if not self.get("items"):
74
+ raise ValidationError("At least one item is required")
75
+ system = _system_quantities(self.warehouse)
76
+ seen = set()
77
+ counted = differences = 0
78
+ for idx, row in enumerate(self.get("items"), 1):
79
+ if not row.get("item_code"):
80
+ raise ValidationError(f"Stock Count row {idx}: Item Code is required")
81
+ item = db.get_value("Item", row["item_code"], ["item_name", "is_stock_item"])
82
+ if item and not flt(item.get("is_stock_item")):
83
+ raise ValidationError(f"Stock Count row {idx}: {row['item_code']} is not a stock item")
84
+ for field in ("batch_no", "location"):
85
+ row[field] = str(row.get(field) or "").strip() or None
86
+ key = _key(row)
87
+ if key in seen:
88
+ raise ValidationError(
89
+ f"Stock Count row {idx}: {row['item_code']}"
90
+ + (f" batch {row['batch_no']}" if row["batch_no"] else "")
91
+ + (f" at {row['location']}" if row["location"] else "") + " is listed twice")
92
+ seen.add(key)
93
+ row["warehouse"] = self.warehouse
94
+ if not row.get("item_name") and item:
95
+ row["item_name"] = item.get("item_name")
96
+ if row.get("system_qty") in (None, ""):
97
+ row["system_qty"] = system.get(key, 0.0) # a line added by hand
98
+ row["system_qty"] = flt(row["system_qty"])
99
+ if row.get("counted_qty") in (None, ""):
100
+ row["counted_qty"] = None
101
+ row["difference_qty"] = None
102
+ continue
103
+ try:
104
+ quantity = float(row["counted_qty"])
105
+ except (TypeError, ValueError):
106
+ raise ValidationError(f"Stock Count row {idx}: Counted Qty must be a number")
107
+ if quantity < 0 or quantity != quantity or quantity == float("inf"):
108
+ raise ValidationError(f"Stock Count row {idx}: Counted Qty cannot be negative")
109
+ row["counted_qty"] = quantity
110
+ row["difference_qty"] = quantity - row["system_qty"]
111
+ counted += 1
112
+ differences += 1 if abs(row["difference_qty"]) > EPSILON else 0
113
+ self._data["counted_lines"] = counted
114
+ self._data["difference_lines"] = differences
115
+
116
+ def before_submit(self):
117
+ if not str(self._data.get("reason") or "").strip():
118
+ raise ValidationError("Stock Count: a reason is required to post a count")
119
+ if not any(row.get("counted_qty") is not None for row in self.get("items")):
120
+ raise ValidationError("Stock Count: no line has a counted quantity")
121
+ system = _system_quantities(self.warehouse)
122
+ moved = []
123
+ for idx, row in enumerate(self.get("items"), 1):
124
+ if row.get("counted_qty") is None:
125
+ continue
126
+ now_there = system.get(_key(row), 0.0)
127
+ if abs(now_there - flt(row.get("system_qty"))) > EPSILON:
128
+ moved.append(f"row {idx} ({row['item_code']}"
129
+ + (f", batch {row['batch_no']}" if row.get("batch_no") else "")
130
+ + f": {flt(row.get('system_qty')):g} when prepared, {now_there:g} now)")
131
+ if moved:
132
+ raise ValidationError(
133
+ "Stock has moved since this count was prepared: " + "; ".join(moved)
134
+ + ". Refresh the count and check these lines again before posting")
135
+
136
+ def on_submit(self):
137
+ entries = []
138
+ for row in self.get("items"):
139
+ difference = flt(row.get("difference_qty")) if row.get("counted_qty") is not None else 0
140
+ if abs(difference) <= EPSILON:
141
+ continue
142
+ entries.append(_dict(
143
+ item_code=row["item_code"], warehouse=self.warehouse, actual_qty=difference,
144
+ # Valued at what the item costs here now; a count knows quantities, not prices.
145
+ incoming_rate=0, outgoing_rate=0,
146
+ batch_no=row.get("batch_no"), location=row.get("location"), expiry_date=row.get("expiry_date"),
147
+ # Stock without a batch / location (from before tracking) can be counted away, never added.
148
+ allow_unassigned_batch=difference < 0 and not row.get("batch_no"),
149
+ allow_unassigned_location=difference < 0 and not row.get("location"),
150
+ voucher_type=self.DOCTYPE, voucher_no=self.name, voucher_detail_no=row.get("name"),
151
+ posting_date=self.posting_date, company=self.company))
152
+ # Take out before putting in, so a correction between two batches or
153
+ # locations of one item never needs more than is there.
154
+ entries.sort(key=lambda entry: entry["actual_qty"] > 0)
155
+ if entries:
156
+ make_sl_entries(entries)
157
+ gl_entries = self._get_gl_entries()
158
+ if gl_entries:
159
+ make_gl_entries(gl_entries)
160
+ self._data["status"] = "Posted"
161
+ self._persist(commit=False)
162
+
163
+ def on_cancel(self):
164
+ rows = get_db().get_all("Stock Ledger Entry", filters={
165
+ "voucher_type": self.DOCTYPE, "voucher_no": self.name, "is_cancelled": 0}, fields=["*"])
166
+ reversals = reverse_stock_sles(rows)
167
+ for row in reversals:
168
+ # Reverse at the value that was posted, whatever the cost is now.
169
+ row["incoming_rate_is_explicit"] = True
170
+ row["outgoing_rate_is_explicit"] = True
171
+ # Put back before taking out again.
172
+ reversals.sort(key=lambda entry: entry["actual_qty"] < 0)
173
+ if reversals:
174
+ make_cancel_sl_entries(reversals)
175
+ make_reverse_gl_entries(voucher_type=self.DOCTYPE, voucher_no=self.name)
176
+
177
+ def _get_gl_entries(self):
178
+ """Stock account against the stock adjustment account, from the
179
+ values the stock ledger posted."""
180
+ db = get_db()
181
+ rows = db.sql('SELECT COALESCE(SUM(stock_value_difference), 0) AS value FROM "Stock Ledger Entry" '
182
+ 'WHERE voucher_type = ? AND voucher_no = ? AND is_cancelled = 0', [self.DOCTYPE, self.name])
183
+ value = flt(rows[0]["value"], 2) if rows else 0
184
+ if not value:
185
+ return []
186
+ account = stock_account_for(self.company, self.warehouse)
187
+ contra = db.get_value("Company", self.company, "stock_adjustment_account")
188
+ if not account or not contra:
189
+ raise ValidationError("A stock account and the company's stock adjustment account are required to post a count")
190
+ cost_center = db.get_value("Company", self.company, "default_cost_center")
191
+ common = dict(voucher_type=self.DOCTYPE, voucher_no=self.name, posting_date=self.posting_date,
192
+ company=self.company, cost_center=cost_center,
193
+ remarks=f"Stock count {self.name}: {self._data.get('reason')}")
194
+
195
+ def leg(name, amount):
196
+ return _dict(account=name, debit=max(0, amount), credit=max(0, -amount),
197
+ debit_in_account_currency=max(0, amount), credit_in_account_currency=max(0, -amount), **common)
198
+
199
+ return [leg(account, value), leg(contra, -value)]
200
+
201
+
202
+ def prepare_stock_count(warehouse, *, location=None, item_code=None, item_prefix=None, include_empty=False,
203
+ stock_count=None):
204
+ """A draft Stock Count for a warehouse with a line per item, batch and
205
+ storage location and the quantity the system expects, optionally limited
206
+ to one storage location, one item or item codes starting with a prefix.
207
+
208
+ With `stock_count`, refreshes that draft instead: system quantities are
209
+ brought up to date, counted quantities are kept, and stock the system
210
+ now knows but the draft did not list is added.
211
+ """
212
+ db = get_db()
213
+
214
+ def wanted(row):
215
+ if location is not None and (row["location"] or "") != (location or ""):
216
+ return False
217
+ if item_code and row["item_code"] != item_code:
218
+ return False
219
+ if item_prefix and not str(row["item_code"]).startswith(str(item_prefix)):
220
+ return False
221
+ return include_empty or abs(flt(row["actual_qty"])) > EPSILON
222
+
223
+ if stock_count:
224
+ doc = StockCount.load(stock_count)
225
+ if doc.docstatus != 0 or doc.get("discarded"):
226
+ raise ValidationError("Only a draft count can be refreshed")
227
+ system = _system_quantities(doc.warehouse)
228
+ listed = set()
229
+ for row in doc.get("items"):
230
+ row["system_qty"] = system.get(_key(row), 0.0)
231
+ listed.add(_key(row))
232
+ scoped = bool(location is not None or item_code or item_prefix)
233
+ for row in get_stock_details(warehouse=doc.warehouse):
234
+ key = (row["item_code"], row["batch_no"] or "", row["location"] or "")
235
+ if key not in listed and abs(flt(row["actual_qty"])) > EPSILON and (not scoped or wanted(row)):
236
+ doc.append("items", _dict(item_code=row["item_code"], batch_no=row["batch_no"] or None,
237
+ location=row["location"] or None, system_qty=flt(row["actual_qty"])))
238
+ return doc
239
+
240
+ if not db.exists("Warehouse", warehouse):
241
+ raise ValidationError(f"Warehouse {warehouse} not found")
242
+ rows = [row for row in get_stock_details(warehouse=warehouse) if wanted(row)]
243
+ if not rows:
244
+ raise ValidationError(f"There is no stock to count in warehouse {warehouse} for this selection")
245
+ doc = StockCount(warehouse=warehouse, posting_date=nowdate())
246
+ for row in sorted(rows, key=lambda r: (r["location"] or "", r["item_code"], r["batch_no"] or "")):
247
+ expiry = db.get_value("Batch", {"item_code": row["item_code"], "batch_no": row["batch_no"]}, "expiry_date") \
248
+ if row["batch_no"] else None
249
+ doc.append("items", _dict(item_code=row["item_code"], batch_no=row["batch_no"] or None,
250
+ location=row["location"] or None, expiry_date=expiry,
251
+ system_qty=flt(row["actual_qty"])))
252
+ return doc
@@ -135,6 +135,43 @@ def get_batch(item_code, batch_no):
135
135
  ["name", "batch_no", "item_code", "expiry_date", "disabled"])
136
136
 
137
137
 
138
+ AUDITED_BATCH_FIELDS = ("expiry_date", "blocked", "blocked_reason", "disabled")
139
+
140
+
141
+ def log_batch_changes(batch_name, before, after, source):
142
+ """Keep who changed a batch's expiry date or block, when, and from what.
143
+ `before` / `after` are the batch's values; only audited fields that
144
+ differ are recorded."""
145
+ import uuid
146
+
147
+ db = get_db()
148
+ if not db._get_table_columns("Batch Change"):
149
+ return
150
+ from lambda_erp.permissions import current_principal
151
+ principal = current_principal() or {}
152
+ who = principal.get("user_id") or principal.get("name")
153
+
154
+ def text(field, value):
155
+ if value in (None, ""):
156
+ return None
157
+ if field in ("blocked", "disabled"):
158
+ return "1" if flt(value) else "0"
159
+ return str(value)[:10] if field == "expiry_date" else str(value)
160
+
161
+ for field in AUDITED_BATCH_FIELDS:
162
+ if field not in after:
163
+ continue
164
+ old, new = text(field, (before or {}).get(field)), text(field, after.get(field))
165
+ if field in ("blocked", "disabled"):
166
+ old, new = old or "0", new or "0"
167
+ if old == new:
168
+ continue
169
+ db.insert("Batch Change", _dict(
170
+ name=uuid.uuid4().hex, batch=batch_name, item_code=(before or {}).get("item_code") or after.get("item_code"),
171
+ batch_no=(before or {}).get("batch_no") or after.get("batch_no"), field=field,
172
+ old_value=old, new_value=new, changed_by=who, changed_at=now(), source=source))
173
+
174
+
138
175
  def _date_text(value):
139
176
  return str(value)[:10] if value not in (None, "") else None
140
177
 
@@ -181,6 +218,8 @@ def resolve_entry_batch(sle):
181
218
  f"Correct the line or the batch")
182
219
  if expiry and not known:
183
220
  db.set_value("Batch", batch["name"], {"expiry_date": expiry, "modified": now()})
221
+ log_batch_changes(batch["name"], batch, {"expiry_date": expiry},
222
+ f"{sle.get('voucher_type') or 'Stock'} {sle.get('voucher_no') or ''}".strip())
184
223
  return batch_no
185
224
  if flt(item.get("has_expiry_date")) and not expiry:
186
225
  raise ValidationError(
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "lambda-erp"
3
- version = "1.4.11"
3
+ version = "1.4.12"
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