lambda-erp 1.4.15__tar.gz → 1.4.17__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 (135) hide show
  1. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/PKG-INFO +1 -1
  2. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/auth.py +8 -0
  3. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/chat.py +8 -0
  4. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/pdf.py +16 -0
  5. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/masters.py +20 -0
  6. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/services.py +8 -2
  7. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/templates/delivery_note.html +11 -1
  8. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/templates/document.html +11 -1
  9. lambda_erp-1.4.17/lambda_erp/addresses.py +191 -0
  10. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/controllers/price_resolution.py +1 -1
  11. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/controllers/pricing_rule.py +2 -2
  12. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/database.py +65 -0
  13. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/model.py +4 -0
  14. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/permissions.py +2 -0
  15. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/stock/delivery_note.py +14 -15
  16. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/stock/purchase_receipt.py +74 -15
  17. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/stock/reservation.py +167 -17
  18. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/workflow.py +54 -33
  19. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/pyproject.toml +1 -1
  20. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/.gitignore +0 -0
  21. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/LICENSE +0 -0
  22. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/README.md +0 -0
  23. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/__init__.py +0 -0
  24. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/attachments.py +0 -0
  25. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/bootstrap.py +0 -0
  26. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/chat_links.py +0 -0
  27. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/demo_limits.py +0 -0
  28. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/deps.py +0 -0
  29. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/erp_context.py +0 -0
  30. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/errors.py +0 -0
  31. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/list_values.py +0 -0
  32. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/llm_provider.py +0 -0
  33. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/main.py +0 -0
  34. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/mcp_oauth.py +0 -0
  35. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/mentions.py +0 -0
  36. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/menu_layout.py +0 -0
  37. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/oauth.py +0 -0
  38. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/pdf_contract.py +0 -0
  39. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/pdf_exports.py +0 -0
  40. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/pdf_fonts.py +0 -0
  41. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/pdf_pages.py +0 -0
  42. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/pdf_profiles.py +0 -0
  43. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/pdf_templates.py +0 -0
  44. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/pricing_actions.py +0 -0
  45. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/providers.py +0 -0
  46. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/record_notes.py +0 -0
  47. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/remarks_md.py +0 -0
  48. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/__init__.py +0 -0
  49. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/accounting.py +0 -0
  50. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/actions.py +0 -0
  51. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/admin.py +0 -0
  52. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/analytics.py +0 -0
  53. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/availability.py +0 -0
  54. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/bank_reconciliation.py +0 -0
  55. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/bank_statements.py +0 -0
  56. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/chat_api.py +0 -0
  57. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/documents.py +0 -0
  58. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/mcp.py +0 -0
  59. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/pdf_templates.py +0 -0
  60. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/proposals.py +0 -0
  61. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/reports.py +0 -0
  62. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/routers/setup.py +0 -0
  63. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/stock_actions.py +0 -0
  64. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/templates/_proposal_totals.html +0 -0
  65. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/templates/_record_base.html +0 -0
  66. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/templates/proposal.html +0 -0
  67. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/templates/record.html +0 -0
  68. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/templates/reservation.html +0 -0
  69. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/time_filters.py +0 -0
  70. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/tool_permissions.py +0 -0
  71. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/api/write_context.py +0 -0
  72. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/docs/agents/README.md +0 -0
  73. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/frontend/LICENSE +0 -0
  74. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/frontend/README.md +0 -0
  75. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/frontend/src/api/client.ts +0 -0
  76. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/__init__.py +0 -0
  77. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/__init__.py +0 -0
  78. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/bank_account.py +0 -0
  79. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  80. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/bank_statement_import.py +0 -0
  81. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/bank_transaction.py +0 -0
  82. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/budget.py +0 -0
  83. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/camt.py +0 -0
  84. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  85. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/general_ledger.py +0 -0
  86. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/journal_entry.py +0 -0
  87. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/payment_entry.py +0 -0
  88. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/pos_invoice.py +0 -0
  89. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/purchase_invoice.py +0 -0
  90. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/revaluation.py +0 -0
  91. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/sales_invoice.py +0 -0
  92. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/settlement.py +0 -0
  93. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/__init__.py +0 -0
  94. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/engine.py +0 -0
  95. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/pack.py +0 -0
  96. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  97. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  98. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  99. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  100. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  101. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  102. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/profiles.py +0 -0
  103. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/setup/spine.py +0 -0
  104. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/accounting/subscription.py +0 -0
  105. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/assets/__init__.py +0 -0
  106. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/assets/asset.py +0 -0
  107. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/assets/lifecycle.py +0 -0
  108. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/assets/reservation.py +0 -0
  109. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/backlog.py +0 -0
  110. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/buying/__init__.py +0 -0
  111. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/buying/purchase_order.py +0 -0
  112. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/controllers/__init__.py +0 -0
  113. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/controllers/currency.py +0 -0
  114. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/controllers/defaults.py +0 -0
  115. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/controllers/item_price.py +0 -0
  116. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/controllers/item_prices.py +0 -0
  117. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  118. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/exceptions.py +0 -0
  119. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/hooks.py +0 -0
  120. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/master_integrity.py +0 -0
  121. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/selling/__init__.py +0 -0
  122. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/selling/proposal.py +0 -0
  123. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/selling/quotation.py +0 -0
  124. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/selling/sales_order.py +0 -0
  125. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/simulation.py +0 -0
  126. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/stock/__init__.py +0 -0
  127. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/stock/consignment.py +0 -0
  128. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/stock/serial.py +0 -0
  129. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/stock/stock_count.py +0 -0
  130. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/stock/stock_entry.py +0 -0
  131. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/stock/stock_ledger.py +0 -0
  132. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/timestamps.py +0 -0
  133. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/utils.py +0 -0
  134. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/lambda_erp/validation.py +0 -0
  135. {lambda_erp-1.4.15 → lambda_erp-1.4.17}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.15
3
+ Version: 1.4.17
4
4
  Summary: Core ERP logic - accounting, sales, purchasing, inventory
5
5
  Author: TORUS INVESTMENTS AG
6
6
  License-Expression: Apache-2.0
@@ -584,6 +584,14 @@ def _describe_restrictions(user):
584
584
  names = {route.path.rsplit("/", 1)[-1] for route in reports.router.routes
585
585
  if getattr(route, "path", "").startswith("/reports/") and "{" not in route.path}
586
586
  names |= set(services.REGISTERED_REPORTS)
587
+ # Fields hidden on document types the user can open, so a form does
588
+ # not show inputs for them: {slug: {"" | child key: [field, ...]}}.
589
+ hidden = {}
590
+ for slug, doctype in services.SLUG_TO_DOCTYPE.items():
591
+ plan = permissions.hidden_write_plan(doctype)
592
+ if plan and permissions.can(doctype, "read"):
593
+ hidden[slug] = {child: sorted(fields) for child, fields in plan.items()}
594
+ described["hidden_fields"] = hidden
587
595
  described["denied_reports"] = sorted(name for name in names if permissions.artifact_denied("report", name))
588
596
  return described
589
597
 
@@ -3009,6 +3009,8 @@ For a complete sales return (financial + stock): create and submit both a Credit
3009
3009
  - Order progress is derived from the submitted documents, per order line: delivered_qty (net of returns), returned_qty, billed_qty. Never set them. Open = qty − delivered_qty.
3010
3010
  - A delivery for less than ordered leaves the rest of the line open; convert the order again later for the remainder. Converters only ever propose what is left, and submit rechecks, so a repeated conversion cannot deliver or bill twice.
3011
3011
  - Deliver first, invoice after: convert the submitted **Delivery Note** to a Sales Invoice (convert_document doctype="delivery-note", target_doctype="Sales Invoice"). It bills what that delivery delivered and has not been billed, and does not move stock again. Converting the Sales Order to a Sales Invoice instead bills the ordered quantity regardless of delivery.
3012
+ - Receive first, invoice after works the same on the purchasing side: convert the submitted **Purchase Receipt** to a Purchase Invoice (convert_document doctype="purchase-receipt", target_doctype="Purchase Invoice"). It bills what was received and not billed, at the received price, and does not move stock again.
3013
+ - A Stock Reservation can name `batch_no` and / or `location` to hold exactly that stock; without them it holds a quantity in the warehouse and the batch is decided when picking.
3012
3014
  - "What is still open / on backorder / can go out now" → sales-backlog report. "Is it on order, and when does it come" → the same report's purchase order columns, or purchase-backlog.
3013
3015
  - When a supplier's order confirmation arrives, record its date with the `confirm_purchase_order` action.
3014
3016
 
@@ -3032,6 +3034,12 @@ For a complete sales return (financial + stock): create and submit both a Credit
3032
3034
  - Never invent or guess a serial number. If the user has not given them, ask; to see what is in stock use search_masters master_type="serial-no" (filter item_code, warehouse) or the serial-trace report for one number.
3033
3035
  - Units from before the item was serial-tracked have no number: give them one with a Stock Entry of type "Serial Assignment" (item_code, qty, t_warehouse, serial_no).
3034
3036
 
3037
+ ### Addresses
3038
+ - 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.
3039
+ - 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.
3040
+ - When an order names where the goods must go and that address is not on record, put the text in `shipping_address_display` (recipient first, one line per row) without a link: what the document says takes precedence. Do not create an address record for a one-off address unless the user asks.
3041
+ - Never guess between several addresses of a customer: use the default, or ask.
3042
+
3035
3043
  ### Storage locations (places inside a warehouse)
3036
3044
  - A warehouse with `use_locations=1` has storage locations (master `storage-location`: warehouse + location label, e.g. "A12"). The same label may exist in several warehouses.
3037
3045
  - In such a warehouse every stock-moving line names its location: `location` on Delivery Note, Purchase Receipt and invoice lines (with update_stock=1); on Stock Entry lines `s_location` for the source side and `t_location` for the target side. Drafts may be saved without it; submit is refused. A warehouse without storage locations takes no location.
@@ -311,6 +311,18 @@ def _render_commercial_pdf(doctype, name, doc, contract, layout=None, blocked=No
311
311
  line.lstrip().startswith(">>") for line in _remarks.splitlines()
312
312
  )
313
313
 
314
+ # The document's own addresses (lambda_erp/addresses.py): a delivery note
315
+ # is addressed to where the goods go, everything else to where the
316
+ # invoice goes, with the delivery address below it when it differs.
317
+ from lambda_erp.addresses import delivery_instructions, document_address_lines
318
+ billing_lines = document_address_lines(doc, "billing")
319
+ shipping_lines = document_address_lines(doc, "shipping")
320
+ if file == "delivery_note.html":
321
+ address_lines, delivery_lines = shipping_lines or billing_lines, []
322
+ else:
323
+ address_lines = billing_lines
324
+ delivery_lines = shipping_lines if shipping_lines and shipping_lines != billing_lines else []
325
+
314
326
  context = dict(
315
327
  doc=doc,
316
328
  pdf_status=contract["status"],
@@ -322,6 +334,10 @@ def _render_commercial_pdf(doctype, name, doc, contract, layout=None, blocked=No
322
334
  party_label=party_label,
323
335
  party_name=party_name,
324
336
  party_info=party_info,
337
+ address_lines=address_lines,
338
+ delivery_lines=delivery_lines,
339
+ delivery_label="Delivery address",
340
+ delivery_instructions=delivery_instructions(doc) if file == "delivery_note.html" else None,
325
341
  currency=currency,
326
342
  meta_fields=meta_fields,
327
343
  items=items,
@@ -67,6 +67,10 @@ DELETE_REFERENCE_CHECKS = {
67
67
  "serial-no": [
68
68
  ('SELECT 1 FROM "Serial Movement" WHERE serial = ? LIMIT 1', "stock movement"),
69
69
  ],
70
+ "address": [
71
+ (f'SELECT 1 FROM "{table}" WHERE billing_address = ? OR shipping_address = ? LIMIT 1', table.lower())
72
+ for table in ("Quotation", "Sales Order", "Delivery Note", "Sales Invoice")
73
+ ],
70
74
  "storage-location": [
71
75
  ('SELECT 1 FROM "Stock Ledger Entry" s JOIN "Storage Location" l ON l.warehouse = s.warehouse '
72
76
  'AND l.location = s.location WHERE l.name = ? LIMIT 1', "stock ledger entry"),
@@ -221,6 +225,8 @@ def _normalize_master_data(data: dict) -> dict:
221
225
 
222
226
  MASTER_LINK_FIELDS = {
223
227
  'customer': {'default_price_list': 'Price List'},
228
+ 'supplier': {'default_price_list': 'Price List'},
229
+ 'address': {'customer': 'Customer'},
224
230
  'company': {'default_price_list': 'Price List'},
225
231
  'item': {'default_warehouse': 'Warehouse'},
226
232
  'warehouse': {'company': 'Company', 'account': 'Account', 'parent_warehouse': 'Warehouse',
@@ -283,6 +289,11 @@ def _validate_master_input(master_type, doctype, data, name=None):
283
289
  raise ValidationError('Cannot change master identity; create a new record instead')
284
290
  merged = dict(db.get_value(doctype, name, list(allowed)) or {}) if name else {}
285
291
  merged.update(data)
292
+ if master_type == 'address':
293
+ # The title is made from customer, label and town, never typed.
294
+ from lambda_erp.addresses import address_title
295
+ merged['address_title'] = data['address_title'] = address_title(
296
+ merged, db.get_value('Customer', merged.get('customer'), 'customer_name') if merged.get('customer') else None)
286
297
  for field in master_requirements(master_type)['required']:
287
298
  if missing(merged.get(field)):
288
299
  raise ValidationError(f'{doctype}: {field} is required')
@@ -297,6 +308,9 @@ def _validate_master_input(master_type, doctype, data, name=None):
297
308
  _validate_batch(db, merged, name)
298
309
  if master_type == 'serial-no':
299
310
  _validate_serial(db, data, name)
311
+ if master_type == 'address':
312
+ from lambda_erp.addresses import validate_address
313
+ validate_address(merged)
300
314
  # A user restricted to assigned records cannot write one outside of them
301
315
  # (a new customer or warehouse is never one of the assigned).
302
316
  permissions.require_record_in_scope(doctype, {**merged, 'name': name})
@@ -479,6 +493,9 @@ def _create_master_record(master_type: str, data: dict) -> dict:
479
493
  doc["default_currency"] = companies[0].get("default_currency") or "USD"
480
494
 
481
495
  db.insert(doctype, doc)
496
+ if master_type == 'address':
497
+ from lambda_erp.addresses import finish_address
498
+ finish_address(doc["name"])
482
499
  row = db.get_all(doctype, filters={"name": doc["name"]}, fields=["*"])[0]
483
500
  return _echo_identity_alias(master_type, row)
484
501
 
@@ -537,6 +554,9 @@ def _update_master_record(master_type: str, name: str, data: dict) -> dict:
537
554
  update_fields["modified"] = now()
538
555
  if update_fields:
539
556
  db.set_value(doctype, name, update_fields)
557
+ if master_type == 'address':
558
+ from lambda_erp.addresses import finish_address
559
+ finish_address(name)
540
560
  if master_type == 'batch':
541
561
  # A batch's expiry date and block decide what may be sold: keep the trail.
542
562
  from lambda_erp.stock.stock_ledger import log_batch_changes
@@ -23,7 +23,9 @@ from lambda_erp.stock.stock_entry import StockEntry
23
23
  from lambda_erp.stock.delivery_note import (
24
24
  DeliveryNote, make_delivery_note, make_delivery_return, make_sales_invoice_from_delivery_note,
25
25
  )
26
- from lambda_erp.stock.purchase_receipt import PurchaseReceipt, make_purchase_receipt, make_purchase_receipt_return
26
+ from lambda_erp.stock.purchase_receipt import (
27
+ PurchaseReceipt, make_purchase_receipt, make_purchase_receipt_return, make_purchase_invoice_from_purchase_receipt,
28
+ )
27
29
  from lambda_erp.accounting.pos_invoice import POSInvoice
28
30
  from lambda_erp.controllers.pricing_rule import PricingRule
29
31
  from lambda_erp.controllers.item_price import PriceList, ItemPrice
@@ -82,6 +84,7 @@ CONVERTERS = {
82
84
  ("Delivery Note", "Sales Invoice"): make_sales_invoice_from_delivery_note,
83
85
  ("Purchase Order", "Purchase Invoice"): make_purchase_invoice,
84
86
  ("Purchase Order", "Purchase Receipt"): make_purchase_receipt,
87
+ ("Purchase Receipt", "Purchase Invoice"): make_purchase_invoice_from_purchase_receipt,
85
88
  # Returns (same-to-same conversion creates a return document)
86
89
  ("Sales Invoice", "Sales Invoice"): make_sales_return,
87
90
  ("Purchase Invoice", "Purchase Invoice"): make_purchase_return,
@@ -103,6 +106,8 @@ MASTER_TABLES = {
103
106
  "storage-location": ("Storage Location", "location"),
104
107
  # One row per (item, serial number); written by the stock ledger.
105
108
  "serial-no": ("Serial No", "serial_no"),
109
+ # Further addresses of a customer (lambda_erp/addresses.py).
110
+ "address": ("Address", "address_title"),
106
111
  }
107
112
 
108
113
  # Auto-naming prefixes: masters created without an explicit `name` get a
@@ -115,11 +120,12 @@ MASTER_NAME_PREFIXES = {
115
120
  "warehouse": "WH",
116
121
  "batch": "BATCH",
117
122
  "storage-location": "LOC",
123
+ "address": "ADDR",
118
124
  }
119
125
 
120
126
  # Minimum numeric suffix width for sequential plugin master ids. Core masters
121
127
  # retain the historical three-digit form; plugins can opt into e.g. FIDX-0001.
122
- MASTER_NAME_DIGITS: dict[str, int] = {"batch": 5, "storage-location": 5}
128
+ MASTER_NAME_DIGITS: dict[str, int] = {"batch": 5, "storage-location": 5, "address": 5}
123
129
 
124
130
  # High-volume plugin masters can opt out of sequential ids. Sequential naming
125
131
  # must inspect existing suffixes after a process restart; opaque random ids keep
@@ -100,14 +100,24 @@
100
100
  </div>
101
101
  <div class="party-block" style="text-align: right;">
102
102
  <h3>{{ party_label }}</h3>
103
- <div class="name">{{ party_name }}</div>
103
+ <div class="name">{{ address_lines[0] if address_lines else party_name }}</div>
104
104
  {% if party_info %}
105
+ {% if address_lines %}
106
+ {# The document's own address (lambda_erp/addresses.py); its first line is the recipient. #}
107
+ {% for line in address_lines[1:] %}<div class="detail">{{ line }}</div>{% endfor %}
108
+ {% else %}
105
109
  {% if party_info.get("address") %}<div class="detail">{{ party_info.address }}</div>{% endif %}
106
110
  {% if party_info.get("city") or party_info.get("zip_code") or party_info.get("country") %}<div class="detail">{{ party_info.get("city", "") }}{% if party_info.get("zip_code") %} {{ party_info.zip_code }}{% endif %}{% if party_info.get("country") %}, {{ party_info.country }}{% endif %}</div>{% endif %}
111
+ {% endif %}
107
112
  {% if party_info.get("email") %}<div class="detail">{{ party_info.email }}</div>{% endif %}
108
113
  {% if party_info.get("phone") %}<div class="detail">{{ party_info.phone }}</div>{% endif %}
109
114
  {% if party_info.get("tax_id") %}<div class="detail">Tax ID: {{ party_info.tax_id }}</div>{% endif %}
110
115
  {% endif %}
116
+ {% if delivery_lines %}
117
+ <div class="detail" style="margin-top: 6px;"><strong>{{ delivery_label }}</strong></div>
118
+ {% for line in delivery_lines %}<div class="detail">{{ line }}</div>{% endfor %}
119
+ {% endif %}
120
+ {% if delivery_instructions %}<div class="detail" style="margin-top: 4px;">{{ delivery_instructions }}</div>{% endif %}
111
121
  </div>
112
122
  </div>
113
123
 
@@ -96,14 +96,24 @@
96
96
  </div>
97
97
  <div class="party-block" style="text-align: right;">
98
98
  <h3>{{ party_label }}</h3>
99
- <div class="name">{{ party_name }}</div>
99
+ <div class="name">{{ address_lines[0] if address_lines else party_name }}</div>
100
100
  {% if party_info %}
101
+ {% if address_lines %}
102
+ {# The document's own address (lambda_erp/addresses.py); its first line is the recipient. #}
103
+ {% for line in address_lines[1:] %}<div class="detail">{{ line }}</div>{% endfor %}
104
+ {% else %}
101
105
  {% if party_info.get("address") %}<div class="detail">{{ party_info.address }}</div>{% endif %}
102
106
  {% if party_info.get("city") or party_info.get("zip_code") or party_info.get("country") %}<div class="detail">{{ party_info.get("city", "") }}{% if party_info.get("zip_code") %} {{ party_info.zip_code }}{% endif %}{% if party_info.get("country") %}, {{ party_info.country }}{% endif %}</div>{% endif %}
107
+ {% endif %}
103
108
  {% if party_info.get("email") %}<div class="detail">{{ party_info.email }}</div>{% endif %}
104
109
  {% if party_info.get("phone") %}<div class="detail">{{ party_info.phone }}</div>{% endif %}
105
110
  {% if party_info.get("tax_id") %}<div class="detail">Tax ID: {{ party_info.tax_id }}</div>{% endif %}
106
111
  {% endif %}
112
+ {% if delivery_lines %}
113
+ <div class="detail" style="margin-top: 6px;"><strong>{{ delivery_label }}</strong></div>
114
+ {% for line in delivery_lines %}<div class="detail">{{ line }}</div>{% endfor %}
115
+ {% endif %}
116
+ {% if delivery_instructions %}<div class="detail" style="margin-top: 4px;">{{ delivery_instructions }}</div>{% endif %}
107
117
  </div>
108
118
  </div>
109
119
 
@@ -0,0 +1,191 @@
1
+ """Several addresses per customer, and the two a sales document uses.
2
+
3
+ A customer keeps its main address on the customer record, as before. On top
4
+ of it, any number of Address records: accounting, central store, a ward.
5
+ Each says what it is for (invoices, deliveries or both) and one of each kind
6
+ can be the default.
7
+
8
+ A sales document (quotation, sales order, delivery note, sales invoice)
9
+ carries an invoice address and a delivery address. Each is a link to an
10
+ Address plus the text as it is printed:
11
+
12
+ billing_address / billing_address_display
13
+ shipping_address / shipping_address_display
14
+
15
+ The text is a copy taken when the document is saved, so a document that was
16
+ issued keeps its address when the master changes. It can be edited for one
17
+ document, or typed in without a link when an order names an address that is
18
+ not on record: what the document says takes precedence.
19
+
20
+ Where a document has neither, it inherits from the document it was made
21
+ from (order from quotation, delivery from order, invoice from delivery or
22
+ order); else it takes the customer's default of that kind; else it stays
23
+ empty and the customer's main address is printed.
24
+
25
+ See docs/addresses.md.
26
+ """
27
+ from lambda_erp.database import get_db
28
+ from lambda_erp.exceptions import ValidationError
29
+ from lambda_erp.utils import flt, now
30
+
31
+ # document type -> where an inherited address comes from: (line field naming
32
+ # the source line or document, table to resolve a line to its document or
33
+ # None, source document type), first match wins.
34
+ SOURCES = {
35
+ "Quotation": (),
36
+ "Sales Order": (("quotation_item", "Quotation Item", "Quotation"),),
37
+ "Delivery Note": (("against_sales_order", None, "Sales Order"),),
38
+ "Sales Invoice": (("delivery_note", None, "Delivery Note"), ("sales_order", None, "Sales Order")),
39
+ }
40
+ KINDS = {"billing": ("is_billing", "is_default_billing", "invoices"),
41
+ "shipping": ("is_shipping", "is_default_shipping", "deliveries")}
42
+
43
+
44
+ def register_address_document(doctype, sources=()):
45
+ """Plugin seam: a further document type with a customer that carries
46
+ billing_address / shipping_address (and their _display columns, which the
47
+ plugin adds to its table). `sources` as in SOURCES."""
48
+ SOURCES[doctype] = tuple(sources)
49
+
50
+
51
+ def format_address(address, customer_name=None):
52
+ """An Address record as the lines that are printed."""
53
+ lines = [address.get("recipient_name") or customer_name or "", address.get("contact_person") or "",
54
+ *str(address.get("address") or "").splitlines(),
55
+ " ".join(part for part in (address.get("zip_code"), address.get("city")) if part),
56
+ address.get("country") or ""]
57
+ return "\n".join(line.strip() for line in lines if line and line.strip())
58
+
59
+
60
+ def address_title(address, customer_name=None):
61
+ """What an address is called when picking it: customer, label, town."""
62
+ parts = [customer_name or address.get("customer") or "", address.get("label") or "", address.get("city") or ""]
63
+ return ", ".join(part for part in parts if part)
64
+
65
+
66
+ def _columns(doctype):
67
+ return get_db()._get_table_columns(doctype)
68
+
69
+
70
+ def _source_addresses(doc):
71
+ """(billing link, billing text, shipping link, shipping text) of the
72
+ document this one was made from, or None."""
73
+ db = get_db()
74
+ for field, line_table, source in SOURCES.get(doc.DOCTYPE, ()):
75
+ if "billing_address" not in _columns(source):
76
+ continue
77
+ for row in doc.get("items") or ():
78
+ reference = row.get(field)
79
+ if not reference:
80
+ continue
81
+ parent = db.get_value(line_table, reference, "parent") if line_table else reference
82
+ found = db.get_value(source, parent, ["customer", "billing_address", "billing_address_display",
83
+ "shipping_address", "shipping_address_display"]) if parent else None
84
+ if found and found.get("customer") == doc.get("customer"):
85
+ return found
86
+ return None
87
+
88
+
89
+ def default_address(customer, kind):
90
+ """The customer's default Address of a kind ('billing' / 'shipping'), or None."""
91
+ usable, default, _ = KINDS[kind]
92
+ rows = get_db().sql(
93
+ f'SELECT name FROM "Address" WHERE customer = ? AND COALESCE(disabled, 0) = 0 '
94
+ f'AND COALESCE({default}, 0) = 1 AND COALESCE({usable}, 0) = 1 ORDER BY name LIMIT 1', [customer])
95
+ return rows[0]["name"] if rows else None
96
+
97
+
98
+ def resolve_document_addresses(doc):
99
+ """Fill, check and snapshot a sales document's two addresses. Called
100
+ before the document validates, on every save and on submit."""
101
+ if doc.DOCTYPE not in SOURCES:
102
+ return
103
+ db = get_db()
104
+ if "billing_address" not in _columns(doc.DOCTYPE) or not _columns("Address"):
105
+ return
106
+ customer = doc.get("customer")
107
+ if not customer:
108
+ return
109
+ stored = db.get_value(doc.DOCTYPE, doc.name, [
110
+ "customer", "billing_address", "billing_address_display", "shipping_address",
111
+ "shipping_address_display"]) if getattr(doc, "_persisted", False) and doc.name else None
112
+ customer_name = db.get_value("Customer", customer, "customer_name") or customer
113
+ inherited = None
114
+ for kind, (usable, _, purpose) in KINDS.items():
115
+ link_field, text_field = f"{kind}_address", f"{kind}_address_display"
116
+ link = str(doc._data.get(link_field) or "").strip() or None
117
+ text = str(doc._data.get(text_field) or "").strip() or None
118
+ was_link = (stored or {}).get(link_field) or None
119
+ was_text = str((stored or {}).get(text_field) or "").strip() or None
120
+ if stored and stored.get("customer") != customer and link == was_link:
121
+ # Another customer now: the old customer's address does not follow.
122
+ link = text = was_link = was_text = None
123
+ if not link and not text:
124
+ if inherited is None:
125
+ inherited = _source_addresses(doc) or {}
126
+ link, text = inherited.get(link_field) or None, inherited.get(text_field) or None
127
+ if not link and not text:
128
+ link = default_address(customer, kind)
129
+ if link:
130
+ address = db.get_all("Address", filters={"name": link}, fields=["*"])
131
+ address = address[0] if address else None
132
+ if not address:
133
+ raise ValidationError(f"{doc.DOCTYPE}: {link_field} {link} does not exist")
134
+ if address.get("customer") != customer:
135
+ raise ValidationError(
136
+ f"{doc.DOCTYPE}: address {link} belongs to customer {address.get('customer')}, not {customer}")
137
+ if link != was_link:
138
+ if flt(address.get("disabled")):
139
+ raise ValidationError(f"{doc.DOCTYPE}: address {link} is disabled")
140
+ if not flt(address.get(usable)):
141
+ raise ValidationError(f"{doc.DOCTYPE}: address {link} is not marked for {purpose}")
142
+ if not text or (link != was_link and text == was_text):
143
+ # A newly picked address replaces the text of the previous one,
144
+ # unless the text was changed in the same save.
145
+ text = format_address(address, customer_name)
146
+ doc._data[link_field], doc._data[text_field] = link, text
147
+
148
+
149
+ def finish_address(name):
150
+ """After an Address was saved: its title, and one default per customer and kind."""
151
+ db = get_db()
152
+ rows = db.get_all("Address", filters={"name": name}, fields=["*"])
153
+ if not rows:
154
+ return
155
+ address = rows[0]
156
+ customer_name = db.get_value("Customer", address.get("customer"), "customer_name")
157
+ values = {"address_title": address_title(address, customer_name)}
158
+ for usable, default, _ in KINDS.values():
159
+ if flt(address.get(default)):
160
+ if not flt(address.get(usable)) or flt(address.get("disabled")):
161
+ values[default] = 0
162
+ else:
163
+ db.sql(f'UPDATE "Address" SET {default} = 0, modified = ? WHERE customer = ? AND name <> ? '
164
+ f'AND COALESCE({default}, 0) = 1', [now(), address.get("customer"), name])
165
+ db.set_value("Address", name, values)
166
+
167
+
168
+ def validate_address(merged):
169
+ """Checks on an Address before it is saved."""
170
+ if not str(merged.get("label") or "").strip():
171
+ raise ValidationError("Address: label is required (what the address is: Accounting, Central store, ...)")
172
+ if not any(str(merged.get(field) or "").strip() for field in ("address", "city", "zip_code")):
173
+ raise ValidationError("Address: give at least the street, the zip code or the town")
174
+ # Left out, an address is for both (the column defaults).
175
+ usable = [flt(1 if merged.get(field) in (None, "") else merged.get(field)) for field in ("is_billing", "is_shipping")]
176
+ if not any(usable):
177
+ raise ValidationError("Address: mark it for invoices, for deliveries or both")
178
+
179
+
180
+ def document_address_lines(doc, kind):
181
+ """The lines to print for a document's invoice ('billing') or delivery
182
+ ('shipping') address, or [] when the document has none."""
183
+ return [line for line in str(doc.get(f"{kind}_address_display") or "").splitlines() if line.strip()]
184
+
185
+
186
+ def delivery_instructions(doc):
187
+ """Instructions of the delivery address a document links, for delivery notes."""
188
+ link = doc.get("shipping_address")
189
+ if not link or not _columns("Address"):
190
+ return None
191
+ return get_db().get_value("Address", link, "instructions") or None
@@ -158,7 +158,7 @@ _CLASSES = {
158
158
  "Purchase Order": ("lambda_erp.buying.purchase_order", "PurchaseOrder"),
159
159
  "Purchase Invoice": ("lambda_erp.accounting.purchase_invoice", "PurchaseInvoice"),
160
160
  }
161
- _BUYING = ("Purchase Order", "Purchase Invoice")
161
+ _BUYING = ("Purchase Order", "Purchase Invoice", "Purchase Receipt")
162
162
 
163
163
 
164
164
  def _document_class(doctype):
@@ -52,8 +52,8 @@ APPLICABLE_FOR = ("Customer", "Customer Group", "Territory", "Supplier", "Suppli
52
52
  # schema, so relaxing that check — for a till that rings up anonymous sales —
53
53
  # would make both flags false, match no rule, and silently price at base rate
54
54
  # instead of raising. Trade side is a property of the document type; say so.
55
- SELLING_DOCTYPES = {"Quotation", "Sales Order", "Sales Invoice", "POS Invoice"}
56
- BUYING_DOCTYPES = {"Purchase Order", "Purchase Invoice"}
55
+ SELLING_DOCTYPES = {"Quotation", "Sales Order", "Sales Invoice", "POS Invoice", "Delivery Note"}
56
+ BUYING_DOCTYPES = {"Purchase Order", "Purchase Invoice", "Purchase Receipt"}
57
57
 
58
58
 
59
59
  class PricingRule(Document):
@@ -3561,6 +3561,69 @@ def _m061_record_scope(db: "Database") -> None:
3561
3561
  db.ensure_column("Report Draft", "access_stamp", "TEXT")
3562
3562
 
3563
3563
 
3564
+ def _m062_stock_document_pricing(db: "Database") -> None:
3565
+ """Delivery notes and purchase receipts price their lines like orders and
3566
+ invoices do; a purchase invoice can bill a receipt line; a stock
3567
+ reservation can name a batch and a storage location.
3568
+
3569
+ Lines that exist keep their price: they are marked so that pricing rules
3570
+ do not run on them when a draft is saved again."""
3571
+ for doc_table, item_table in (("Delivery Note", "Delivery Note Item"), ("Purchase Receipt", "Purchase Receipt Item")):
3572
+ db.ensure_column(doc_table, "pricing_date", "TEXT")
3573
+ fresh = "ignore_pricing_rule" not in db._get_table_columns(item_table)
3574
+ db.ensure_column(item_table, "pricing_rule", "TEXT")
3575
+ db.ensure_column(item_table, "ignore_pricing_rule", "INTEGER DEFAULT 0")
3576
+ db.ensure_column(item_table, "price_source", "TEXT")
3577
+ db.ensure_column(item_table, "price_reference", "TEXT")
3578
+ if fresh:
3579
+ db.sql(f'UPDATE "{item_table}" SET ignore_pricing_rule = 1')
3580
+ db.ensure_column("Purchase Receipt Item", "billed_qty", "REAL DEFAULT 0")
3581
+ db.ensure_column("Purchase Invoice Item", "purchase_receipt", "TEXT")
3582
+ db.ensure_column("Purchase Invoice Item", "pr_detail", "TEXT")
3583
+ db.ensure_column("Stock Reservation", "batch_no", "TEXT")
3584
+ db.ensure_column("Stock Reservation", "location", "TEXT")
3585
+ # A supplier's own buying price list, as a customer has a selling one.
3586
+ db.ensure_column("Supplier", "default_price_list", "TEXT")
3587
+
3588
+
3589
+ def _m063_addresses(db: "Database") -> None:
3590
+ """Several addresses per customer, and an invoice and a delivery address
3591
+ on sales documents (see docs/addresses.md). No address is created and no
3592
+ document changed: a customer's main address stays where it is and is
3593
+ still what prints when a document has no address of its own."""
3594
+ db.conn.execute(db._ddl(
3595
+ """CREATE TABLE IF NOT EXISTS "Address" (
3596
+ name TEXT PRIMARY KEY,
3597
+ customer TEXT NOT NULL,
3598
+ label TEXT,
3599
+ address_title TEXT,
3600
+ is_billing INTEGER DEFAULT 1,
3601
+ is_shipping INTEGER DEFAULT 1,
3602
+ is_default_billing INTEGER DEFAULT 0,
3603
+ is_default_shipping INTEGER DEFAULT 0,
3604
+ recipient_name TEXT,
3605
+ address TEXT,
3606
+ zip_code TEXT,
3607
+ city TEXT,
3608
+ country TEXT,
3609
+ contact_person TEXT,
3610
+ email TEXT,
3611
+ phone TEXT,
3612
+ instructions TEXT,
3613
+ disabled INTEGER DEFAULT 0,
3614
+ creation TEXT,
3615
+ modified TEXT
3616
+ )"""))
3617
+ db.conn.execute(db._ddl('CREATE INDEX IF NOT EXISTS "ix_address_customer" ON "Address" (customer)'))
3618
+ db.conn.commit()
3619
+ db._col_cache.pop("Address", None)
3620
+ db._text_col_cache.pop("Address", None)
3621
+ db.ensure_column("Customer", "invoice_email", "TEXT")
3622
+ for table in ("Quotation", "Sales Order", "Delivery Note", "Sales Invoice"):
3623
+ for column in ("billing_address", "billing_address_display", "shipping_address", "shipping_address_display"):
3624
+ db.ensure_column(table, column, "TEXT")
3625
+
3626
+
3564
3627
  def _m052_access_profiles(db: "Database") -> None:
3565
3628
  """Access profiles narrow what a user's role allows (lambda_erp.permissions).
3566
3629
  No profile is created and no user is assigned one: nothing changes for
@@ -3662,6 +3725,8 @@ Database.MIGRATIONS = [
3662
3725
  (59, "batch_change_log", _m059_batch_change_log),
3663
3726
  (60, "serial_numbers", _m060_serial_numbers),
3664
3727
  (61, "record_scope", _m061_record_scope),
3728
+ (62, "stock_document_pricing", _m062_stock_document_pricing),
3729
+ (63, "addresses", _m063_addresses),
3665
3730
  ]
3666
3731
 
3667
3732
 
@@ -346,6 +346,8 @@ class Document:
346
346
  from lambda_erp.controllers.item_prices import normalize_item_prices
347
347
  normalize_item_prices(self)
348
348
  self._normalize_timestamps(before_validate=True)
349
+ from lambda_erp.addresses import resolve_document_addresses
350
+ resolve_document_addresses(self)
349
351
  self.validate()
350
352
  normalize_item_prices(self)
351
353
  self._require_in_scope()
@@ -404,6 +406,8 @@ class Document:
404
406
  from lambda_erp.controllers.item_prices import normalize_item_prices
405
407
  normalize_item_prices(self)
406
408
  self._normalize_timestamps(before_validate=True)
409
+ from lambda_erp.addresses import resolve_document_addresses
410
+ resolve_document_addresses(self)
407
411
  self.validate()
408
412
  normalize_item_prices(self)
409
413
  self._require_in_scope()
@@ -265,6 +265,8 @@ def _core_record_scopes():
265
265
  register_record_scope(doctype, "customer", "customer")
266
266
  for doctype in ("Item Price", "Pricing Rule", "Serial No"):
267
267
  register_record_scope(doctype, "customer", "customer", optional=True)
268
+ register_record_scope("Address", "customer", "customer")
269
+ register_record_scope("Address", "warehouse", unrelated=True)
268
270
  for doctype in ("Payment Entry", "Subscription", "Reservation"):
269
271
  register_record_scope(doctype, "customer", "party", when=("party_type", "Customer"))
270
272
  register_record_scope("Journal Entry", "customer", child="accounts", child_table="Journal Entry Account",
@@ -14,7 +14,7 @@ from lambda_erp.model import Document
14
14
  from lambda_erp.utils import _dict, flt, nowdate
15
15
  from lambda_erp.database import get_db
16
16
  from lambda_erp.controllers.taxes_and_totals import calculate_taxes_and_totals
17
- from lambda_erp.controllers.defaults import set_default_currency
17
+ from lambda_erp.controllers.defaults import set_default_currency, derived_line_pricing_fields as agreed_line_price
18
18
  from lambda_erp.exceptions import ValidationError
19
19
  from lambda_erp.stock.stock_ledger import (
20
20
  make_cancel_sl_entries,
@@ -60,12 +60,13 @@ class DeliveryNote(Document):
60
60
  self.posting_date = nowdate()
61
61
 
62
62
  self._set_customer_name()
63
+ # The price list is chosen by currency, so the currency comes first.
64
+ set_default_currency(self, "Customer", "customer")
63
65
  self._set_item_defaults()
64
66
 
65
67
  if self.is_return:
66
68
  self._validate_return()
67
69
 
68
- set_default_currency(self, "Customer", "customer")
69
70
  calculate_taxes_and_totals(self)
70
71
  self._set_status()
71
72
 
@@ -75,19 +76,13 @@ class DeliveryNote(Document):
75
76
  self.customer_name = db.get_value("Customer", self.customer, "customer_name")
76
77
 
77
78
  def _set_item_defaults(self):
78
- db = get_db()
79
- for item in self.get("items"):
80
- if item.get("item_code") and not item.get("item_name"):
81
- item_data = db.get_value(
82
- "Item", item["item_code"],
83
- ["item_name", "description", "stock_uom", "standard_rate"]
84
- )
85
- if item_data:
86
- item["item_name"] = item_data.item_name
87
- item["description"] = item.get("description") or item_data.description
88
- item["uom"] = item.get("uom") or item_data.stock_uom
89
- if item.get("rate") is None and item.get("price_list_rate") is None:
90
- item["rate"] = flt(item_data.standard_rate)
79
+ # The same price resolution as orders and invoices: price list,
80
+ # customer-specific prices, then pricing rules. Lines that come from
81
+ # an order carry its price and are left alone.
82
+ from lambda_erp.controllers.item_price import set_item_defaults
83
+ from lambda_erp.controllers.pricing_rule import apply_pricing_rules
84
+ set_item_defaults(self, "Customer", "customer")
85
+ apply_pricing_rules(self)
91
86
 
92
87
  def _validate_return(self):
93
88
  from lambda_erp.workflow import validate_return
@@ -187,6 +182,8 @@ def make_delivery_note(sales_order_name):
187
182
  # is a proposal on a draft; nothing is reserved or moved by it.
188
183
  for pick in _proposed_picks(so, item, undelivered):
189
184
  dn.append("items", _dict(
185
+ # The price was agreed in the source document: pricing rules do not run again.
186
+ **agreed_line_price(item),
190
187
  item_code=item.get("item_code"),
191
188
  item_name=item.get("item_name"),
192
189
  description=item.get("description"),
@@ -234,6 +231,8 @@ def make_delivery_return(dn_name):
234
231
  from lambda_erp.workflow import returnable_rows
235
232
  for item in returnable_rows(original):
236
233
  return_dn.append("items", _dict(
234
+ # The price was agreed in the source document: pricing rules do not run again.
235
+ **agreed_line_price(item),
237
236
  item_code=item.get("item_code"),
238
237
  item_name=item.get("item_name"),
239
238
  description=item.get("description"),