lambda-erp 1.4.4__tar.gz → 1.4.5__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 (125) hide show
  1. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/PKG-INFO +1 -1
  2. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/chat.py +24 -3
  3. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/masters.py +40 -1
  4. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/reports.py +93 -1
  5. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/services.py +4 -1
  6. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/frontend/src/api/client.ts +6 -0
  7. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/pos_invoice.py +1 -0
  8. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/purchase_invoice.py +1 -0
  9. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/sales_invoice.py +1 -0
  10. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/database.py +63 -0
  11. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/master_integrity.py +2 -0
  12. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/stock/delivery_note.py +1 -0
  13. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/stock/purchase_receipt.py +3 -0
  14. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/stock/stock_entry.py +33 -5
  15. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/stock/stock_ledger.py +153 -3
  16. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/workflow.py +43 -2
  17. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/pyproject.toml +1 -1
  18. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/.gitignore +0 -0
  19. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/LICENSE +0 -0
  20. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/README.md +0 -0
  21. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/__init__.py +0 -0
  22. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/attachments.py +0 -0
  23. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/auth.py +0 -0
  24. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/bootstrap.py +0 -0
  25. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/chat_links.py +0 -0
  26. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/demo_limits.py +0 -0
  27. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/deps.py +0 -0
  28. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/erp_context.py +0 -0
  29. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/errors.py +0 -0
  30. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/list_values.py +0 -0
  31. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/llm_provider.py +0 -0
  32. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/main.py +0 -0
  33. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/mcp_oauth.py +0 -0
  34. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/mentions.py +0 -0
  35. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/menu_layout.py +0 -0
  36. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/oauth.py +0 -0
  37. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/pdf.py +0 -0
  38. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/pdf_contract.py +0 -0
  39. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/pdf_exports.py +0 -0
  40. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/pdf_fonts.py +0 -0
  41. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/pdf_pages.py +0 -0
  42. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/pdf_profiles.py +0 -0
  43. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/pdf_templates.py +0 -0
  44. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/providers.py +0 -0
  45. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/record_notes.py +0 -0
  46. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/remarks_md.py +0 -0
  47. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/__init__.py +0 -0
  48. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/accounting.py +0 -0
  49. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/actions.py +0 -0
  50. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/admin.py +0 -0
  51. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/analytics.py +0 -0
  52. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/availability.py +0 -0
  53. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/bank_reconciliation.py +0 -0
  54. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/bank_statements.py +0 -0
  55. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/chat_api.py +0 -0
  56. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/documents.py +0 -0
  57. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/mcp.py +0 -0
  58. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/pdf_templates.py +0 -0
  59. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/proposals.py +0 -0
  60. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/routers/setup.py +0 -0
  61. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/templates/_proposal_totals.html +0 -0
  62. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/templates/_record_base.html +0 -0
  63. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/templates/delivery_note.html +0 -0
  64. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/templates/document.html +0 -0
  65. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/templates/proposal.html +0 -0
  66. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/templates/record.html +0 -0
  67. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/templates/reservation.html +0 -0
  68. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/time_filters.py +0 -0
  69. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/tool_permissions.py +0 -0
  70. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/api/write_context.py +0 -0
  71. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/docs/agents/README.md +0 -0
  72. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/frontend/LICENSE +0 -0
  73. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/frontend/README.md +0 -0
  74. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/__init__.py +0 -0
  75. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/__init__.py +0 -0
  76. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/bank_account.py +0 -0
  77. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  78. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/bank_statement_import.py +0 -0
  79. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/bank_transaction.py +0 -0
  80. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/budget.py +0 -0
  81. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/camt.py +0 -0
  82. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  83. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/general_ledger.py +0 -0
  84. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/journal_entry.py +0 -0
  85. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/payment_entry.py +0 -0
  86. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/revaluation.py +0 -0
  87. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/settlement.py +0 -0
  88. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/__init__.py +0 -0
  89. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/engine.py +0 -0
  90. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/pack.py +0 -0
  91. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  92. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  93. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  94. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  95. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  96. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  97. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/profiles.py +0 -0
  98. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/spine.py +0 -0
  99. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/accounting/subscription.py +0 -0
  100. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/assets/__init__.py +0 -0
  101. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/assets/asset.py +0 -0
  102. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/assets/lifecycle.py +0 -0
  103. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/assets/reservation.py +0 -0
  104. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/buying/__init__.py +0 -0
  105. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/buying/purchase_order.py +0 -0
  106. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/controllers/__init__.py +0 -0
  107. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/controllers/currency.py +0 -0
  108. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/controllers/defaults.py +0 -0
  109. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/controllers/item_price.py +0 -0
  110. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/controllers/item_prices.py +0 -0
  111. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/controllers/pricing_rule.py +0 -0
  112. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  113. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/exceptions.py +0 -0
  114. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/hooks.py +0 -0
  115. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/model.py +0 -0
  116. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/selling/__init__.py +0 -0
  117. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/selling/proposal.py +0 -0
  118. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/selling/quotation.py +0 -0
  119. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/selling/sales_order.py +0 -0
  120. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/simulation.py +0 -0
  121. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/stock/__init__.py +0 -0
  122. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/timestamps.py +0 -0
  123. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/utils.py +0 -0
  124. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/lambda_erp/validation.py +0 -0
  125. {lambda_erp-1.4.4 → lambda_erp-1.4.5}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.4
3
+ Version: 1.4.5
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", "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 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", "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": {}},
883
883
  },
884
884
  "required": ["report_type"],
885
885
  },
@@ -1963,6 +1963,16 @@ def _handle_get_report(args):
1963
1963
  elif report_type == "stock-balance":
1964
1964
  from api.routers.reports import _stock_balance
1965
1965
  return _stock_balance(db, filters.get("item_code"), filters.get("warehouse"))
1966
+ elif report_type == "batch-stock":
1967
+ from api.routers.reports import _batch_stock
1968
+ return _batch_stock(db, filters.get("item_code"), filters.get("warehouse"), filters.get("batch_no"),
1969
+ filters.get("item_prefix"), filters.get("expiring_before"),
1970
+ bool(filters.get("include_empty")))
1971
+ elif report_type == "batch-movements":
1972
+ from api.routers.reports import _batch_movements
1973
+ if not filters.get("batch_no"):
1974
+ return {"error": "batch-movements needs filters.batch_no"}
1975
+ return _batch_movements(db, filters.get("batch_no"), filters.get("item_code"), filters.get("warehouse"))
1966
1976
  elif report_type == "dashboard-summary":
1967
1977
  from api.routers.reports import _dashboard_summary
1968
1978
  return _dashboard_summary(db, filters.get("company"))
@@ -2879,6 +2889,15 @@ For a complete sales return (financial + stock): create and submit both a Credit
2879
2889
  - **Material Receipt:** Manual adjustment that adds stock (found stock, inventory count corrections). Posts Dr Stock In Hand / Cr Stock Adjustment. Not for purchased goods — use Purchase Receipt or Purchase Invoice with update_stock=1 for those. Not for opening balances — use Opening Stock.
2880
2890
  - **Material Issue:** Removes stock for write-offs or internal consumption. Posts Dr Stock Adjustment / Cr Stock In Hand.
2881
2891
  - **Material Transfer:** Moves stock between warehouses. No GL impact.
2892
+ - **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.
2893
+
2894
+ ### Batches (lot numbers)
2895
+ - 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.
2896
+ - 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.
2897
+ - Receiving lines (Purchase Receipt, Purchase Invoice with update_stock, Stock Entry receipt/opening) create a new batch automatically: give `batch_no` and, for items with expiry dates, `expiry_date`. Outgoing lines must name an existing batch with enough quantity in that warehouse — check with the batch-stock report first. Never invent a batch number or expiry date; ask.
2898
+ - Quantities are checked per batch: 10 in stock but only 2 in the named batch means a line for 3 is refused.
2899
+ - A return must name a batch that was on the original document, and at most the quantity of it that was delivered/received.
2900
+ - The `batch` master (search_masters master_type="batch") has one record per item + batch label.
2882
2901
 
2883
2902
  ### Assets & Reservations (equipment you OWN and hire out — not stock you sell)
2884
2903
  Use these only for items flagged `is_asset_tracked` on the Item master. Neither posts GL or stock entries: an owned machine going out on hire is not a sale of inventory, so the books are untouched until you invoice the hire through the normal selling cycle.
@@ -2935,6 +2954,8 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
2935
2954
  - **ar-aging** — Outstanding receivables bucketed by overdue days (Current, 1-30, 31-60, 61-90, 90+). Filters: company, as_of_date.
2936
2955
  - **ap-aging** — Outstanding payables bucketed by overdue days. Filters: company, as_of_date.
2937
2956
  - **stock-balance** — Inventory quantities and valuations. Filters: item_code, warehouse.
2957
+ - **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.
2958
+ - **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.
2938
2959
  - **dashboard-summary** — KPI overview (revenue, receivables, payables, stock value).
2939
2960
  - **Custom analytics drafts** — reserved for when the user **explicitly asks
2940
2961
  for** a chart, graph, trend, pivot, breakdown, or saved report, or when the
@@ -2964,7 +2985,7 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
2964
2985
 
2965
2986
  ## Stock Entry specifics
2966
2987
  When creating a stock-entry, the `data` object MUST include:
2967
- - `stock_entry_type`: "Opening Stock", "Material Receipt", "Material Issue", or "Material Transfer"
2988
+ - `stock_entry_type`: "Opening Stock", "Material Receipt", "Material Issue", "Material Transfer", or "Batch Assignment"
2968
2989
  - `company`, `posting_date`
2969
2990
  - `items` array where each item uses `basic_rate` (NOT `rate`) and warehouse fields:
2970
2991
  - Opening Stock: items need `t_warehouse` (target). Set `to_warehouse` on the parent too.
@@ -4,7 +4,7 @@ import secrets
4
4
 
5
5
  from fastapi import APIRouter, Depends, HTTPException, Query, Request
6
6
  from lambda_erp.database import get_db
7
- from lambda_erp.utils import _dict, now
7
+ from lambda_erp.utils import _dict, flt, now
8
8
  # The per-type registries live in api.services so `register_master` can extend
9
9
  # them; imported here (not moved) so existing `from api.routers.masters import
10
10
  # MASTER_IDENTITY_ALIAS`-style imports keep working.
@@ -59,6 +59,10 @@ DELETE_REFERENCE_CHECKS = {
59
59
  ('SELECT 1 FROM "Subscription" WHERE company = ? LIMIT 1', "subscription"),
60
60
  ('SELECT 1 FROM "Bank Transaction" t JOIN "Bank Account" a ON a.name = t.bank_account WHERE a.company = ? LIMIT 1', "bank transaction"),
61
61
  ],
62
+ "batch": [
63
+ ('SELECT 1 FROM "Stock Ledger Entry" s JOIN "Batch" b ON b.item_code = s.item_code '
64
+ 'AND b.batch_no = s.batch_no WHERE b.name = ? LIMIT 1', "stock ledger entry"),
65
+ ],
62
66
  "customer": [
63
67
  ('SELECT 1 FROM "Quotation" WHERE customer = ? LIMIT 1', "quotation"),
64
68
  ('SELECT 1 FROM "Sales Order" WHERE customer = ? LIMIT 1', "sales order"),
@@ -211,6 +215,7 @@ MASTER_LINK_FIELDS = {
211
215
  'warehouse': {'company': 'Company', 'account': 'Account', 'parent_warehouse': 'Warehouse'},
212
216
  'account': {'company': 'Company', 'parent_account': 'Account'},
213
217
  'cost-center': {'company': 'Company', 'parent_cost_center': 'Cost Center'},
218
+ 'batch': {'item_code': 'Item'},
214
219
  }
215
220
 
216
221
 
@@ -272,12 +277,46 @@ def _validate_master_input(master_type, doctype, data, name=None):
272
277
  raise ValidationError(f'{doctype}: {field} must reference an existing {table}')
273
278
  if master_type == 'item' and data.get('valuation_method') not in (None, '', 'Moving Average'):
274
279
  raise ValidationError('Item: valuation_method must be Moving Average; it is the only valuation the stock ledger implements')
280
+ if master_type == 'item':
281
+ _validate_item_batch_flags(db, merged, name)
282
+ if master_type == 'batch':
283
+ _validate_batch(db, merged, name)
275
284
  if master_type == 'company' and data.get('default_sales_tax_template'):
276
285
  template = db.get_value('Tax Template', data['default_sales_tax_template'], ['company', 'tax_type'])
277
286
  if not template or template['company'] != (name or data.get('name')) or template['tax_type'] != 'Sales':
278
287
  raise ValidationError('Default sales tax template must be a Sales template belonging to this Company')
279
288
 
280
289
 
290
+ def _validate_item_batch_flags(db, merged, name):
291
+ """Batch tracking can be switched on at any time (stock that is already
292
+ there stays without a batch until a Batch Assignment). It cannot be
293
+ switched off while the item has batches in the stock ledger."""
294
+ tracked = bool(flt(merged.get('has_batch_no')))
295
+ if flt(merged.get('has_expiry_date')) and not tracked:
296
+ raise ValidationError('Item: has_expiry_date needs has_batch_no; the expiry date belongs to the batch')
297
+ stock_item = merged.get('is_stock_item')
298
+ if tracked and stock_item is not None and not flt(stock_item):
299
+ raise ValidationError('Item: only a stock item can be batch-tracked')
300
+ if name and not tracked and db.sql(
301
+ 'SELECT 1 FROM "Stock Ledger Entry" WHERE item_code = ? AND batch_no IS NOT NULL '
302
+ 'AND batch_no <> \'\' LIMIT 1', [name]):
303
+ raise ValidationError(f'Item {name}: batch tracking cannot be switched off, the stock ledger has batches of it')
304
+
305
+
306
+ def _validate_batch(db, merged, name):
307
+ for field in ('item_code', 'batch_no'):
308
+ if missing(merged.get(field)):
309
+ raise ValidationError(f'Batch: {field} is required')
310
+ item = db.get_value('Item', merged['item_code'], ['has_batch_no', 'has_expiry_date'])
311
+ if not item or not flt(item.get('has_batch_no')):
312
+ raise ValidationError(f'Batch: item {merged["item_code"]} is not batch-tracked (set has_batch_no on the item first)')
313
+ if flt(item.get('has_expiry_date')) and missing(merged.get('expiry_date')):
314
+ raise ValidationError(f'Batch: expiry_date is required, item {merged["item_code"]} has expiry dates')
315
+ twin = db.get_value('Batch', {'item_code': merged['item_code'], 'batch_no': merged['batch_no']}, 'name')
316
+ if twin and twin != name:
317
+ raise ValidationError(f'Batch {merged["batch_no"]} already exists for item {merged["item_code"]} ({twin})')
318
+
319
+
281
320
  @router.get('/company/{name}/sales-tax-templates')
282
321
  def company_sales_tax_templates(name: str, _user: dict = _viewer):
283
322
  """Choices for the company default, using existing tax templates only."""
@@ -2,7 +2,7 @@
2
2
 
3
3
  from datetime import date
4
4
 
5
- from fastapi import APIRouter, Depends, Query
5
+ from fastapi import APIRouter, Depends, HTTPException, Query
6
6
  from lambda_erp.database import get_db
7
7
  from lambda_erp.utils import flt, nowdate
8
8
  from lambda_erp.controllers.currency import get_exchange_rate
@@ -381,6 +381,98 @@ def stock_balance(
381
381
  return _stock_balance(get_db(), item_code, warehouse)
382
382
 
383
383
 
384
+ def _batch_stock(db, item_code=None, warehouse=None, batch_no=None, item_prefix=None,
385
+ expiring_before=None, include_empty=False):
386
+ """Stock per item x warehouse x batch with the batch's expiry date.
387
+
388
+ `batch_no` is the label as printed on the goods: the same label can exist
389
+ on several items, so it can return several rows. Stock of a tracked item
390
+ that has no batch yet appears with an empty batch_no."""
391
+ where, params = [], []
392
+ for column, value in (("d.item_code", item_code), ("d.warehouse", warehouse), ("d.batch_no", batch_no)):
393
+ if value:
394
+ where.append(f"{column} = ?")
395
+ params.append(value)
396
+ if item_prefix:
397
+ where.append("d.item_code LIKE ?")
398
+ params.append(item_prefix.replace("%", "") + "%")
399
+ if expiring_before:
400
+ where.append("b.expiry_date IS NOT NULL AND b.expiry_date <= ?")
401
+ params.append(expiring_before)
402
+ if not include_empty:
403
+ where.append("d.actual_qty <> 0")
404
+ if not batch_no:
405
+ # Untracked items have no batches to show; their stock is in stock-balance.
406
+ where.append("(d.batch_no <> '' OR COALESCE(i.has_batch_no, 0) = 1)")
407
+ rows = db.sql(
408
+ 'SELECT d.item_code, i.item_name, d.warehouse, d.batch_no, b.name AS batch, b.expiry_date, '
409
+ 'COALESCE(b.disabled, 0) AS batch_disabled, d.actual_qty '
410
+ 'FROM "Stock Balance Detail" d '
411
+ 'LEFT JOIN "Item" i ON i.name = d.item_code '
412
+ 'LEFT JOIN "Batch" b ON b.item_code = d.item_code AND b.batch_no = d.batch_no '
413
+ + (f"WHERE {' AND '.join(where)} " if where else "")
414
+ + 'ORDER BY d.item_code, b.expiry_date, d.batch_no, d.warehouse', params)
415
+ return {"rows": [{**dict(row), "actual_qty": flt(row["actual_qty"])} for row in rows]}
416
+
417
+
418
+ @router.get("/batch-stock")
419
+ def batch_stock(
420
+ item_code: str | None = None,
421
+ warehouse: str | None = None,
422
+ batch_no: str | None = None,
423
+ item_prefix: str | None = None,
424
+ expiring_before: str | None = None,
425
+ include_empty: bool = False,
426
+ ):
427
+ return _batch_stock(get_db(), item_code, warehouse, batch_no, item_prefix, expiring_before, include_empty)
428
+
429
+
430
+ _BATCH_PARTY = {
431
+ "Delivery Note": ("customer", "Customer"), "Sales Invoice": ("customer", "Customer"),
432
+ "POS Invoice": ("customer", "Customer"), "Purchase Receipt": ("supplier", "Supplier"),
433
+ "Purchase Invoice": ("supplier", "Supplier"),
434
+ }
435
+
436
+
437
+ def _batch_movements(db, batch_no=None, item_code=None, warehouse=None):
438
+ """Every stock movement of a batch, oldest first, with its document, line
439
+ and the customer or supplier of that document: where a batch came from
440
+ and who received it. `batch_no` alone can match several items."""
441
+ if not batch_no:
442
+ raise HTTPException(status_code=422, detail="batch_no is required")
443
+ where, params = ["s.batch_no = ?"], [batch_no]
444
+ for column, value in (("s.item_code", item_code), ("s.warehouse", warehouse)):
445
+ if value:
446
+ where.append(f"{column} = ?")
447
+ params.append(value)
448
+ rows = db.sql(
449
+ 'SELECT s.name, s.posting_date, s.item_code, s.warehouse, s.batch_no, s.actual_qty, '
450
+ 's.voucher_type, s.voucher_no, s.voucher_detail_no '
451
+ f'FROM "Stock Ledger Entry" s WHERE {" AND ".join(where)} '
452
+ 'ORDER BY s.posting_date, s.creation, s.name', params)
453
+ parties = {}
454
+ result = []
455
+ for row in rows:
456
+ entry = {**dict(row), "actual_qty": flt(row["actual_qty"]), "party_type": None, "party": None}
457
+ field = _BATCH_PARTY.get(row["voucher_type"])
458
+ if field:
459
+ key = (row["voucher_type"], row["voucher_no"])
460
+ if key not in parties:
461
+ parties[key] = db.get_value(row["voucher_type"], row["voucher_no"], field[0])
462
+ entry["party_type"], entry["party"] = field[1], parties[key]
463
+ result.append(entry)
464
+ return {"rows": result}
465
+
466
+
467
+ @router.get("/batch-movements")
468
+ def batch_movements(
469
+ batch_no: str,
470
+ item_code: str | None = None,
471
+ warehouse: str | None = None,
472
+ ):
473
+ return _batch_movements(get_db(), batch_no, item_code, warehouse)
474
+
475
+
384
476
  def _dashboard_summary(db, company=None):
385
477
  """Compute dashboard summary metrics."""
386
478
 
@@ -84,6 +84,8 @@ MASTER_TABLES = {
84
84
  "account": ("Account", "account_name"),
85
85
  "company": ("Company", "company_name"),
86
86
  "cost-center": ("Cost Center", "cost_center_name"),
87
+ # One row per (item, batch label); the label alone is not unique.
88
+ "batch": ("Batch", "batch_no"),
87
89
  }
88
90
 
89
91
  # Auto-naming prefixes: masters created without an explicit `name` get a
@@ -94,11 +96,12 @@ MASTER_NAME_PREFIXES = {
94
96
  "supplier": "SUPP",
95
97
  "item": "ITEM",
96
98
  "warehouse": "WH",
99
+ "batch": "BATCH",
97
100
  }
98
101
 
99
102
  # Minimum numeric suffix width for sequential plugin master ids. Core masters
100
103
  # retain the historical three-digit form; plugins can opt into e.g. FIDX-0001.
101
- MASTER_NAME_DIGITS: dict[str, int] = {}
104
+ MASTER_NAME_DIGITS: dict[str, int] = {"batch": 5}
102
105
 
103
106
  # High-volume plugin masters can opt out of sequential ids. Sequential naming
104
107
  # must inspect existing suffixes after a process restart; opaque random ids keep
@@ -555,6 +555,12 @@ export const api = {
555
555
  stockBalance: (params?: Record<string, string>) =>
556
556
  request<{ rows: any[] }>(`/reports/stock-balance${qs(params)}`),
557
557
 
558
+ batchStock: (params?: Record<string, string>) =>
559
+ request<{ rows: any[] }>(`/reports/batch-stock${qs(params)}`),
560
+
561
+ batchMovements: (params: Record<string, string>) =>
562
+ request<{ rows: any[] }>(`/reports/batch-movements${qs(params)}`),
563
+
558
564
  // --- Rentals: availability + fleet calendar ---
559
565
  availability: (params: { item_code: string; from: string; to: string; warehouse?: string; exclude?: string }) =>
560
566
  request<AvailabilityResult>(`/availability${qs(params)}`),
@@ -337,6 +337,7 @@ def make_pos_return(posi_name):
337
337
  income_account=item.get("income_account"),
338
338
  cost_center=item.get("cost_center"),
339
339
  warehouse=item.get("warehouse"),
340
+ batch_no=item.get("batch_no"),
340
341
  ))
341
342
 
342
343
  for tax in original.get("taxes") or []:
@@ -474,6 +474,7 @@ def make_purchase_return(pinv_name):
474
474
  expense_account=item.get("expense_account"),
475
475
  cost_center=item.get("cost_center"),
476
476
  warehouse=item.get("warehouse"),
477
+ batch_no=item.get("batch_no"),
477
478
  purchase_order=item.get("purchase_order"),
478
479
  purchase_order_item=item.get("purchase_order_item"),
479
480
  ))
@@ -458,6 +458,7 @@ def make_sales_return(sinv_name):
458
458
  income_account=item.get("income_account"),
459
459
  cost_center=item.get("cost_center"),
460
460
  warehouse=item.get("warehouse"),
461
+ batch_no=item.get("batch_no"),
461
462
  sales_order=item.get("sales_order"),
462
463
  sales_order_item=item.get("sales_order_item"),
463
464
  ))
@@ -3209,6 +3209,68 @@ def _m050_amount_only_returns(db: "Database") -> None:
3209
3209
  db.ensure_column(table, "amount_only", "INTEGER DEFAULT 0")
3210
3210
 
3211
3211
 
3212
+ BATCH_LINE_TABLES = ("Stock Entry Detail", "Delivery Note Item", "Purchase Receipt Item",
3213
+ "Sales Invoice Item", "Purchase Invoice Item", "POS Invoice Item")
3214
+ BATCH_RECEIVING_TABLES = ("Stock Entry Detail", "Purchase Receipt Item", "Purchase Invoice Item")
3215
+
3216
+
3217
+ def _m051_batches(db: "Database") -> None:
3218
+ """Batch-tracked stock (see docs/batches.md).
3219
+
3220
+ - Item.has_batch_no / has_expiry_date switch tracking on per item.
3221
+ - "Batch" is the master: one row per (item, batch label); a label alone is
3222
+ not unique, several items can carry the same one.
3223
+ - "Stock Balance Detail" is the quantity per item x warehouse x batch,
3224
+ maintained with every stock ledger entry. batch_no '' is stock without a
3225
+ batch (items that are not tracked, and stock that was there before an
3226
+ item was switched to tracking). Its rows always add up to "Bin".
3227
+ - Existing stock is backfilled into the '' rows: no batch is invented.
3228
+ """
3229
+ db.conn.execute(db._ddl(
3230
+ """CREATE TABLE IF NOT EXISTS "Batch" (
3231
+ name TEXT PRIMARY KEY,
3232
+ batch_no TEXT NOT NULL,
3233
+ item_code TEXT NOT NULL,
3234
+ expiry_date TEXT,
3235
+ manufacturing_date TEXT,
3236
+ description TEXT,
3237
+ disabled INTEGER DEFAULT 0,
3238
+ creation TEXT,
3239
+ modified TEXT
3240
+ )"""))
3241
+ db.conn.execute(db._ddl(
3242
+ 'CREATE UNIQUE INDEX IF NOT EXISTS "ux_batch_item_batch_no" ON "Batch" (item_code, batch_no)'))
3243
+ db.conn.execute(db._ddl(
3244
+ """CREATE TABLE IF NOT EXISTS "Stock Balance Detail" (
3245
+ name TEXT PRIMARY KEY,
3246
+ item_code TEXT NOT NULL,
3247
+ warehouse TEXT NOT NULL,
3248
+ batch_no TEXT NOT NULL DEFAULT '',
3249
+ actual_qty REAL DEFAULT 0
3250
+ )"""))
3251
+ db.conn.execute(db._ddl(
3252
+ 'CREATE UNIQUE INDEX IF NOT EXISTS "ux_stock_balance_detail_key" '
3253
+ 'ON "Stock Balance Detail" (item_code, warehouse, batch_no)'))
3254
+ db.conn.commit()
3255
+ for table in ("Batch", "Stock Balance Detail"):
3256
+ db._col_cache.pop(table, None)
3257
+ db._text_col_cache.pop(table, None)
3258
+ db.ensure_column("Item", "has_batch_no", "INTEGER DEFAULT 0")
3259
+ db.ensure_column("Item", "has_expiry_date", "INTEGER DEFAULT 0")
3260
+ for table in BATCH_LINE_TABLES:
3261
+ db.ensure_column(table, "batch_no", "TEXT")
3262
+ for table in BATCH_RECEIVING_TABLES:
3263
+ db.ensure_column(table, "expiry_date", "TEXT")
3264
+ import uuid
3265
+ for row in db.sql(
3266
+ 'SELECT b.item_code, b.warehouse, b.actual_qty FROM "Bin" b WHERE NOT EXISTS ('
3267
+ 'SELECT 1 FROM "Stock Balance Detail" d WHERE d.item_code = b.item_code AND d.warehouse = b.warehouse)'):
3268
+ db.sql('INSERT INTO "Stock Balance Detail" (name, item_code, warehouse, batch_no, actual_qty) '
3269
+ 'VALUES (?, ?, ?, ?, ?)',
3270
+ [uuid.uuid4().hex, row["item_code"], row["warehouse"], "", row["actual_qty"] or 0])
3271
+ db.conn.commit()
3272
+
3273
+
3212
3274
  def _m042_record_notes(db: "Database") -> None:
3213
3275
  """Internal team notes on any document or master (see api.record_notes)."""
3214
3276
  db.conn.execute(
@@ -3279,6 +3341,7 @@ Database.MIGRATIONS = [
3279
3341
  (48, "item_valuation_moving_average", _m048_item_valuation_moving_average),
3280
3342
  (49, "pricing_rule_currency", _m049_pricing_rule_currency),
3281
3343
  (50, "amount_only_returns", _m050_amount_only_returns),
3344
+ (51, "batches", _m051_batches),
3282
3345
  ]
3283
3346
 
3284
3347
 
@@ -6,6 +6,8 @@ STRUCTURAL_FIELDS = {
6
6
  'item': ('is_asset_tracked', 'is_stock_item', 'stock_uom'),
7
7
  'cost-center': ('company', 'parent_cost_center', 'is_group'),
8
8
  'company': ('default_currency',),
9
+ # A batch is identified by its item and label once stock has moved on it.
10
+ 'batch': ('item_code', 'batch_no'),
9
11
  }
10
12
 
11
13
 
@@ -209,6 +209,7 @@ def make_delivery_return(dn_name):
209
209
  uom=item.get("uom"),
210
210
  rate=flt(item.get("rate")),
211
211
  warehouse=item.get("warehouse"),
212
+ batch_no=item.get("batch_no"),
212
213
  against_sales_order=item.get("against_sales_order"),
213
214
  so_detail=item.get("so_detail"),
214
215
  ))
@@ -179,6 +179,8 @@ class PurchaseReceipt(Document):
179
179
  voucher_type=self.DOCTYPE,
180
180
  voucher_no=self.name,
181
181
  voucher_detail_no=item.get("name"),
182
+ batch_no=item.get("batch_no"),
183
+ expiry_date=item.get("expiry_date"),
182
184
  posting_date=self.posting_date,
183
185
  company=self.company,
184
186
  ))
@@ -309,6 +311,7 @@ def make_purchase_receipt_return(prec_name):
309
311
  uom=item.get("uom"),
310
312
  rate=flt(item.get("rate")),
311
313
  warehouse=item.get("warehouse"),
314
+ batch_no=item.get("batch_no"),
312
315
  against_purchase_order=item.get("against_purchase_order"),
313
316
  po_detail=item.get("po_detail"),
314
317
  ))
@@ -5,6 +5,7 @@ Stock Entry handles all material movements:
5
5
  - Material Receipt: goods coming INTO a warehouse (no source)
6
6
  - Material Issue: goods going OUT of a warehouse (no target)
7
7
  - Material Transfer: goods moving between warehouses
8
+ - Batch Assignment: stock without a batch gets its batch, in place
8
9
 
9
10
  Each type creates Stock Ledger Entries (SLEs) and optionally
10
11
  GL entries for perpetual inventory.
@@ -29,8 +30,10 @@ class StockEntry(Document):
29
30
  CHILD_REQUIREMENTS = {'items': {'required': ['item_code', 'qty']}}
30
31
  CONDITIONAL_REQUIREMENTS = (
31
32
  "Receipt/opening rows require an explicit finite basic_rate >= 0 in company currency (zero means intentionally unvalued). Issues and transfers use actual inventory cost, not a supplied selling rate. Financial postings derive from posted stock values.",
32
- "stock_entry_type must be Opening Stock, Material Receipt, Material Issue or Material Transfer.",
33
+ "stock_entry_type must be Opening Stock, Material Receipt, Material Issue, Material Transfer or Batch Assignment.",
33
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
+ "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
+ "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.",
34
37
  )
35
38
 
36
39
  LINK_FIELDS = {
@@ -47,9 +50,11 @@ class StockEntry(Document):
47
50
  }
48
51
 
49
52
  def validate(self):
50
- if self.stock_entry_type not in {"Opening Stock", "Material Receipt", "Material Issue", "Material Transfer"}:
53
+ if self.stock_entry_type not in {"Opening Stock", "Material Receipt", "Material Issue", "Material Transfer",
54
+ "Batch Assignment"}:
51
55
  raise ValidationError(
52
- "Stock Entry Type must be Opening Stock, Material Receipt, Material Issue or Material Transfer"
56
+ "Stock Entry Type must be Opening Stock, Material Receipt, Material Issue, "
57
+ "Material Transfer or Batch Assignment"
53
58
  )
54
59
  if not self.get("items"):
55
60
  raise ValidationError("At least one item is required")
@@ -111,6 +116,20 @@ class StockEntry(Document):
111
116
  raise ValidationError(
112
117
  f"Source Warehouse is required for Material Issue (Item: {item.get('item_code')})"
113
118
  )
119
+ elif self.stock_entry_type == "Batch Assignment":
120
+ # Same warehouse on both sides: the stock stays where it is.
121
+ warehouse = (item.get("t_warehouse") or item.get("s_warehouse")
122
+ or self.to_warehouse or self.from_warehouse)
123
+ if not warehouse:
124
+ raise ValidationError(
125
+ f"Warehouse is required for Batch Assignment (Item: {item.get('item_code')})")
126
+ if item.get("s_warehouse") and item.get("t_warehouse") and item["s_warehouse"] != item["t_warehouse"]:
127
+ raise ValidationError(
128
+ "Batch Assignment does not move stock: Source and Target Warehouse must be the same")
129
+ item["s_warehouse"] = item["t_warehouse"] = warehouse
130
+ if not str(item.get("batch_no") or "").strip():
131
+ raise ValidationError(
132
+ f"Batch is required for Batch Assignment (Item: {item.get('item_code')})")
114
133
  elif self.stock_entry_type == "Material Transfer":
115
134
  if not item.get("s_warehouse"):
116
135
  item["s_warehouse"] = self.from_warehouse
@@ -164,14 +183,19 @@ class StockEntry(Document):
164
183
  posting_date=self.posting_date, posting_time=self.posting_time or '00:00:00',
165
184
  company=self.company)
166
185
  rate = flt(item.get('basic_rate'))
186
+ batch = {'batch_no': item.get('batch_no')}
187
+ # Batch Assignment takes the quantity out of stock without a batch
188
+ # and puts it back, at the same value, under the batch.
189
+ source_batch = ({'batch_no': None, 'allow_unassigned_batch': True}
190
+ if self.stock_entry_type == 'Batch Assignment' else batch)
167
191
  if item.get('s_warehouse'):
168
- make_sl_entries([{**base, 'warehouse': item['s_warehouse'], 'actual_qty': -flt(item['qty']), 'outgoing_rate': 0}])
192
+ make_sl_entries([{**base, **source_batch, 'warehouse': item['s_warehouse'], 'actual_qty': -flt(item['qty']), 'outgoing_rate': 0}])
169
193
  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'])
170
194
  value = -flt(posted.stock_value_difference)
171
195
  rate = value / flt(item['qty'])
172
196
  outgoing += value
173
197
  if item.get('t_warehouse'):
174
- make_sl_entries([{**base, 'warehouse': item['t_warehouse'], 'actual_qty': flt(item['qty']), 'incoming_rate': rate, 'incoming_rate_is_explicit': True}])
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}])
175
199
  incoming += flt(item['qty']) * rate
176
200
  item['basic_rate'] = rate
177
201
  item['basic_amount'] = item['amount'] = flt(flt(item['qty']) * rate, 2)
@@ -209,6 +233,10 @@ class StockEntry(Document):
209
233
  if not account:
210
234
  raise ValidationError('Stock account is required before posting a valued stock movement')
211
235
  amounts[account] = amounts.get(account, 0) + value
236
+ if self.stock_entry_type == 'Batch Assignment':
237
+ if abs(sum(amounts.values())) > 0.01:
238
+ raise ValidationError('Batch Assignment must not change stock value')
239
+ return []
212
240
  if self.stock_entry_type != 'Material Transfer':
213
241
  total = sum(amounts.values())
214
242
  if total: