lambda-erp 1.4.21__tar.gz → 1.4.22__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 (139) hide show
  1. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/PKG-INFO +3 -1
  2. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/README.md +2 -0
  3. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/chat.py +7 -0
  4. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/pdf.py +19 -0
  5. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/pdf_profiles.py +3 -0
  6. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/pdf_templates.py +1 -0
  7. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/services.py +3 -0
  8. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/templates/delivery_note.html +1 -1
  9. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/templates/document.html +4 -3
  10. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/pos_invoice.py +2 -1
  11. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/purchase_invoice.py +2 -1
  12. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/sales_invoice.py +2 -1
  13. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/buying/purchase_order.py +2 -1
  14. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/controllers/item_price.py +38 -8
  15. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/controllers/taxes_and_totals.py +8 -3
  16. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/database.py +30 -0
  17. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/permissions.py +20 -0
  18. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/selling/quotation.py +6 -3
  19. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/selling/sales_order.py +2 -1
  20. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/stock/delivery_note.py +6 -3
  21. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/stock/purchase_receipt.py +6 -3
  22. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/stock/stock_entry.py +4 -0
  23. lambda_erp-1.4.22/lambda_erp/units.py +191 -0
  24. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/pyproject.toml +1 -1
  25. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/.gitignore +0 -0
  26. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/LICENSE +0 -0
  27. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/__init__.py +0 -0
  28. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/attachments.py +0 -0
  29. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/auth.py +0 -0
  30. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/bootstrap.py +0 -0
  31. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/chat_links.py +0 -0
  32. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/demo_limits.py +0 -0
  33. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/deps.py +0 -0
  34. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/erp_context.py +0 -0
  35. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/errors.py +0 -0
  36. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/list_values.py +0 -0
  37. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/llm_provider.py +0 -0
  38. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/main.py +0 -0
  39. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/mcp_oauth.py +0 -0
  40. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/mentions.py +0 -0
  41. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/menu_layout.py +0 -0
  42. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/oauth.py +0 -0
  43. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/pdf_contract.py +0 -0
  44. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/pdf_exports.py +0 -0
  45. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/pdf_fonts.py +0 -0
  46. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/pdf_pages.py +0 -0
  47. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/pricing_actions.py +0 -0
  48. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/providers.py +0 -0
  49. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/record_attachments.py +0 -0
  50. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/record_notes.py +0 -0
  51. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/remarks_md.py +0 -0
  52. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/__init__.py +0 -0
  53. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/accounting.py +0 -0
  54. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/actions.py +0 -0
  55. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/admin.py +0 -0
  56. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/analytics.py +0 -0
  57. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/availability.py +0 -0
  58. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/bank_reconciliation.py +0 -0
  59. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/bank_statements.py +0 -0
  60. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/chat_api.py +0 -0
  61. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/documents.py +0 -0
  62. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/masters.py +0 -0
  63. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/mcp.py +0 -0
  64. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/pdf_templates.py +0 -0
  65. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/proposals.py +0 -0
  66. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/reports.py +0 -0
  67. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/routers/setup.py +0 -0
  68. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/stock_actions.py +0 -0
  69. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/templates/_proposal_totals.html +0 -0
  70. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/templates/_record_base.html +0 -0
  71. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/templates/proposal.html +0 -0
  72. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/templates/record.html +0 -0
  73. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/templates/reservation.html +0 -0
  74. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/time_filters.py +0 -0
  75. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/tool_permissions.py +0 -0
  76. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/api/write_context.py +0 -0
  77. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/docs/agents/README.md +0 -0
  78. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/frontend/LICENSE +0 -0
  79. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/frontend/README.md +0 -0
  80. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/frontend/src/api/client.ts +0 -0
  81. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/__init__.py +0 -0
  82. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/__init__.py +0 -0
  83. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/bank_account.py +0 -0
  84. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  85. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/bank_statement_import.py +0 -0
  86. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/bank_transaction.py +0 -0
  87. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/budget.py +0 -0
  88. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/camt.py +0 -0
  89. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  90. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/general_ledger.py +0 -0
  91. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/journal_entry.py +0 -0
  92. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/payment_entry.py +0 -0
  93. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/revaluation.py +0 -0
  94. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/settlement.py +0 -0
  95. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/__init__.py +0 -0
  96. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/engine.py +0 -0
  97. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/pack.py +0 -0
  98. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  99. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  100. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  101. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  102. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  103. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  104. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/profiles.py +0 -0
  105. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/setup/spine.py +0 -0
  106. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/accounting/subscription.py +0 -0
  107. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/addresses.py +0 -0
  108. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/assets/__init__.py +0 -0
  109. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/assets/asset.py +0 -0
  110. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/assets/lifecycle.py +0 -0
  111. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/assets/reservation.py +0 -0
  112. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/backlog.py +0 -0
  113. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/bundles.py +0 -0
  114. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/buying/__init__.py +0 -0
  115. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/controllers/__init__.py +0 -0
  116. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/controllers/currency.py +0 -0
  117. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/controllers/defaults.py +0 -0
  118. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/controllers/item_prices.py +0 -0
  119. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/controllers/price_resolution.py +0 -0
  120. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/controllers/pricing_rule.py +0 -0
  121. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/controllers/tax_defaults.py +0 -0
  122. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/exceptions.py +0 -0
  123. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/hooks.py +0 -0
  124. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/master_integrity.py +0 -0
  125. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/model.py +0 -0
  126. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/selling/__init__.py +0 -0
  127. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/selling/proposal.py +0 -0
  128. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/simulation.py +0 -0
  129. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/stock/__init__.py +0 -0
  130. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/stock/consignment.py +0 -0
  131. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/stock/reservation.py +0 -0
  132. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/stock/serial.py +0 -0
  133. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/stock/stock_count.py +0 -0
  134. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/stock/stock_ledger.py +0 -0
  135. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/timestamps.py +0 -0
  136. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/utils.py +0 -0
  137. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/validation.py +0 -0
  138. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/lambda_erp/workflow.py +0 -0
  139. {lambda_erp-1.4.21 → lambda_erp-1.4.22}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.21
3
+ Version: 1.4.22
4
4
  Summary: Core ERP logic - accounting, sales, purchasing, inventory
5
5
  Author: TORUS INVESTMENTS AG
6
6
  License-Expression: Apache-2.0
@@ -34,6 +34,8 @@ Description-Content-Type: text/markdown
34
34
 
35
35
  Lambda ERP is a simpler ERP: create invoices, check inventory, answer accounting questions, and change reports by asking for what you need in plain language.
36
36
 
37
+ Developed by [Lambda](https://lambda.dev/erp).
38
+
37
39
  https://github.com/user-attachments/assets/1b2749ef-10e7-42f5-9cce-df5628292667
38
40
 
39
41
  <p align="center">
@@ -4,6 +4,8 @@
4
4
 
5
5
  Lambda ERP is a simpler ERP: create invoices, check inventory, answer accounting questions, and change reports by asking for what you need in plain language.
6
6
 
7
+ Developed by [Lambda](https://lambda.dev/erp).
8
+
7
9
  https://github.com/user-attachments/assets/1b2749ef-10e7-42f5-9cce-df5628292667
8
10
 
9
11
  <p align="center">
@@ -3060,6 +3060,13 @@ For a complete sales return (financial + stock): create and submit both a Credit
3060
3060
  - On quotations, sales orders, delivery notes and sales / POS invoices, put the bundle's item_code and qty on a line and save: the line is replaced by one line per item of the bundle, which are then ordinary lines. Do not give a bundle line a rate, discount or batch; do not expand a bundle by hand.
3061
3061
  - When the user names a set, look for it with list_documents doctype="item-bundle" (or the item) before listing single items yourself.
3062
3062
 
3063
+ ### Units of measure (ordering in a pack, stocking in pieces)
3064
+ - An item is stocked in its `stock_uom`. An **Item Unit** (doctype `item-unit`: item_code, uom, conversion_factor = stock units per unit, e.g. Karton = 100) gives it a further unit. List an item's units with list_documents doctype="item-unit" filtered by item_code.
3065
+ - To enter a line in such a unit, send `qty` and `rate` in that unit and name it in `uom` (qty 2, uom "Karton", rate 290). On save the line is stored per stock unit (qty 200, rate 2.90) and keeps `order_uom`, `conversion_factor` and `order_qty` (2). Amounts are unchanged: 2 x 290 = 200 x 2.90.
3066
+ - On a stored line `qty`, `rate`, delivered/billed quantities and every stock figure are in the stock unit; `order_qty` + `order_uom` say what was ordered. Tell the user both when they differ ("2 Karton = 200 Stk"). Never multiply or divide by the factor yourself before sending a line: either send the entered unit in `uom`, or send stock units.
3067
+ - A unit the item does not have is refused. Do not guess a factor from a product name or from "VE"/"Pack": ask, or have an Item Unit created first.
3068
+ - An Item Price with `uom` set is a price per that unit (290 per Karton) and is used for lines entered in it; a price without `uom` is per stock unit.
3069
+
3063
3070
  ### Addresses
3064
3071
  - A customer can have several addresses (master_type="address": customer, label, is_billing, is_shipping, is_default_billing, is_default_shipping, recipient_name, contact_person, address, zip_code, city, country, instructions). Search them with search_masters master_type="address" and the customer's name.
3065
3072
  - Quotation, Sales Order, Delivery Note and Sales Invoice carry `billing_address` and `shipping_address` (address record ids of that customer) and `billing_address_display` / `shipping_address_display` (the text that prints). Leave them out to get the customer's defaults; documents made from an order follow the order.
@@ -110,6 +110,25 @@ def add_line_deductions(items):
110
110
  item["discount_total"], item["discount_label"] = deduction["amount"], deduction["label"]
111
111
  else:
112
112
  item["discount_total"] = 0
113
+ add_order_unit(item)
114
+
115
+
116
+ def add_order_unit(item):
117
+ """A line ordered in a further unit of the item (lambda_erp/units.py) is
118
+ stored per stock unit. For printing it also gets the price per ordered
119
+ unit: item.order_rate (and item.order_gross_rate before a deduction), next
120
+ to item.order_qty and item.order_uom. item.ordered_in_unit says whether
121
+ the line has them."""
122
+ try:
123
+ factor = float(item.get("conversion_factor") or 0)
124
+ except (TypeError, ValueError):
125
+ factor = 0
126
+ ordered = bool(item.get("order_uom")) and factor > 0
127
+ item["ordered_in_unit"] = ordered
128
+ if ordered:
129
+ item["order_rate"] = round(float(item.get("rate") or 0) * factor, 2)
130
+ if item.get("gross_rate") is not None:
131
+ item["order_gross_rate"] = round(float(item.get("gross_rate") or 0) * factor, 2)
113
132
 
114
133
 
115
134
  def fill_text_placeholders(text, doc, party_name=None, company_name=None) -> str:
@@ -107,6 +107,9 @@ PROFILES.update({
107
107
  'Price List': PDFProfile('record', 'Price list overview',
108
108
  fields=('price_list_name', 'currency', 'selling', 'buying', 'enabled'),
109
109
  required=('price_list_name', 'currency')),
110
+ 'Item Unit': PDFProfile('record', 'Item unit',
111
+ fields=('item_code', 'uom', 'conversion_factor', 'enabled'),
112
+ required=('item_code', 'uom', 'conversion_factor')),
110
113
  'Item Price': PDFProfile('record', 'Item price overview',
111
114
  fields=('item_code', 'price_list', 'customer', 'supplier', 'uom', 'min_qty', 'rate', 'valid_from', 'valid_upto', 'enabled'),
112
115
  required=('item_code', 'price_list', 'rate')),
@@ -697,6 +697,7 @@ _REFERENCES = {
697
697
  "commercial": """- doc: the document (name, transaction_date or posting_date, valid_till / due_date / delivery_date, customer or supplier and their _name, currency, net_total, total_taxes_and_charges, grand_total, outstanding_amount (invoices), is_return (credit note), remarks, status, docstatus, ...)
698
698
  <<PARTY>>- currency, meta_fields (list of {label, value})
699
699
  - items: list of {idx, item_code, item_name, description, qty, uom, rate, amount, discount_percentage, frequency}
700
+ A line ordered in a further unit of the item (2 Karton of 100) is stored per stock unit: qty 200, uom Stk, rate 2.90. Then item.ordered_in_unit is true and item.order_qty (2), item.order_uom (Karton), item.conversion_factor (100) and item.order_rate (290.00, the price per ordered unit) say what was ordered. Print order_qty + order_uom and order_rate for such a line (the stock quantity may go below); item.amount is the same either way. Never print item.rate with two decimals for it: 12.99 a carton is 0.1299 a piece.
700
701
  A line can carry a deduction (e.g. "Abzüglich bereits verrechnet"): then item.discount_total > 0 (the deduction for the whole line), item.discount_label is its text, and item.gross_rate / item.gross_amount are the full price. Print the full price on the line and a sub-line with the label and −discount_total; item.amount is the net (gross_amount − discount_total). A layout that ignores it prints only the net amount (and gets a warning).
701
702
  - taxes: list of {description, rate, tax_amount, total}
702
703
  <<TEXTS>>- recurring_summary: per billing period [{frequency, label, net_total, grand_total, ...}]; show_frequency: whether any line recurs
@@ -39,6 +39,7 @@ from lambda_erp.stock.reservation import StockReservation
39
39
  from lambda_erp.stock.consignment import ConsignmentWithdrawal
40
40
  from lambda_erp.stock.stock_count import StockCount
41
41
  from lambda_erp.bundles import ItemBundle
42
+ from lambda_erp.units import ItemUnit
42
43
 
43
44
 
44
45
  # --- Doctype registries ---
@@ -75,6 +76,8 @@ DOCUMENT_CLASSES = {
75
76
  # Counted quantities; submitting books the differences with a reason.
76
77
  "Stock Count": StockCount,
77
78
  "Item Bundle": ItemBundle,
79
+ # A further unit of an item (carton of 100) that lines may be entered in.
80
+ "Item Unit": ItemUnit,
78
81
  }
79
82
 
80
83
  CONVERTERS = {
@@ -158,7 +158,7 @@
158
158
  <td>{{ item.item_name or item.description or "" }}{% if item.item_name and item.description and item.description != item.item_name %}<br><span style="color: #555">{{ item.description }}</span>{% endif %}</td>
159
159
  <td>{{ item.warehouse_name or item.warehouse or "" }}</td>
160
160
  <td class="num">{{ "%g"|format(item.qty or 0) }}</td>
161
- <td>{{ item.uom or "" }}</td>
161
+ <td>{{ item.uom or "" }}{% if item.order_uom and item.conversion_factor %}<br><span style="color: #555; font-size: 85%">= {{ "%g"|format(item.order_qty or 0) }} {{ item.order_uom }}</span>{% endif %}</td>
162
162
  </tr>
163
163
  {% endfor %}
164
164
  </tbody>
@@ -154,9 +154,10 @@
154
154
  <td style="font-weight: 600">{{ item.item_code or "" }}</td>
155
155
  <td>{{ item.item_name or item.description or "" }}{% if item.frequency %}<br>{{ item.frequency }}{% endif %}</td>
156
156
  {% if show_warehouse %}<td>{{ item.warehouse or "" }}</td>{% endif %}
157
- <td class="num">{{ item.qty }}</td>
157
+ {# A line ordered in a further unit prints that unit and its price; the stock quantity below. #}
158
+ <td class="num">{% if item.ordered_in_unit %}{{ "%g"|format(item.order_qty or 0) }} {{ item.order_uom }}<br><span style="color: #555; font-size: 85%">= {{ "%g"|format(item.qty or 0) }} {{ item.uom or "" }}</span>{% else %}{{ item.qty }}{% endif %}</td>
158
159
  {% if item.discount_total %}
159
- <td class="num">{{ "%.2f"|format(item.gross_rate) }}</td>
160
+ <td class="num">{{ "%.2f"|format(item.order_gross_rate if item.ordered_in_unit else item.gross_rate) }}</td>
160
161
  <td class="num">{{ "%.2f"|format(item.gross_amount) }}</td>
161
162
  </tr>
162
163
  <tr class="deduction">
@@ -168,7 +169,7 @@
168
169
  <td></td>
169
170
  <td class="num">&minus;{{ "%.2f"|format(item.discount_total) }}</td>
170
171
  {% else %}
171
- <td class="num">{{ "%.2f"|format(item.rate or 0) }}</td>
172
+ <td class="num">{{ "%.2f"|format(item.order_rate if item.ordered_in_unit else (item.rate or 0)) }}</td>
172
173
  <td class="num">{{ "%.2f"|format(item.amount) }}</td>
173
174
  {% endif %}
174
175
  </tr>
@@ -336,7 +336,8 @@ def make_pos_return(posi_name):
336
336
  item_name=item.get("item_name"),
337
337
  description=item.get("description"),
338
338
  qty=-flt(item.get("qty")),
339
- uom=item.get("uom"),
339
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
340
+ conversion_factor=item.get("conversion_factor"),
340
341
  rate=flt(item.get("rate")),
341
342
  income_account=item.get("income_account"),
342
343
  cost_center=item.get("cost_center"),
@@ -469,7 +469,8 @@ def make_purchase_return(pinv_name):
469
469
  item_name=item.get("item_name"),
470
470
  description=item.get("description"),
471
471
  qty=-flt(item.get("qty")),
472
- uom=item.get("uom"),
472
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
473
+ conversion_factor=item.get("conversion_factor"),
473
474
  rate=flt(item.get("rate")),
474
475
  expense_account=item.get("expense_account"),
475
476
  cost_center=item.get("cost_center"),
@@ -457,7 +457,8 @@ def make_sales_return(sinv_name):
457
457
  item_name=item.get("item_name"),
458
458
  description=item.get("description"),
459
459
  qty=-flt(item.get("qty")),
460
- uom=item.get("uom"),
460
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
461
+ conversion_factor=item.get("conversion_factor"),
461
462
  rate=flt(item.get("rate")),
462
463
  income_account=item.get("income_account"),
463
464
  cost_center=item.get("cost_center"),
@@ -118,7 +118,8 @@ def make_purchase_invoice(purchase_order_name):
118
118
  item_name=item.get("item_name"),
119
119
  description=item.get("description"),
120
120
  qty=unbilled,
121
- uom=item.get("uom"),
121
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
122
+ conversion_factor=item.get("conversion_factor"),
122
123
  rate=item.get("rate"),
123
124
  warehouse=item.get("warehouse"),
124
125
  purchase_order=po.name,
@@ -28,6 +28,7 @@ import math
28
28
  from lambda_erp.model import Document
29
29
  from lambda_erp.utils import flt, getdate, nowdate
30
30
  from lambda_erp.database import get_db
31
+ from lambda_erp import units
31
32
  from lambda_erp.exceptions import ValidationError
32
33
 
33
34
 
@@ -244,7 +245,9 @@ def set_item_defaults(doc, party_type=None, party_field=None, *, set_description
244
245
  stamps = "price_source" in db._get_table_columns(doc.CHILD_TABLES["items"][0]) \
245
246
  if "items" in getattr(doc, "CHILD_TABLES", {}) else False
246
247
 
247
- for item in doc.get("items") or []:
248
+ unit_columns = units.has_unit_columns(doc)
249
+
250
+ for position, item in enumerate(doc.get("items") or [], 1):
248
251
  item_code = item.get("item_code")
249
252
  if not item_code:
250
253
  continue
@@ -255,6 +258,15 @@ def set_item_defaults(doc, party_type=None, party_field=None, *, set_description
255
258
  if not item_data:
256
259
  continue
257
260
 
261
+ # A line entered in one of the item's further units (2 Karton) is
262
+ # converted to the stock unit here, before it is priced; see units.py.
263
+ factor = entered_uom = entered_qty = None
264
+ if unit_columns:
265
+ factor = units.pending_factor(item, item_data.stock_uom, f"{doc.DOCTYPE} row {position}")
266
+ if factor:
267
+ entered_uom = str(item.get("uom")).strip()
268
+ entered_qty = units.convert_line(item, item_data.stock_uom, factor)
269
+
258
270
  if not item.get("item_name"):
259
271
  item["item_name"] = item_data.item_name
260
272
  if set_description:
@@ -262,13 +274,28 @@ def set_item_defaults(doc, party_type=None, party_field=None, *, set_description
262
274
  item["uom"] = item.get("uom") or item_data.stock_uom
263
275
 
264
276
  if item.get("rate") is None and item.get("price_list_rate") is None:
265
- row = find_item_price(
266
- item_code, price_list,
267
- qty=flt(item.get("qty", 0)),
268
- party_field=party_field, party=party,
269
- uom=item.get("uom") or item_data.stock_uom,
270
- date=date,
271
- )
277
+ # A price quoted for the entered unit (290.00 per Karton) comes
278
+ # first and is taken per stock unit; else the price per stock
279
+ # unit, with volume breaks counted in stock units.
280
+ row = unit_row = None
281
+ if factor:
282
+ unit_row = find_item_price(
283
+ item_code, price_list, qty=entered_qty,
284
+ party_field=party_field, party=party, uom=entered_uom, date=date)
285
+ if unit_row is not None and unit_row.get("uom") != entered_uom:
286
+ unit_row = None
287
+ row = unit_row
288
+ if row is None:
289
+ row = find_item_price(
290
+ item_code, price_list,
291
+ qty=flt(item.get("qty", 0)),
292
+ party_field=party_field, party=party,
293
+ uom=item.get("uom") or item_data.stock_uom,
294
+ date=date,
295
+ )
296
+ if unit_row is not None:
297
+ row = dict(row)
298
+ row["rate"] = flt(row["rate"]) / factor
272
299
  # Where the base price came from is kept on the line
273
300
  # (price_source / price_reference), see price_resolution.py.
274
301
  if row is None:
@@ -282,3 +309,6 @@ def set_item_defaults(doc, party_type=None, party_field=None, *, set_description
282
309
  item["price_source"], item["price_reference"] = source, reference
283
310
  from lambda_erp.controllers import price_resolution
284
311
  price_resolution.trace_base(item, source, reference, price_list, row)
312
+
313
+ if unit_columns:
314
+ units.stamp_order_qty(item)
@@ -80,6 +80,11 @@ class TaxCalculator:
80
80
  conversion_rate = dec(self.doc.get("conversion_rate") or 1.0)
81
81
 
82
82
  for item in self.doc.get("items"):
83
+ # A line ordered in a further unit (units.py) carries its price
84
+ # per stock unit: 12.99 per carton of 100 is 0.1299 a piece.
85
+ # Rounding that to the cent would move the line amount, so the
86
+ # unit rate keeps six places there; amounts round as always.
87
+ places = 6 if flt(item.get("conversion_factor")) not in (0.0, 1.0) else 2
83
88
  # Apply discount to get rate from price_list_rate
84
89
  if item.get('rate') is not None and flt(item['rate']) == 0:
85
90
  item['rate'] = 0.0
@@ -88,14 +93,14 @@ class TaxCalculator:
88
93
  elif item.get("price_list_rate") is not None and (flt(item['price_list_rate']) != 0 or item.get('rate') is None):
89
94
  list_rate, percent = dec(item["price_list_rate"]), dec(item.get("discount_percentage"))
90
95
  if item.get("rate") is None or percent > 0:
91
- item["rate"] = money(list_rate * (1 - percent / HUNDRED))
92
- item["discount_amount"] = money(list_rate * percent / HUNDRED)
96
+ item["rate"] = money(list_rate * (1 - percent / HUNDRED), places)
97
+ item["discount_amount"] = money(list_rate * percent / HUNDRED, places)
93
98
  elif item.get("discount_amount"):
94
99
  item["rate"] = float(list_rate - dec(item["discount_amount"]))
95
100
 
96
101
  rate = dec(item.get("rate"))
97
102
  # Set net_rate = rate (before inclusive tax adjustment)
98
- item["net_rate"] = money(rate)
103
+ item["net_rate"] = money(rate, places)
99
104
 
100
105
  # Calculate amount: the decimal product, rounded once
101
106
  item["amount"] = money(rate * dec(item.get("qty", 0)))
@@ -3661,6 +3661,35 @@ def _m064_item_bundles(db: "Database") -> None:
3661
3661
  db.ensure_column(table, "bundle_qty", "REAL")
3662
3662
 
3663
3663
 
3664
+ def _m067_item_units(db: "Database") -> None:
3665
+ """Units of measure (see docs/units.md): further units per item with a
3666
+ conversion factor, and on every item line what it was ordered as. No
3667
+ existing line changes: without `order_uom` a line is in the stock unit,
3668
+ as all lines were."""
3669
+ db.conn.execute(db._ddl(
3670
+ """CREATE TABLE IF NOT EXISTS "Item Unit" (
3671
+ name TEXT PRIMARY KEY,
3672
+ item_code TEXT NOT NULL,
3673
+ uom TEXT NOT NULL,
3674
+ conversion_factor REAL DEFAULT 1,
3675
+ enabled INTEGER DEFAULT 1,
3676
+ docstatus INTEGER DEFAULT 0,
3677
+ discarded INTEGER DEFAULT 0,
3678
+ creation TEXT,
3679
+ modified TEXT
3680
+ )"""))
3681
+ db.conn.execute(db._ddl('CREATE INDEX IF NOT EXISTS "ix_item_unit_item_code" ON "Item Unit" (item_code)'))
3682
+ db.conn.commit()
3683
+ db._col_cache.pop("Item Unit", None)
3684
+ db._text_col_cache.pop("Item Unit", None)
3685
+ for table in ("Quotation Item", "Sales Order Item", "Purchase Order Item", "Sales Invoice Item",
3686
+ "Purchase Invoice Item", "Delivery Note Item", "Purchase Receipt Item", "POS Invoice Item",
3687
+ "Stock Entry Detail"):
3688
+ db.ensure_column(table, "order_uom", "TEXT")
3689
+ db.ensure_column(table, "conversion_factor", "REAL")
3690
+ db.ensure_column(table, "order_qty", "REAL")
3691
+
3692
+
3664
3693
  def _m065_record_attachments(db: "Database") -> None:
3665
3694
  """Files kept with a document or master record, and a tracking reference
3666
3695
  on delivery notes (see docs/attachments.md)."""
@@ -3801,6 +3830,7 @@ Database.MIGRATIONS = [
3801
3830
  (64, "item_bundles", _m064_item_bundles),
3802
3831
  (65, "record_attachments", _m065_record_attachments),
3803
3832
  (66, "attachment_sensitivity", _m066_attachment_sensitivity),
3833
+ (67, "item_units", _m067_item_units),
3804
3834
  ]
3805
3835
 
3806
3836
 
@@ -307,6 +307,7 @@ def _core_record_scopes():
307
307
  register_record_scope("Address", "warehouse", unrelated=True)
308
308
  for dimension in ("customer", "warehouse"):
309
309
  register_record_scope("Item Bundle", dimension, unrelated=True)
310
+ register_record_scope("Item Unit", dimension, unrelated=True)
310
311
  for doctype in ("Payment Entry", "Subscription", "Reservation"):
311
312
  register_record_scope(doctype, "customer", "party", when=("party_type", "Customer"))
312
313
  register_record_scope("Journal Entry", "customer", child="accounts", child_table="Journal Entry Account",
@@ -981,9 +982,28 @@ def restore_hidden_values(doctype, stored_rows, new_rows, child):
981
982
  for field in fields:
982
983
  if field in stored:
983
984
  row[field] = stored[field]
985
+ _keep_restored_per_stock_unit(row, stored, fields)
984
986
  return fresh
985
987
 
986
988
 
989
+ def _keep_restored_per_stock_unit(row, stored, fields):
990
+ """A stored line's hidden rate is per stock unit. If the user re-enters the
991
+ line in a further unit of the item (uom "Karton"), saving divides every
992
+ rate on the line by the unit's factor (units.py), which would divide the
993
+ restored rate a second time. The restored values are therefore put back
994
+ per the entered unit, so the conversion ends at the stored price."""
995
+ from lambda_erp import units
996
+ entered = str(row.get("uom") or "").strip()
997
+ if not entered or entered == str(stored.get("uom") or "").strip():
998
+ return
999
+ factor = units.conversion_factor(row.get("item_code"), entered)
1000
+ if not factor:
1001
+ return
1002
+ for field in units.RATE_FIELDS + ("basic_rate", "valuation_rate"):
1003
+ if field in fields and row.get(field) not in (None, ""):
1004
+ row[field] = float(row[field]) * factor
1005
+
1006
+
987
1007
  def require_hidden_complete(doctype, doc, fresh=None):
988
1008
  """After the server has validated a document written by a restricted
989
1009
  user: a new line that needs a hidden value must have got one. `fresh` is
@@ -188,7 +188,8 @@ def make_sales_order(quotation_name):
188
188
  item_name=item.get("item_name"),
189
189
  description=item.get("description"),
190
190
  qty=item.get("qty"),
191
- uom=item.get("uom"),
191
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
192
+ conversion_factor=item.get("conversion_factor"),
192
193
  rate=item.get("rate"),
193
194
  price_list_rate=item.get("price_list_rate"),
194
195
  discount_percentage=item.get("discount_percentage"),
@@ -244,7 +245,8 @@ def make_sales_invoice_from_quotation(quotation_name):
244
245
  item_name=item.get("item_name"),
245
246
  description=item.get("description"),
246
247
  qty=item.get("qty"),
247
- uom=item.get("uom"),
248
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
249
+ conversion_factor=item.get("conversion_factor"),
248
250
  rate=item.get("rate"),
249
251
  price_list_rate=item.get("price_list_rate"),
250
252
  discount_percentage=item.get("discount_percentage"),
@@ -295,7 +297,8 @@ def make_delivery_note_from_quotation(quotation_name):
295
297
  item_name=item.get("item_name"),
296
298
  description=item.get("description"),
297
299
  qty=item.get("qty"),
298
- uom=item.get("uom"),
300
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
301
+ conversion_factor=item.get("conversion_factor"),
299
302
  rate=item.get("rate"),
300
303
  warehouse=item.get("warehouse"),
301
304
  ))
@@ -160,7 +160,8 @@ def make_sales_invoice(sales_order_name):
160
160
  item_name=item.get("item_name"),
161
161
  description=item.get("description"),
162
162
  qty=unbilled_qty,
163
- uom=item.get("uom"),
163
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
164
+ conversion_factor=item.get("conversion_factor"),
164
165
  rate=item.get("rate"),
165
166
  price_list_rate=item.get("price_list_rate"),
166
167
  discount_percentage=item.get("discount_percentage"),
@@ -188,7 +188,8 @@ def make_delivery_note(sales_order_name):
188
188
  item_name=item.get("item_name"),
189
189
  description=item.get("description"),
190
190
  qty=pick["qty"],
191
- uom=item.get("uom"),
191
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
192
+ conversion_factor=item.get("conversion_factor"),
192
193
  rate=item.get("rate"),
193
194
  warehouse=item.get("warehouse"),
194
195
  batch_no=pick.get("batch_no"),
@@ -237,7 +238,8 @@ def make_delivery_return(dn_name):
237
238
  item_name=item.get("item_name"),
238
239
  description=item.get("description"),
239
240
  qty=-flt(item.get("qty")),
240
- uom=item.get("uom"),
241
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
242
+ conversion_factor=item.get("conversion_factor"),
241
243
  rate=flt(item.get("rate")),
242
244
  warehouse=item.get("warehouse"),
243
245
  batch_no=item.get("batch_no"),
@@ -284,7 +286,8 @@ def make_sales_invoice_from_delivery_note(dn_name):
284
286
  item_name=item.get("item_name"),
285
287
  description=item.get("description"),
286
288
  qty=unbilled,
287
- uom=item.get("uom"),
289
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
290
+ conversion_factor=item.get("conversion_factor"),
288
291
  rate=item.get("rate"),
289
292
  price_list_rate=item.get("price_list_rate"),
290
293
  discount_percentage=item.get("discount_percentage"),
@@ -263,7 +263,8 @@ def make_purchase_receipt(purchase_order_name):
263
263
  item_name=item.get("item_name"),
264
264
  description=item.get("description"),
265
265
  qty=unreceived,
266
- uom=item.get("uom"),
266
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
267
+ conversion_factor=item.get("conversion_factor"),
267
268
  rate=item.get("rate"),
268
269
  warehouse=item.get("warehouse"),
269
270
  against_purchase_order=po.name,
@@ -309,7 +310,8 @@ def make_purchase_receipt_return(prec_name):
309
310
  item_name=item.get("item_name"),
310
311
  description=item.get("description"),
311
312
  qty=-flt(item.get("qty")),
312
- uom=item.get("uom"),
313
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
314
+ conversion_factor=item.get("conversion_factor"),
313
315
  rate=flt(item.get("rate")),
314
316
  warehouse=item.get("warehouse"),
315
317
  batch_no=item.get("batch_no"),
@@ -356,7 +358,8 @@ def make_purchase_invoice_from_purchase_receipt(receipt_name):
356
358
  item_name=item.get("item_name"),
357
359
  description=item.get("description"),
358
360
  qty=unbilled,
359
- uom=item.get("uom"),
361
+ uom=item.get("uom"), order_uom=item.get("order_uom"),
362
+ conversion_factor=item.get("conversion_factor"),
360
363
  rate=item.get("rate"),
361
364
  price_list_rate=item.get("price_list_rate"),
362
365
  discount_percentage=item.get("discount_percentage"),
@@ -66,6 +66,10 @@ class StockEntry(Document):
66
66
 
67
67
  if not self.company:
68
68
  raise ValidationError("Stock Entry: Company is required")
69
+ # Lines entered in a further unit of the item (2 Karton) become
70
+ # stock units before anything reads the quantity; see units.py.
71
+ from lambda_erp import units
72
+ units.apply_units(self, rate_fields=("basic_rate", "valuation_rate"))
69
73
  for idx, item in enumerate(self.get("items"), 1):
70
74
  if not item.get('item_code'):
71
75
  raise ValidationError(f"Stock Entry row {idx}: Item Code is required")
@@ -0,0 +1,191 @@
1
+ """Units of measure: ordering and pricing in a pack, stocking in pieces.
2
+
3
+ An item is stocked in one unit, its `stock_uom` ("Stk"). An **Item Unit**
4
+ record gives the item a further unit and says how many stock units it holds:
5
+
6
+ Item Unit GLOVE-M uom "Karton" conversion_factor 100
7
+
8
+ A document line may then be entered in that unit: 2 Karton at 290.00. When
9
+ the document is saved the line is converted to the stock unit and keeps what
10
+ was entered:
11
+
12
+ entered qty 2 uom Karton rate 290.00
13
+ stored qty 200 uom Stk rate 2.90 amount 580.00
14
+ order_uom Karton conversion_factor 100 order_qty 2
15
+
16
+ Quantity and rate are therefore per stock unit on every stored line, and
17
+ everything that reads them (stock ledger, valuation, reservations, picking by
18
+ expiry, deliveries, invoices, backlog, returns, consignment, stock counts)
19
+ needs no knowledge of units. `order_uom`, `conversion_factor` and
20
+ `order_qty` say what the line was ordered as; the factor is a snapshot, so
21
+ changing the Item Unit later does not change a stored document. They follow
22
+ the line into the documents made from it, and `order_qty` is always
23
+ `qty / conversion_factor`: delivering 100 of the 200 shows 1 Karton.
24
+
25
+ A line is converted when its `uom` names one of the item's units. Sending the
26
+ stored line back unchanged (uom = stock unit) converts nothing. A unit the
27
+ item does not have is refused as soon as the item has any Item Unit; items
28
+ without one keep accepting any text in `uom`, as before 1.4.22.
29
+
30
+ See docs/units.md.
31
+ """
32
+ import math
33
+
34
+ from lambda_erp.database import get_db
35
+ from lambda_erp.exceptions import ValidationError
36
+ from lambda_erp.model import Document
37
+ from lambda_erp.utils import flt
38
+
39
+ # Decimal places a converted quantity is kept to.
40
+ QTY_PLACES = 6
41
+ # What is quoted per unit on a line and is divided by the factor with it.
42
+ RATE_FIELDS = ("rate", "price_list_rate", "discount_amount")
43
+
44
+
45
+ class ItemUnit(Document):
46
+ DOCTYPE = "Item Unit"
47
+ CHILD_TABLES = {}
48
+ PREFIX = "IUNIT"
49
+ REQUIRED_FIELDS = ("item_code", "uom", "conversion_factor")
50
+ LINK_FIELDS = {"item_code": "Item"}
51
+ CONDITIONAL_REQUIREMENTS = (
52
+ "conversion_factor is how many stock units (the item's stock_uom) one of this unit holds: "
53
+ "100 for a carton of 100 pieces. It must be a positive number.",
54
+ "uom is the unit's name as it is written on orders (Karton, Pack, VE). It cannot be the item's own "
55
+ "stock_uom, and an item has each unit once.",
56
+ "A document line entered with this uom is converted to the stock unit when saved; the line keeps "
57
+ "order_uom, conversion_factor and order_qty. Changing or disabling a unit does not change stored documents.",
58
+ )
59
+
60
+ def validate(self):
61
+ db = get_db()
62
+ self._data["uom"] = str(self._data.get("uom") or "").strip()
63
+ if not self.item_code:
64
+ raise ValidationError("Item Unit: Item Code is required")
65
+ item = db.get_value("Item", self.item_code, ["name", "stock_uom"])
66
+ if not item:
67
+ raise ValidationError(f"Item Unit: item {self.item_code} does not exist")
68
+ if not self.uom:
69
+ raise ValidationError("Item Unit: UOM is required")
70
+ if self.uom == (item.stock_uom or ""):
71
+ raise ValidationError(
72
+ f"Item Unit: {self.uom} is the stock unit of {self.item_code} itself (factor 1); "
73
+ f"an Item Unit names a further unit")
74
+ try:
75
+ factor = float(self._data.get("conversion_factor"))
76
+ except (TypeError, ValueError):
77
+ raise ValidationError("Item Unit: Conversion Factor must be a number")
78
+ if not math.isfinite(factor) or factor <= 0:
79
+ raise ValidationError("Item Unit: Conversion Factor must be positive")
80
+ self._data["conversion_factor"] = factor
81
+ enabled = self._data.get("enabled")
82
+ self._data["enabled"] = 1 if enabled in (None, "") else int(flt(enabled) != 0)
83
+ twin = db.sql(
84
+ 'SELECT name FROM "Item Unit" WHERE item_code = ? AND uom = ? AND name <> ? '
85
+ 'AND COALESCE(discarded, 0) = 0 LIMIT 1',
86
+ [self.item_code, self.uom, self.name or ""])
87
+ if twin:
88
+ raise ValidationError(
89
+ f"Item Unit: {self.item_code} already has the unit {self.uom} ({twin[0]['name']})")
90
+
91
+
92
+ def _table_ready(db):
93
+ return bool(db._get_table_columns("Item Unit"))
94
+
95
+
96
+ def units_of(item_code):
97
+ """The enabled further units of an item as {uom: conversion_factor}."""
98
+ db = get_db()
99
+ if not item_code or not _table_ready(db):
100
+ return {}
101
+ rows = db.sql(
102
+ 'SELECT uom, conversion_factor FROM "Item Unit" WHERE item_code = ? '
103
+ 'AND COALESCE(enabled, 1) = 1 AND COALESCE(discarded, 0) = 0 ORDER BY uom',
104
+ [item_code])
105
+ return {row["uom"]: flt(row["conversion_factor"]) for row in rows}
106
+
107
+
108
+ def conversion_factor(item_code, uom):
109
+ """Stock units per `uom` for an item, or None if the item has no such unit."""
110
+ return units_of(item_code).get(uom)
111
+
112
+
113
+ def pending_factor(item, stock_uom, label="Row"):
114
+ """The factor a line still has to be converted by, or None.
115
+
116
+ A line is converted when its `uom` is one of the item's units. None for
117
+ a line already in the stock unit, and for an item without any Item Unit
118
+ (its `uom` stays free text). Raises for a unit the item does not have.
119
+ """
120
+ uom = str(item.get("uom") or "").strip()
121
+ if not uom or uom == (stock_uom or ""):
122
+ return None
123
+ units = units_of(item.get("item_code"))
124
+ if not units:
125
+ return None
126
+ factor = units.get(uom)
127
+ if not factor:
128
+ known = ", ".join(f"{name} (= {flt(value):g} {stock_uom})" for name, value in units.items())
129
+ raise ValidationError(
130
+ f"{label}: {uom} is not a unit of item {item.get('item_code')}. It is stocked in {stock_uom}; "
131
+ f"its further units are {known}. Use one of these, or add an Item Unit for {uom} first")
132
+ return factor
133
+
134
+
135
+ def convert_line(item, stock_uom, factor, rate_fields=RATE_FIELDS):
136
+ """Convert one line from the unit in `uom` to the stock unit, in place.
137
+ Returns the quantity as it was entered."""
138
+ entered = flt(item.get("qty"))
139
+ item["order_uom"] = str(item.get("uom")).strip()
140
+ item["conversion_factor"] = factor
141
+ item["qty"] = flt(entered * factor, QTY_PLACES)
142
+ for field in rate_fields:
143
+ if item.get(field) not in (None, ""):
144
+ # Not rounded: 10.00 for a pack of 3 is 3.3333... per piece, and
145
+ # the line amount is rounded once, from quantity x rate.
146
+ item[field] = flt(item[field]) / factor
147
+ item["uom"] = stock_uom
148
+ return entered
149
+
150
+
151
+ def stamp_order_qty(item):
152
+ """Derive `order_qty` (and tidy the snapshot) of a line in the stock unit."""
153
+ factor = flt(item.get("conversion_factor"))
154
+ if item.get("order_uom") and math.isfinite(factor) and factor > 0:
155
+ item["order_qty"] = flt(flt(item.get("qty")) / factor, QTY_PLACES)
156
+ else:
157
+ item["order_uom"] = None
158
+ item["conversion_factor"] = None
159
+ item["order_qty"] = None
160
+
161
+
162
+ def has_unit_columns(doc, child="items"):
163
+ tables = getattr(doc, "CHILD_TABLES", {})
164
+ return child in tables and "order_uom" in get_db()._get_table_columns(tables[child][0])
165
+
166
+
167
+ def apply_units(doc, rate_fields=RATE_FIELDS, child="items"):
168
+ """Convert the lines of a document that were entered in a further unit.
169
+ For documents that do not price their lines (Stock Entry); documents that
170
+ do go through `item_price.set_item_defaults`, which converts and prices
171
+ in one pass."""
172
+ if not has_unit_columns(doc, child):
173
+ return
174
+ db = get_db()
175
+ for idx, item in enumerate(doc.get(child) or [], 1):
176
+ code = item.get("item_code")
177
+ stock_uom = db.get_value("Item", code, "stock_uom") if code else None
178
+ if stock_uom is not None:
179
+ factor = pending_factor(item, stock_uom, f"{doc.DOCTYPE} row {idx}")
180
+ if factor:
181
+ convert_line(item, stock_uom, factor, rate_fields)
182
+ stamp_order_qty(item)
183
+
184
+
185
+ def describe(item, stock_uom=None):
186
+ """"2 Karton (= 100 Stk each)" for a line ordered in a further unit, else ''."""
187
+ if not item.get("order_uom") or not flt(item.get("conversion_factor")):
188
+ return ""
189
+ unit = stock_uom or item.get("uom") or ""
190
+ return (f"{flt(item.get('order_qty')):g} {item['order_uom']} "
191
+ f"(= {flt(item['conversion_factor']):g} {unit} each)").replace(" ", " ")
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "lambda-erp"
3
- version = "1.4.21"
3
+ version = "1.4.22"
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