lambda-erp 1.4.8__tar.gz → 1.4.9__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 (130) hide show
  1. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/PKG-INFO +1 -1
  2. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/chat.py +7 -0
  3. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/main.py +2 -0
  4. lambda_erp-1.4.9/api/pricing_actions.py +47 -0
  5. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/services.py +7 -0
  6. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/controllers/defaults.py +1 -1
  7. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/controllers/item_price.py +48 -11
  8. lambda_erp-1.4.9/lambda_erp/controllers/price_resolution.py +317 -0
  9. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/controllers/pricing_rule.py +101 -31
  10. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/database.py +14 -0
  11. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/pyproject.toml +1 -1
  12. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/.gitignore +0 -0
  13. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/LICENSE +0 -0
  14. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/README.md +0 -0
  15. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/__init__.py +0 -0
  16. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/attachments.py +0 -0
  17. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/auth.py +0 -0
  18. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/bootstrap.py +0 -0
  19. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/chat_links.py +0 -0
  20. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/demo_limits.py +0 -0
  21. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/deps.py +0 -0
  22. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/erp_context.py +0 -0
  23. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/errors.py +0 -0
  24. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/list_values.py +0 -0
  25. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/llm_provider.py +0 -0
  26. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/mcp_oauth.py +0 -0
  27. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/mentions.py +0 -0
  28. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/menu_layout.py +0 -0
  29. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/oauth.py +0 -0
  30. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/pdf.py +0 -0
  31. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/pdf_contract.py +0 -0
  32. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/pdf_exports.py +0 -0
  33. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/pdf_fonts.py +0 -0
  34. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/pdf_pages.py +0 -0
  35. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/pdf_profiles.py +0 -0
  36. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/pdf_templates.py +0 -0
  37. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/providers.py +0 -0
  38. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/record_notes.py +0 -0
  39. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/remarks_md.py +0 -0
  40. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/__init__.py +0 -0
  41. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/accounting.py +0 -0
  42. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/actions.py +0 -0
  43. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/admin.py +0 -0
  44. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/analytics.py +0 -0
  45. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/availability.py +0 -0
  46. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/bank_reconciliation.py +0 -0
  47. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/bank_statements.py +0 -0
  48. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/chat_api.py +0 -0
  49. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/documents.py +0 -0
  50. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/masters.py +0 -0
  51. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/mcp.py +0 -0
  52. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/pdf_templates.py +0 -0
  53. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/proposals.py +0 -0
  54. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/reports.py +0 -0
  55. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/routers/setup.py +0 -0
  56. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/stock_actions.py +0 -0
  57. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/templates/_proposal_totals.html +0 -0
  58. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/templates/_record_base.html +0 -0
  59. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/templates/delivery_note.html +0 -0
  60. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/templates/document.html +0 -0
  61. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/templates/proposal.html +0 -0
  62. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/templates/record.html +0 -0
  63. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/templates/reservation.html +0 -0
  64. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/time_filters.py +0 -0
  65. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/tool_permissions.py +0 -0
  66. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/api/write_context.py +0 -0
  67. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/docs/agents/README.md +0 -0
  68. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/frontend/LICENSE +0 -0
  69. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/frontend/README.md +0 -0
  70. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/frontend/src/api/client.ts +0 -0
  71. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/__init__.py +0 -0
  72. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/__init__.py +0 -0
  73. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/bank_account.py +0 -0
  74. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  75. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/bank_statement_import.py +0 -0
  76. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/bank_transaction.py +0 -0
  77. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/budget.py +0 -0
  78. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/camt.py +0 -0
  79. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  80. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/general_ledger.py +0 -0
  81. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/journal_entry.py +0 -0
  82. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/payment_entry.py +0 -0
  83. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/pos_invoice.py +0 -0
  84. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/purchase_invoice.py +0 -0
  85. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/revaluation.py +0 -0
  86. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/sales_invoice.py +0 -0
  87. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/settlement.py +0 -0
  88. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/__init__.py +0 -0
  89. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/engine.py +0 -0
  90. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/pack.py +0 -0
  91. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  92. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  93. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  94. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  95. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  96. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  97. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/profiles.py +0 -0
  98. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/setup/spine.py +0 -0
  99. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/accounting/subscription.py +0 -0
  100. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/assets/__init__.py +0 -0
  101. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/assets/asset.py +0 -0
  102. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/assets/lifecycle.py +0 -0
  103. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/assets/reservation.py +0 -0
  104. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/buying/__init__.py +0 -0
  105. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/buying/purchase_order.py +0 -0
  106. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/controllers/__init__.py +0 -0
  107. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/controllers/currency.py +0 -0
  108. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/controllers/item_prices.py +0 -0
  109. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  110. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/exceptions.py +0 -0
  111. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/hooks.py +0 -0
  112. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/master_integrity.py +0 -0
  113. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/model.py +0 -0
  114. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/permissions.py +0 -0
  115. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/selling/__init__.py +0 -0
  116. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/selling/proposal.py +0 -0
  117. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/selling/quotation.py +0 -0
  118. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/selling/sales_order.py +0 -0
  119. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/simulation.py +0 -0
  120. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/stock/__init__.py +0 -0
  121. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/stock/delivery_note.py +0 -0
  122. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/stock/purchase_receipt.py +0 -0
  123. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/stock/reservation.py +0 -0
  124. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/stock/stock_entry.py +0 -0
  125. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/stock/stock_ledger.py +0 -0
  126. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/timestamps.py +0 -0
  127. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/utils.py +0 -0
  128. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/validation.py +0 -0
  129. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/lambda_erp/workflow.py +0 -0
  130. {lambda_erp-1.4.8 → lambda_erp-1.4.9}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.8
3
+ Version: 1.4.9
4
4
  Summary: Core ERP logic - accounting, sales, purchasing, inventory
5
5
  Author: TORUS INVESTMENTS AG
6
6
  License-Expression: Apache-2.0
@@ -2918,6 +2918,13 @@ For a complete sales return (financial + stock): create and submit both a Credit
2918
2918
  - **Material Transfer:** Moves stock between warehouses. No GL impact.
2919
2919
  - **Batch Assignment:** Gives stock that has no batch (from before the item was batch-tracked) its batch, in place: row = item_code, qty, t_warehouse, batch_no (+ expiry_date for a new batch). No GL impact, no quantity or value change.
2920
2920
 
2921
+ ### Prices: how they are found, and explaining them
2922
+ - A line without a rate is priced when the document is saved: the Item Price of the document's price list (a row for this customer/supplier beats the list price; the highest min_qty reached; the narrower, then newer validity), else the item's standard rate. Then at most ONE Pricing Rule applies on top: highest priority, then the most specific match, then min_qty, validity and name.
2923
+ - Prices and rules are looked up for the document's date (`pricing_date` if set, else posting/transaction date). A price valid from next month does not apply to a document dated today.
2924
+ - Each line records where its price came from: `price_source` (Item Price, Standard Rate, Entered, Manual, None), `price_reference` (the Item Price) and `pricing_rule`. A rate the user changes on a saved line becomes Manual and is never repriced; converted lines keep the price of their source document.
2925
+ - Use the `explain_price` action to answer "what would X cost for customer Y" and "why is this price what it is" — do not work prices out yourself. If a `price_missing` warning comes back, tell the user there is no price for that item instead of presenting 0.
2926
+ - Deployments may add their own rule keys (for example a price family or a purchasing group); get_document_fields / the rule's `apply_on` and `applicable_for` show what is in use.
2927
+
2921
2928
  ### Reservations, availability and picking (FEFO)
2922
2929
  - available = in stock − blocked (expired or blocked batches) − reserved. Check it with the stock-availability report before promising a delivery.
2923
2930
  - A **Stock Reservation** (doctype `stock-reservation`) sets stock aside: for a sales order line (use the `reserve_sales_order` action, or set `reserve_stock=1` on the Sales Order before submitting it), or free-standing with `remarks` saying what it is for. It is hard: a delivery, issue or transfer that would take reserved stock for someone else is refused with the orders it is reserved for. Deliveries against the order consume its reservation automatically; cancelling the order cancels it; set status Released to give stock back early.
@@ -64,6 +64,8 @@ async def lifespan(app: FastAPI):
64
64
  initialize_record_notes()
65
65
  from api.stock_actions import initialize_stock_actions
66
66
  initialize_stock_actions()
67
+ from api.pricing_actions import initialize_pricing_actions
68
+ initialize_pricing_actions()
67
69
  from api.menu_layout import initialize_menu_layout
68
70
  initialize_menu_layout()
69
71
  from api.pdf_templates import initialize_pdf_templates
@@ -0,0 +1,47 @@
1
+ """Price explanation over REST (/api/actions/explain_price), chat and MCP."""
2
+ from pydantic import Field
3
+
4
+ from api import mentions, services
5
+ from lambda_erp.controllers import price_resolution
6
+
7
+
8
+ class ExplainPrice(mentions.Input):
9
+ doctype: str = Field(default="Sales Order", max_length=100)
10
+ # A line of a saved document ...
11
+ name: str | None = Field(default=None, max_length=200)
12
+ line: str | int | None = None
13
+ # ... or a what-if.
14
+ item_code: str | None = Field(default=None, max_length=200)
15
+ qty: float = Field(default=1, gt=0)
16
+ customer: str | None = Field(default=None, max_length=200)
17
+ supplier: str | None = Field(default=None, max_length=200)
18
+ company: str | None = Field(default=None, max_length=200)
19
+ currency: str | None = Field(default=None, max_length=10)
20
+ date: str | None = Field(default=None, max_length=10)
21
+ uom: str | None = Field(default=None, max_length=50)
22
+ rate: float | None = Field(default=None, ge=0)
23
+
24
+
25
+ def explain(args):
26
+ data = ExplainPrice.model_validate(args)
27
+ doctype = services.SLUG_TO_DOCTYPE.get(data.doctype, data.doctype)
28
+ if data.name:
29
+ return price_resolution.explain_document_line(doctype, data.name, data.line or 1)
30
+ if not data.item_code:
31
+ raise ValueError("Give item_code (with customer or supplier) for a what-if, or name and line of a saved document")
32
+ return price_resolution.explain_price(
33
+ doctype, item_code=data.item_code, qty=data.qty, customer=data.customer, supplier=data.supplier,
34
+ company=data.company, currency=data.currency, date=data.date, uom=data.uom, rate=data.rate)
35
+
36
+
37
+ def initialize_pricing_actions():
38
+ services.register_action(
39
+ "explain_price", explain,
40
+ description=(
41
+ "READ-ONLY. Why a price is what it is. Either a what-if: item_code, qty, customer (or supplier with a "
42
+ "purchase doctype), optional date (the pricing date), currency, company: returns the rate a document "
43
+ "would get, the base price source (Item Price / standard rate / none), the pricing rule applied, the "
44
+ "other rules that matched and any tie. Or a saved line: doctype, name and line (position or row name): "
45
+ "returns the decision stored on that line. Use it before quoting a price and to answer 'why this price'. "
46
+ "Nothing is saved or changed."),
47
+ parameters=ExplainPrice.model_json_schema(), minimum_role="viewer")
@@ -551,6 +551,13 @@ def _document_validation(doc):
551
551
  warnings = []
552
552
  for provider in DOCUMENT_WARNING_PROVIDERS:
553
553
  warnings.extend(provider(doc) or ())
554
+ if "items" in doc.CHILD_TABLES:
555
+ # "I have no list price": say so instead of quietly pricing at zero.
556
+ for idx, row in enumerate(doc.get('items') or [], 1):
557
+ if row.get('price_source') == 'None' and not row.get('rate'):
558
+ warnings.append({'code': 'price_missing', 'message': (
559
+ f"Row {idx}: no price found for {row.get('item_code')} (no Item Price applies and the item "
560
+ f"has no standard rate); the line is priced at 0.")})
554
561
  if doc.DOCTYPE == 'Proposal' and (not doc.get('customer') or not doc.get('company') or not doc.get('quotations')):
555
562
  warnings.append({'code': 'proposal_incomplete', 'message': 'Draft saved; PDF output requires Customer, Company and at least one Quotation.'})
556
563
  if doc.DOCTYPE == "Reservation" and not doc.get("asset") and doc.get("status") in {"Reserved", "Out"}:
@@ -114,7 +114,7 @@ def derived_line_pricing_fields(item):
114
114
  date or a newly added rule); lines added to the new document still get
115
115
  rules."""
116
116
  fields = {field: item.get(field) for field in (
117
- "external_line_reference", "pricing_rule",
117
+ "external_line_reference", "pricing_rule", "price_source", "price_reference",
118
118
  )}
119
119
  fields["ignore_pricing_rule"] = 1
120
120
  return fields
@@ -149,13 +149,39 @@ def resolve_price_list(doc, party_type=None, party_field=None):
149
149
  return None
150
150
 
151
151
 
152
+ def pricing_date(doc):
153
+ """The date prices and rules are looked up for: the document's own
154
+ `pricing_date` when set, else its posting / transaction date, else today.
155
+ A price or rule valid from tomorrow does not apply to a document dated
156
+ today, whenever it is saved."""
157
+ data = doc._data
158
+ return str(data.get("pricing_date") or data.get("posting_date") or data.get("transaction_date") or nowdate())[:10]
159
+
160
+
161
+ def _validity_rank(row):
162
+ """Narrower validity first, then the newer start: (negated width in days,
163
+ start as an ordinal). Open-ended windows are the widest."""
164
+ start, end = row.get("valid_from") or None, row.get("valid_upto") or None
165
+ width = (getdate(end) - getdate(start)).days if start and end else float("inf")
166
+ return (-width, getdate(start).toordinal() if start else 0)
167
+
168
+
152
169
  def get_item_price(item_code, price_list, qty=0, party_field=None, party=None,
153
170
  uom=None, date=None):
154
- """Rate for an item in a price list, or None if the list does not price it.
171
+ """Rate for an item in a price list, or None if the list does not price it."""
172
+ row = find_item_price(item_code, price_list, qty, party_field, party, uom, date)
173
+ return flt(row["rate"]) if row else None
174
+
175
+
176
+ def find_item_price(item_code, price_list, qty=0, party_field=None, party=None,
177
+ uom=None, date=None):
178
+ """The Item Price row that prices an item in a price list, or None.
155
179
 
156
- `party_field` is "customer" or "supplier"; a row naming this party beats an
157
- unnamed list price. Within the same specificity the highest min_qty at or
158
- below `qty` wins, so volume breaks read naturally.
180
+ `party_field` is "customer" or "supplier". Among the rows that apply, in
181
+ this order: a row naming this party beats an unnamed list price; a row
182
+ for this unit beats one for any unit; the highest min_qty at or below
183
+ `qty` (volume breaks); the narrower validity window; the newer
184
+ valid_from; the name. The same inputs always give the same row.
159
185
  """
160
186
  if not price_list or not item_code:
161
187
  return None
@@ -195,9 +221,10 @@ def get_item_price(item_code, price_list, qty=0, party_field=None, party=None,
195
221
 
196
222
  def rank(row):
197
223
  party_match = 1 if (party_field and row.get(party_field)) else 0
198
- return (party_match, flt(row.get("min_qty")), str(row.get("name")))
224
+ unit_match = 1 if (uom and row.get("uom") == uom) else 0
225
+ return (party_match, unit_match, flt(row.get("min_qty")), *_validity_rank(row), str(row.get("name")))
199
226
 
200
- return flt(max(rows, key=rank)["rate"])
227
+ return max(rows, key=rank)
201
228
 
202
229
 
203
230
  def set_item_defaults(doc, party_type=None, party_field=None, *, set_description=True):
@@ -213,7 +240,9 @@ def set_item_defaults(doc, party_type=None, party_field=None, *, set_description
213
240
  db = get_db()
214
241
  price_list = resolve_price_list(doc, party_type, party_field)
215
242
  party = doc._data.get(party_field) if party_field else None
216
- date = doc._data.get("posting_date") or doc._data.get("transaction_date")
243
+ date = pricing_date(doc)
244
+ stamps = "price_source" in db._get_table_columns(doc.CHILD_TABLES["items"][0]) \
245
+ if "items" in getattr(doc, "CHILD_TABLES", {}) else False
217
246
 
218
247
  for item in doc.get("items") or []:
219
248
  item_code = item.get("item_code")
@@ -233,15 +262,23 @@ def set_item_defaults(doc, party_type=None, party_field=None, *, set_description
233
262
  item["uom"] = item.get("uom") or item_data.stock_uom
234
263
 
235
264
  if item.get("rate") is None and item.get("price_list_rate") is None:
236
- rate = get_item_price(
265
+ row = find_item_price(
237
266
  item_code, price_list,
238
267
  qty=flt(item.get("qty", 0)),
239
268
  party_field=party_field, party=party,
240
269
  uom=item.get("uom") or item_data.stock_uom,
241
270
  date=date,
242
271
  )
243
- if rate is None:
272
+ # Where the base price came from is kept on the line
273
+ # (price_source / price_reference), see price_resolution.py.
274
+ if row is None:
244
275
  item["rate"] = flt(item_data.standard_rate)
276
+ source, reference = ("Standard Rate" if flt(item_data.standard_rate) else "None"), None
245
277
  else:
246
- item["price_list_rate"] = rate
247
- item["rate"] = rate
278
+ item["price_list_rate"] = flt(row["rate"])
279
+ item["rate"] = flt(row["rate"])
280
+ source, reference = "Item Price", row["name"]
281
+ if stamps:
282
+ item["price_source"], item["price_reference"] = source, reference
283
+ from lambda_erp.controllers import price_resolution
284
+ price_resolution.trace_base(item, source, reference, price_list, row)
@@ -0,0 +1,317 @@
1
+ """Price resolution: one path for every channel, and an explanation of it.
2
+
3
+ A line's price is resolved in two layers that already exist:
4
+
5
+ 1. the base price: an Item Price of the document's price list (a row for
6
+ the party beats the list price), else Item.standard_rate
7
+ (controllers/item_price.py);
8
+ 2. at most one Pricing Rule on top of it (controllers/pricing_rule.py).
9
+
10
+ Documents run exactly these two steps when they are saved, whatever created
11
+ them (form, REST, chat, MCP, import). This module adds what sits around them:
12
+
13
+ - **dimensions**: match keys a deployment defines for pricing rules, such
14
+ as a price family of items or a purchasing group of customers. The
15
+ deployment says which values an item or party has; the rule engine does
16
+ the matching, ranking and pricing as for its built-in keys.
17
+ - **the decision**: where a line's price came from is kept on the line
18
+ (`price_source`, `price_reference`, `pricing_rule`).
19
+ - **explain**: the same resolution, run on a document that is never saved,
20
+ with the candidates that were considered.
21
+
22
+ See docs/pricing-and-external-sources.md.
23
+ """
24
+ from contextvars import ContextVar
25
+ from dataclasses import dataclass
26
+ from typing import Callable
27
+
28
+ from lambda_erp.database import get_db
29
+ from lambda_erp.exceptions import PermissionDenied, ValidationError
30
+ from lambda_erp.utils import flt
31
+
32
+ PRICE_SOURCES = ("Item Price", "Standard Rate", "Entered", "Manual", "None")
33
+
34
+ BUILTIN_ITEM_KEYS = ("Item Code", "Item Group")
35
+ BUILTIN_PARTY_KEYS = ("Customer", "Customer Group", "Territory", "Supplier", "Supplier Group")
36
+
37
+
38
+ # -- dimensions ---------------------------------------------------------------
39
+
40
+ @dataclass(frozen=True)
41
+ class PriceDimension:
42
+ name: str
43
+ kind: str # "item" or "party"
44
+ resolve: Callable # context -> iterable of values this item / party has
45
+ specificity: int
46
+ party_type: str | None # "Customer" / "Supplier" for a party dimension
47
+
48
+
49
+ _DIMENSIONS: dict[str, PriceDimension] = {}
50
+
51
+
52
+ def register_price_dimension(name, kind, resolve, *, specificity=None, party_type=None):
53
+ """Plugin seam: a match key for pricing rules.
54
+
55
+ `kind="item"` makes `name` selectable as a rule's Apply On (next to Item
56
+ Code and Item Group); `kind="party"` as its Applicable For (next to
57
+ Customer, Customer Group, ...). A rule then names one value of the
58
+ dimension in `apply_on_value` / `applicable_for_value`.
59
+
60
+ `resolve(context)` returns the values the line's item or the document's
61
+ party has in this dimension (a list, possibly empty). `context` carries
62
+ item_code, item_group, customer, customer_group, territory, supplier,
63
+ supplier_group, company, currency, date and side ("selling"/"buying"),
64
+ so buying and selling can be assigned differently.
65
+
66
+ `specificity` ranks a match against the built-in keys when two rules have
67
+ the same priority. Items: Item Code is 2, Item Group is 1 (default 1).
68
+ Parties: Customer / Supplier is 3, the group keys are 2, nobody is 0
69
+ (default 2). A party dimension says which `party_type` it is about.
70
+
71
+ The dimension only says who belongs where. Prices stay in pricing rules.
72
+ """
73
+ if kind not in ("item", "party"):
74
+ raise ValueError('kind must be "item" or "party"')
75
+ name = str(name or "").strip()
76
+ if not name or name in BUILTIN_ITEM_KEYS or name in BUILTIN_PARTY_KEYS:
77
+ raise ValueError(f"{name!r} is not a usable dimension name")
78
+ if kind == "party" and party_type not in ("Customer", "Supplier"):
79
+ raise ValueError('a party dimension needs party_type "Customer" or "Supplier"')
80
+ if specificity is None:
81
+ specificity = 1 if kind == "item" else 2
82
+ _DIMENSIONS[name] = PriceDimension(name, kind, resolve, int(specificity),
83
+ party_type if kind == "party" else None)
84
+
85
+
86
+ def unregister_price_dimension(name):
87
+ _DIMENSIONS.pop(name, None)
88
+
89
+
90
+ def dimensions(kind=None):
91
+ return {name: d for name, d in _DIMENSIONS.items() if kind is None or d.kind == kind}
92
+
93
+
94
+ def strict_conflicts():
95
+ """Setting `pricing_strict_conflicts`: refuse a line when two rules of the
96
+ same priority and specificity apply to it, instead of choosing by the
97
+ remaining tie-breakers. Off by default."""
98
+ db = get_db()
99
+ if not db._get_table_columns("Settings"):
100
+ return False
101
+ rows = db.sql('SELECT value FROM "Settings" WHERE key = ?', ["pricing_strict_conflicts"])
102
+ return bool(rows) and str(rows[0]["value"]).strip().lower() in ("1", "true", "yes", "on")
103
+
104
+
105
+ # -- trace (only while explaining) --------------------------------------------
106
+
107
+ _TRACE = ContextVar("price_resolution_trace", default=None)
108
+
109
+
110
+ def _line_trace(item):
111
+ trace = _TRACE.get()
112
+ if trace is None:
113
+ return None
114
+ return trace.setdefault(id(item), {})
115
+
116
+
117
+ def trace_base(item, source, reference, price_list, row):
118
+ entry = _line_trace(item)
119
+ if entry is None:
120
+ return
121
+ entry["base"] = {"source": source, "reference": reference, "price_list": price_list,
122
+ "rate": flt(item.get("rate")),
123
+ "valid_from": (row or {}).get("valid_from") or None,
124
+ "valid_upto": (row or {}).get("valid_upto") or None,
125
+ "min_qty": flt((row or {}).get("min_qty")) if row else None,
126
+ "party_specific": bool(row and (row.get("customer") or row.get("supplier")))}
127
+
128
+
129
+ def trace_rules(item, rules, applied, tied):
130
+ entry = _line_trace(item)
131
+ if entry is None:
132
+ return
133
+
134
+ def describe(rule):
135
+ key = rule.get("apply_on") or "Item Code"
136
+ who = rule.get("applicable_for") or None
137
+ return {"name": rule.get("name"), "title": rule.get("title"), "priority": int(rule.get("priority") or 0),
138
+ "apply_on": key, "applicable_for": who, "type": rule.get("rate_or_discount"),
139
+ "rate": flt(rule.get("rate")), "discount_percentage": flt(rule.get("discount_percentage")),
140
+ "discount_amount": flt(rule.get("discount_amount")),
141
+ "valid_from": rule.get("valid_from") or None, "valid_upto": rule.get("valid_upto") or None,
142
+ "min_qty": flt(rule.get("min_qty"))}
143
+
144
+ entry["rules"] = [describe(rule) for rule in rules]
145
+ entry["applied_rule"] = describe(applied) if applied else None
146
+ entry["tied_with"] = [rule.get("name") for rule in tied]
147
+
148
+
149
+ # -- explain ------------------------------------------------------------------
150
+
151
+ _SLUGS = {"Quotation": "quotation", "Sales Order": "sales-order", "Sales Invoice": "sales-invoice",
152
+ "POS Invoice": "pos-invoice", "Purchase Order": "purchase-order", "Purchase Invoice": "purchase-invoice"}
153
+ _CLASSES = {
154
+ "Quotation": ("lambda_erp.selling.quotation", "Quotation"),
155
+ "Sales Order": ("lambda_erp.selling.sales_order", "SalesOrder"),
156
+ "Sales Invoice": ("lambda_erp.accounting.sales_invoice", "SalesInvoice"),
157
+ "POS Invoice": ("lambda_erp.accounting.pos_invoice", "POSInvoice"),
158
+ "Purchase Order": ("lambda_erp.buying.purchase_order", "PurchaseOrder"),
159
+ "Purchase Invoice": ("lambda_erp.accounting.purchase_invoice", "PurchaseInvoice"),
160
+ }
161
+ _BUYING = ("Purchase Order", "Purchase Invoice")
162
+
163
+
164
+ def _document_class(doctype):
165
+ if doctype not in _CLASSES:
166
+ raise ValidationError(f"Prices are resolved for: {', '.join(_CLASSES)}")
167
+ module, name = _CLASSES[doctype]
168
+ import importlib
169
+ return getattr(importlib.import_module(module), name)
170
+
171
+
172
+ def _require_explainable(doctype):
173
+ """An explanation names prices, lists and rules: buying-side ones are
174
+ purchase prices."""
175
+ from lambda_erp import permissions
176
+ permissions.require(doctype, "read")
177
+ if doctype in _BUYING and "purchase_price" in permissions.hidden_classes():
178
+ raise PermissionDenied("Your access profile does not allow you to see purchase prices or how they are found")
179
+
180
+
181
+ def _summary(base, rule, line, manual=False, carried=False):
182
+ source = (base or {}).get("source")
183
+ if manual:
184
+ text = "The rate was entered by hand on the saved line; pricing rules no longer change it."
185
+ elif carried:
186
+ text = "The price was carried over from the source document; pricing rules were not run again."
187
+ elif source == "Item Price":
188
+ text = f"Base price from Item Price {base.get('reference')}" + (
189
+ f" of price list {base['price_list']}" if base.get("price_list") else "") + "."
190
+ elif source == "Standard Rate":
191
+ text = "Base price is the item's standard rate (no Item Price applies)."
192
+ elif source == "Entered":
193
+ text = "The rate was given with the line."
194
+ elif source == "None":
195
+ text = "No price source: no Item Price applies and the item has no standard rate."
196
+ else:
197
+ text = "The origin of this price was not recorded (the line predates price decisions)."
198
+ if rule:
199
+ text += f" Pricing rule {rule['name']} ({rule.get('title') or rule.get('type')}) applies."
200
+ return text
201
+
202
+
203
+ def explain_price(doctype="Sales Order", *, item_code, qty=1, customer=None, supplier=None, company=None,
204
+ currency=None, date=None, uom=None, rate=None):
205
+ """What a line would cost and why, without saving anything.
206
+
207
+ Builds a document of `doctype` with this one line and runs the pricing
208
+ steps a real save runs, so the answer is what the document would get.
209
+ `date` is the pricing date. A `rate` is treated as entered by the caller
210
+ (rules then apply on top of it, as they do on a document).
211
+ """
212
+ _require_explainable(doctype)
213
+ cls = _document_class(doctype)
214
+ db = get_db()
215
+ buying = doctype in _BUYING
216
+ if not company:
217
+ rows = db.get_all("Company", fields=["name"], limit=2)
218
+ if len(rows) != 1:
219
+ raise ValidationError("company is required")
220
+ company = rows[0]["name"]
221
+ if not db.exists("Item", item_code):
222
+ raise ValidationError(f"Item {item_code} not found")
223
+ party_field = "supplier" if buying else "customer"
224
+ party = supplier if buying else customer
225
+ if not party:
226
+ raise ValidationError(f"{party_field} is required")
227
+ date_field = "posting_date" if doctype.endswith("Invoice") else "transaction_date"
228
+ line = {"item_code": item_code, "qty": flt(qty) or 1}
229
+ if uom:
230
+ line["uom"] = uom
231
+ if rate is not None:
232
+ line["rate"] = flt(rate)
233
+ doc = cls({"company": company, party_field: party, date_field: date, "pricing_date": date,
234
+ **({"currency": currency} if currency else {}), "items": [line]})
235
+ from lambda_erp.controllers.defaults import set_default_currency
236
+ from lambda_erp.controllers.item_price import pricing_date, resolve_price_list, set_item_defaults
237
+ from lambda_erp.controllers.pricing_rule import apply_pricing_rules
238
+
239
+ party_type = "Supplier" if buying else "Customer"
240
+ set_default_currency(doc, party_type, party_field)
241
+ item = doc.get("items")[0]
242
+ token = _TRACE.set({})
243
+ try:
244
+ set_item_defaults(doc, party_type, party_field)
245
+ if rate is not None:
246
+ trace_base(item, "Entered", None, None, None)
247
+ item["price_source"] = "Entered"
248
+ apply_pricing_rules(doc)
249
+ trace = _TRACE.get().get(id(item), {})
250
+ finally:
251
+ _TRACE.reset(token)
252
+ base, rule = trace.get("base"), trace.get("applied_rule")
253
+ return {
254
+ "doctype": doctype, "item_code": item_code, "qty": flt(item.get("qty")), "uom": item.get("uom"),
255
+ party_field: party, "company": company, "currency": doc._data.get("currency"),
256
+ "pricing_date": pricing_date(doc),
257
+ "price_list": resolve_price_list(doc, party_type, party_field),
258
+ "rate": flt(item.get("rate")),
259
+ "price_list_rate": item.get("price_list_rate"),
260
+ "discount_percentage": flt(item.get("discount_percentage")),
261
+ "discount_amount": flt(item.get("discount_amount")),
262
+ "price_source": (base or {}).get("source"),
263
+ "price_reference": (base or {}).get("reference"),
264
+ "base": base,
265
+ "pricing_rule": rule,
266
+ "tied_with": trace.get("tied_with") or [],
267
+ "rules_considered": trace.get("rules") or [],
268
+ "explanation": _summary(base, rule, item),
269
+ }
270
+
271
+
272
+ def explain_document_line(doctype, name, line=1):
273
+ """The stored price decision of one line of a saved document (`line` is
274
+ its row name or its 1-based position), with the validity of the Item
275
+ Price and rule it names as they are now."""
276
+ _require_explainable(doctype)
277
+ cls = _document_class(doctype)
278
+ from lambda_erp import permissions
279
+ permissions.require_record_visible(doctype, name)
280
+ doc = cls.load(name)
281
+ rows = doc.get("items") or []
282
+ if isinstance(line, int) or str(line).isdigit():
283
+ index = int(line) - 1
284
+ row = rows[index] if 0 <= index < len(rows) else None
285
+ else:
286
+ row = next((r for r in rows if r.get("name") == line), None)
287
+ if row is None:
288
+ raise ValidationError(f"{doctype} {name} has no line {line}")
289
+ db = get_db()
290
+ source, reference = row.get("price_source"), row.get("price_reference")
291
+ base = {"source": source, "reference": reference} if source else None
292
+ if source == "Item Price" and reference:
293
+ price = db.get_value("Item Price", reference, ["price_list", "rate", "valid_from", "valid_upto", "customer", "supplier"])
294
+ if price:
295
+ base.update({"price_list": price.get("price_list"), "current_rate": flt(price.get("rate")),
296
+ "valid_from": price.get("valid_from") or None, "valid_upto": price.get("valid_upto") or None,
297
+ "party_specific": bool(price.get("customer") or price.get("supplier"))})
298
+ rule = None
299
+ if row.get("pricing_rule"):
300
+ stored = db.get_value("Pricing Rule", row["pricing_rule"], ["name", "title", "priority", "rate_or_discount",
301
+ "valid_from", "valid_upto", "enabled"])
302
+ rule = {"name": row["pricing_rule"], **({
303
+ "title": stored.get("title"), "priority": int(stored.get("priority") or 0),
304
+ "type": stored.get("rate_or_discount"), "valid_from": stored.get("valid_from") or None,
305
+ "valid_upto": stored.get("valid_upto") or None, "enabled": bool(stored.get("enabled"))} if stored else {})}
306
+ manual = source == "Manual"
307
+ carried = bool(flt(row.get("ignore_pricing_rule"))) and not manual
308
+ from lambda_erp.controllers.item_price import pricing_date
309
+ return {
310
+ "doctype": doctype, "name": name, "line": row.get("name"), "item_code": row.get("item_code"),
311
+ "qty": flt(row.get("qty")), "rate": flt(row.get("rate")), "price_list_rate": row.get("price_list_rate"),
312
+ "discount_percentage": flt(row.get("discount_percentage")), "discount_amount": flt(row.get("discount_amount")),
313
+ "pricing_date": pricing_date(doc), "docstatus": doc.docstatus,
314
+ "price_source": source, "price_reference": reference, "base": base, "pricing_rule": rule,
315
+ "manual": manual, "rules_skipped": bool(flt(row.get("ignore_pricing_rule")) or flt(doc.get("ignore_pricing_rule"))),
316
+ "explanation": _summary(base, rule, row, manual=manual, carried=carried),
317
+ }