lambda-erp 1.4.31__tar.gz → 1.4.33__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 (146) hide show
  1. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/PKG-INFO +1 -1
  2. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/chat.py +8 -3
  3. lambda_erp-1.4.33/api/mail.py +405 -0
  4. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/main.py +2 -0
  5. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/order_actions.py +40 -0
  6. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/pdf.py +3 -0
  7. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/pdf_templates.py +2 -0
  8. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/masters.py +5 -0
  9. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/reports.py +6 -3
  10. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/templates/delivery_note.html +1 -0
  11. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/templates/document.html +1 -0
  12. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/sales_invoice.py +3 -1
  13. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/addresses.py +79 -0
  14. lambda_erp-1.4.33/lambda_erp/customer_terms.py +107 -0
  15. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/database.py +52 -0
  16. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/stock/delivery_note.py +12 -3
  17. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/pyproject.toml +1 -1
  18. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/.gitignore +0 -0
  19. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/LICENSE +0 -0
  20. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/README.md +0 -0
  21. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/__init__.py +0 -0
  22. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/attachments.py +0 -0
  23. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/auth.py +0 -0
  24. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/bootstrap.py +0 -0
  25. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/chat_links.py +0 -0
  26. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/demo_limits.py +0 -0
  27. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/deps.py +0 -0
  28. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/erp_context.py +0 -0
  29. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/errors.py +0 -0
  30. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/list_columns.py +0 -0
  31. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/list_values.py +0 -0
  32. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/llm_provider.py +0 -0
  33. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/mcp_oauth.py +0 -0
  34. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/mentions.py +0 -0
  35. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/menu_layout.py +0 -0
  36. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/number_series.py +0 -0
  37. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/oauth.py +0 -0
  38. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/pdf_contract.py +0 -0
  39. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/pdf_exports.py +0 -0
  40. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/pdf_fonts.py +0 -0
  41. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/pdf_pages.py +0 -0
  42. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/pdf_profiles.py +0 -0
  43. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/pricing_actions.py +0 -0
  44. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/providers.py +0 -0
  45. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/record_attachments.py +0 -0
  46. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/record_notes.py +0 -0
  47. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/remarks_md.py +0 -0
  48. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/__init__.py +0 -0
  49. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/accounting.py +0 -0
  50. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/actions.py +0 -0
  51. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/admin.py +0 -0
  52. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/analytics.py +0 -0
  53. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/availability.py +0 -0
  54. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/bank_reconciliation.py +0 -0
  55. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/bank_statements.py +0 -0
  56. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/chat_api.py +0 -0
  57. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/documents.py +0 -0
  58. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/mcp.py +0 -0
  59. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/pdf_templates.py +0 -0
  60. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/proposals.py +0 -0
  61. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/routers/setup.py +0 -0
  62. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/services.py +0 -0
  63. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/stock_actions.py +0 -0
  64. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/templates/_proposal_totals.html +0 -0
  65. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/templates/_record_base.html +0 -0
  66. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/templates/proposal.html +0 -0
  67. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/templates/record.html +0 -0
  68. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/templates/reservation.html +0 -0
  69. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/time_filters.py +0 -0
  70. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/tool_permissions.py +0 -0
  71. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/tool_results.py +0 -0
  72. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/api/write_context.py +0 -0
  73. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/docs/agents/README.md +0 -0
  74. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/frontend/LICENSE +0 -0
  75. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/frontend/README.md +0 -0
  76. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/frontend/src/api/client.ts +0 -0
  77. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/__init__.py +0 -0
  78. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/__init__.py +0 -0
  79. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/bank_account.py +0 -0
  80. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  81. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/bank_statement_import.py +0 -0
  82. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/bank_transaction.py +0 -0
  83. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/budget.py +0 -0
  84. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/camt.py +0 -0
  85. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  86. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/general_ledger.py +0 -0
  87. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/journal_entry.py +0 -0
  88. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/payment_entry.py +0 -0
  89. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/pos_invoice.py +0 -0
  90. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/purchase_invoice.py +0 -0
  91. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/revaluation.py +0 -0
  92. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/settlement.py +0 -0
  93. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/__init__.py +0 -0
  94. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/engine.py +0 -0
  95. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/pack.py +0 -0
  96. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  97. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  98. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  99. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  100. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  101. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  102. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/profiles.py +0 -0
  103. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/setup/spine.py +0 -0
  104. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/accounting/subscription.py +0 -0
  105. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/assets/__init__.py +0 -0
  106. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/assets/asset.py +0 -0
  107. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/assets/lifecycle.py +0 -0
  108. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/assets/reservation.py +0 -0
  109. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/backlog.py +0 -0
  110. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/bundles.py +0 -0
  111. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/buying/__init__.py +0 -0
  112. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/buying/purchase_order.py +0 -0
  113. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/controllers/__init__.py +0 -0
  114. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/controllers/currency.py +0 -0
  115. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/controllers/defaults.py +0 -0
  116. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/controllers/item_price.py +0 -0
  117. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/controllers/item_prices.py +0 -0
  118. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/controllers/price_resolution.py +0 -0
  119. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/controllers/pricing_rule.py +0 -0
  120. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/controllers/tax_defaults.py +0 -0
  121. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  122. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/exceptions.py +0 -0
  123. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/hooks.py +0 -0
  124. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/master_integrity.py +0 -0
  125. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/model.py +0 -0
  126. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/order_closing.py +0 -0
  127. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/permissions.py +0 -0
  128. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/selling/__init__.py +0 -0
  129. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/selling/proposal.py +0 -0
  130. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/selling/quotation.py +0 -0
  131. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/selling/sales_order.py +0 -0
  132. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/simulation.py +0 -0
  133. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/stock/__init__.py +0 -0
  134. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/stock/consignment.py +0 -0
  135. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/stock/purchase_receipt.py +0 -0
  136. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/stock/reservation.py +0 -0
  137. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/stock/serial.py +0 -0
  138. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/stock/stock_count.py +0 -0
  139. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/stock/stock_entry.py +0 -0
  140. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/stock/stock_ledger.py +0 -0
  141. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/timestamps.py +0 -0
  142. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/units.py +0 -0
  143. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/utils.py +0 -0
  144. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/validation.py +0 -0
  145. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/lambda_erp/workflow.py +0 -0
  146. {lambda_erp-1.4.31 → lambda_erp-1.4.33}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.31
3
+ Version: 1.4.33
4
4
  Summary: Core ERP logic - accounting, sales, purchasing, inventory
5
5
  Author: TORUS INVESTMENTS AG
6
6
  License-Expression: Apache-2.0
@@ -1954,7 +1954,10 @@ def _compact_master_columns(db, doctype):
1954
1954
  """What identifies a master record in a list: its id, the columns a
1955
1955
  free-text search looks at, and a few that tell records apart."""
1956
1956
  columns = db._get_table_columns(doctype)
1957
- wanted = ["name", *_master_search_columns(db, doctype),
1957
+ # The record's own name first, so further text columns never push it out.
1958
+ titles = [column for column in columns if column.endswith("_name") and column != "name"]
1959
+ wanted = ["name", *sorted(titles, key=lambda c: c != f"{doctype.lower().replace(' ', '_')}_name"),
1960
+ *_master_search_columns(db, doctype),
1958
1961
  "root_type", "account_type", "is_group", "parent_account", "company",
1959
1962
  "item_group", "stock_uom", "city", "zip_code", "country", "customer", "disabled"]
1960
1963
  return [column for column in dict.fromkeys(wanted) if column in columns][:9]
@@ -2273,7 +2276,7 @@ def _run_report(args):
2273
2276
  elif report_type == "unbilled-deliveries":
2274
2277
  from api.routers.reports import _unbilled_deliveries
2275
2278
  return _unbilled_deliveries(db, filters.get("customer"), filters.get("company"), filters.get("from_date"),
2276
- filters.get("to_date"), filters.get("delivery_note"))
2279
+ filters.get("to_date"), filters.get("delivery_note"), filters.get("billing_cycle"))
2277
2280
  elif report_type == "stock-availability":
2278
2281
  from api.routers.reports import _stock_availability
2279
2282
  return _stock_availability(db, filters.get("item_code"), filters.get("warehouse"), filters.get("item_prefix"))
@@ -3291,6 +3294,8 @@ For a complete sales return (financial + stock): create and submit both a Credit
3291
3294
  - 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.
3292
3295
  - 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.
3293
3296
  - **Closing the rest of a line** (the customer no longer wants what is still open, a supplier will never deliver the rest): use the `close_order_lines` action on the submitted order with the lines and a reason. Do not cancel or amend the order, and do not create a return for goods that were never delivered. Deliveries and invoices already posted stay. Delivered or invoiced quantities cannot be closed (a credit note corrects those). `reopen_order_lines` undoes it.
3297
+ - **Addresses**: a customer can have several saved addresses (central store, radiology, accounting) and earlier one-off addresses typed on single orders. When the user asks which addresses a customer has or has used, or an order names a delivery point that is not the default, call `list_customer_addresses` and offer the matching ones. On a draft, a saved address is set by its id (shipping_address / billing_address); an earlier or new one-off address goes into shipping_address_display / billing_address_display with the link left empty. Department and delivery / STOP codes belong in the address text so they print on the delivery note. The customer's notes for delivery notes and invoices (delivery_note_text / invoice_note_text on the customer) are copied into a new document's customer_note and printed; change customer_note on the draft for a one-time difference.
3298
+ - **Customer billing terms** (on the customer master): customer_type (Company / Individual), billing_cycle (Per Delivery / Monthly; a Monthly customer's deliveries are not invoiced one by one but with the collective invoice at month end), payment_terms_days (the invoice due date; default 30) and credit_limit. Going over the credit limit is a WARNING on the order or invoice (credit_limit_exceeded), never a reason to refuse or hold back an order: say it, then carry on.
3294
3299
  - **Monthly / collective invoice** (several deliveries to one customer billed together): check the unbilled-deliveries report for the customer and period, then use `prepare_collective_invoice` (customer + from_date/to_date, or delivery_notes, or the delivery note lines). It drafts ONE Sales Invoice whose lines keep their delivery note and order line; already billed lines are never taken again. Show the draft before submitting.
3295
3300
  - 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.
3296
3301
  - 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.
@@ -3418,7 +3423,7 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
3418
3423
  - **ap-aging** — Outstanding payables bucketed by overdue days. Filters: company, as_of_date.
3419
3424
  - **stock-balance** — Inventory quantities and valuations. Filters: item_code, warehouse.
3420
3425
  - **sales-backlog** — Open sales order lines (ordered − closed > delivered): ordered_qty, delivered_qty (net of returns), returned_qty, billed_qty, closed_qty, open_qty, reserved_qty, deliverable_qty (what can be delivered NOW; stock is shared out in due-date order, so it is never promised twice), short_qty, on_purchase_order_qty, next_expected_date and the purchase orders behind it. Filters: customer, item_code, item_prefix, warehouse, sales_order, only_deliverable. Use only_deliverable=true after a goods receipt to see which open orders can now go out. Read-only: it books nothing.
3421
- - **unbilled-deliveries** — Delivered and not yet invoiced, per delivery note line (oldest first): delivery_note, posting_date, customer, item_code, qty, billed_qty, unbilled_qty, rate, unbilled_amount, sales_order. Filters: customer, company, from_date, to_date, delivery_note. What prepare_collective_invoice would bill.
3426
+ - **unbilled-deliveries** — Delivered and not yet invoiced, per delivery note line (oldest first): delivery_note, posting_date, customer, item_code, qty, billed_qty, unbilled_qty, rate, unbilled_amount, sales_order. Filters: customer, company, from_date, to_date, delivery_note. billing_cycle per row (the customer's: Per Delivery or Monthly); filter billing_cycle=Monthly for the month-end run. What prepare_collective_invoice would bill.
3422
3427
  - **purchase-backlog** — Open purchase order lines with expected_date (the supplier's confirmed date, else the order's schedule date), confirmed, overdue and days_overdue. Filters: supplier, item_code, warehouse, overdue_only. Use overdue_only=true for "what should have arrived".
3423
3428
  - **stock-availability** — Per item × warehouse: physical_qty (in stock), blocked_qty (expired or blocked batches), reserved_qty (open Stock Reservations), available_qty (= physical − blocked − reserved), plus open_sales_order_qty (ordered by customers, not yet delivered) and on_purchase_order_qty (ordered from suppliers, not yet received). Filters: item_code, warehouse, item_prefix. Use this to answer "can we deliver X" and "is it already on order".
3424
3429
  - **stock-detail** — Where stock is, in one view: item, warehouse, consignment_customer (who it lies with, for consignment warehouses), storage location, batch, expiry date, quantity. Filters: item_code, warehouse, location, batch_no, item_prefix, item_group, expiring_before, expiring_after, include_empty, consignment_customer (one customer's consignment stock), consignment (true = only consignment, false = only own warehouses). Use this for "what is in location B4", "where is item X", "what expires in the next 3 months in warehouse Y".
@@ -0,0 +1,405 @@
1
+ """Mail from the ERP through the customer's own Microsoft 365 (Microsoft Graph).
2
+
3
+ The ERP sends as a mailbox of the customer's tenant (for example a shared
4
+ `innendienst@...` mailbox): the mail comes from their domain and lands in
5
+ that mailbox's Sent Items, so replies reach the people who work there.
6
+
7
+ Where things are set:
8
+
9
+ - Deployment (secrets, never in the UI): MAIL_GRAPH_TENANT_ID is the
10
+ customer's tenant. The app is MAIL_GRAPH_CLIENT_ID / MAIL_GRAPH_CLIENT_SECRET,
11
+ by default the same Entra app as Microsoft sign-in
12
+ (MICROSOFT_OAUTH_CLIENT_ID / MICROSOFT_OAUTH_CLIENT_SECRET). It needs the
13
+ application permission Mail.Send, consented by the tenant's admin; limit it
14
+ to the sending mailbox(es) with Exchange's application access policy.
15
+ - MAIL_ALLOWED_RECIPIENTS (deployment, optional): comma-separated addresses
16
+ and @domains. When set, mail goes only to those; everything else is
17
+ refused. Development environments set it so real customers are never
18
+ mailed.
19
+ - Settings → E-Mail (admins): on/off, the default sending mailbox and further
20
+ mailboxes a message may name as its sender.
21
+
22
+ send_mail() is the Python API for deployments and plugins. Every message is
23
+ logged ("Mail Log"). With an idempotency key, sending the same message again
24
+ returns the first result instead of mailing twice; a send whose outcome is
25
+ unknown (the connection broke after Graph got it) is not repeated
26
+ automatically. See docs/mail.md.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import base64
31
+ import hashlib
32
+ import json
33
+ import os
34
+ import re
35
+ import threading
36
+ import time
37
+ import uuid
38
+
39
+ import httpx
40
+ from fastapi import APIRouter, Depends, HTTPException
41
+ from pydantic import BaseModel, ConfigDict, Field
42
+
43
+ from api.auth import require_role
44
+ from lambda_erp.database import get_db
45
+ from lambda_erp.utils import now
46
+
47
+ router = APIRouter(prefix="/mail", tags=["mail"])
48
+
49
+ GRAPH = "https://graph.microsoft.com/v1.0"
50
+ LOGIN = "https://login.microsoftonline.com"
51
+ # Graph takes attachments inline up to a 4 MB request; base64 adds a third.
52
+ MAX_ATTACHMENT_BYTES = 3 * 1024 * 1024
53
+ MAX_RECIPIENTS = 50
54
+ ADDRESS = re.compile(r"^[^@\s<>,;\"']+@[^@\s<>,;\"']+\.[^@\s<>,;\"']+$")
55
+
56
+ SETTING_ENABLED = "mail.enabled"
57
+ SETTING_SENDER = "mail.sender"
58
+ SETTING_SENDERS = "mail.senders"
59
+
60
+ SENDING, SENT, FAILED, UNKNOWN = "Sending", "Sent", "Failed", "Unknown"
61
+
62
+ _token_lock = threading.Lock()
63
+ _token_cache: dict[tuple, tuple[str, float]] = {}
64
+
65
+
66
+ class MailError(Exception):
67
+ """A message was refused or could not be sent. `retry` says whether
68
+ trying again later may help (throttling, a service outage)."""
69
+
70
+ def __init__(self, message: str, *, retry: bool = False, log: str | None = None):
71
+ super().__init__(message)
72
+ self.retry = retry
73
+ self.log = log
74
+
75
+
76
+ # -- configuration ------------------------------------------------------------
77
+
78
+ def _env(name: str) -> str:
79
+ return (os.environ.get(name) or "").strip()
80
+
81
+
82
+ def _credentials() -> tuple[str, str, str]:
83
+ tenant = _env("MAIL_GRAPH_TENANT_ID")
84
+ client = _env("MAIL_GRAPH_CLIENT_ID") or _env("MICROSOFT_OAUTH_CLIENT_ID")
85
+ secret = _env("MAIL_GRAPH_CLIENT_SECRET") or _env("MICROSOFT_OAUTH_CLIENT_SECRET")
86
+ return tenant, client, secret
87
+
88
+
89
+ def allowed_recipients() -> list[str]:
90
+ return [part.strip().lower() for part in _env("MAIL_ALLOWED_RECIPIENTS").split(",") if part.strip()]
91
+
92
+
93
+ def _recipient_allowed(address: str, allowed: list[str]) -> bool:
94
+ if not allowed:
95
+ return True
96
+ address = address.lower()
97
+ domain = "@" + address.rsplit("@", 1)[-1]
98
+ return address in allowed or domain in allowed
99
+
100
+
101
+ def _get_setting(key: str) -> str:
102
+ rows = get_db().sql('SELECT value FROM "Settings" WHERE key = ?', [key])
103
+ return (rows[0]["value"] or "") if rows else ""
104
+
105
+
106
+ def _set_setting(key: str, value: str) -> None:
107
+ db = get_db()
108
+ with db.atomic():
109
+ if db.sql('SELECT key FROM "Settings" WHERE key = ?', [key]):
110
+ db.sql('UPDATE "Settings" SET value = ? WHERE key = ?', [value, key])
111
+ else:
112
+ db.sql('INSERT INTO "Settings" (key, value) VALUES (?, ?)', [key, value])
113
+
114
+
115
+ def settings() -> dict:
116
+ try:
117
+ senders = json.loads(_get_setting(SETTING_SENDERS) or "[]")
118
+ except ValueError:
119
+ senders = []
120
+ return {"enabled": _get_setting(SETTING_ENABLED) == "1",
121
+ "sender": _get_setting(SETTING_SENDER) or None,
122
+ "senders": [str(s) for s in senders if s]}
123
+
124
+
125
+ def status() -> dict:
126
+ """What an admin sees: whether the deployment is configured (never the
127
+ secrets themselves), the settings, and the recipient allowlist."""
128
+ tenant, client, secret = _credentials()
129
+ current = settings()
130
+ configured = bool(tenant and client and secret)
131
+ return {**current, "tenant_configured": bool(tenant), "client_configured": bool(client),
132
+ "secret_configured": bool(secret), "configured": configured,
133
+ "ready": configured and current["enabled"] and bool(current["sender"]),
134
+ "allowed_recipients": allowed_recipients()}
135
+
136
+
137
+ def _clean_address(value: str, label: str) -> str:
138
+ address = str(value or "").strip()
139
+ if not ADDRESS.match(address) or len(address) > 254:
140
+ raise MailError(f"{label}: {address!r} is not an email address")
141
+ return address
142
+
143
+
144
+ def update_settings(*, enabled: bool | None = None, sender: str | None = None,
145
+ senders: list[str] | None = None) -> dict:
146
+ if sender is not None:
147
+ _set_setting(SETTING_SENDER, _clean_address(sender, "Sending mailbox") if sender.strip() else "")
148
+ if senders is not None:
149
+ cleaned = sorted({_clean_address(s, "Further mailbox").lower() for s in senders if str(s).strip()})
150
+ _set_setting(SETTING_SENDERS, json.dumps(cleaned))
151
+ if enabled is not None:
152
+ if enabled and not settings()["sender"]:
153
+ raise MailError("Set the sending mailbox before switching mail on")
154
+ _set_setting(SETTING_ENABLED, "1" if enabled else "0")
155
+ return status()
156
+
157
+
158
+ # -- Microsoft Graph ----------------------------------------------------------
159
+
160
+ def _token() -> str:
161
+ tenant, client, secret = _credentials()
162
+ if not (tenant and client and secret):
163
+ raise MailError("Mail is not configured for this deployment (MAIL_GRAPH_TENANT_ID and the app credentials)")
164
+ key = (tenant, client)
165
+ with _token_lock:
166
+ cached = _token_cache.get(key)
167
+ if cached and cached[1] > time.time() + 60:
168
+ return cached[0]
169
+ try:
170
+ response = httpx.post(f"{LOGIN}/{tenant}/oauth2/v2.0/token", timeout=15, data={
171
+ "client_id": client, "client_secret": secret, "grant_type": "client_credentials",
172
+ "scope": "https://graph.microsoft.com/.default"})
173
+ except httpx.HTTPError as exc:
174
+ raise MailError(f"Microsoft sign-in for mail could not be reached: {exc.__class__.__name__}", retry=True)
175
+ if response.status_code != 200:
176
+ detail = _graph_error(response)
177
+ raise MailError(f"Microsoft refused the mail app's sign-in ({response.status_code}): {detail}",
178
+ retry=response.status_code >= 500)
179
+ body = response.json()
180
+ _token_cache[key] = (body["access_token"], time.time() + float(body.get("expires_in") or 3000))
181
+ return body["access_token"]
182
+
183
+
184
+ def _graph_error(response) -> str:
185
+ try:
186
+ body = response.json()
187
+ except ValueError:
188
+ return response.text[:300]
189
+ error = body.get("error")
190
+ if isinstance(error, dict):
191
+ return f"{error.get('code')}: {error.get('message')}"[:300]
192
+ return str(body.get("error_description") or error or body)[:300]
193
+
194
+
195
+ def _post_send_mail(sender: str, message: dict) -> None:
196
+ """One sendMail call. Raises MailError; `UNKNOWN` outcomes raise with
197
+ log=UNKNOWN so the caller records that Graph may have accepted it."""
198
+ token = _token()
199
+ try:
200
+ response = httpx.post(f"{GRAPH}/users/{sender}/sendMail", timeout=30,
201
+ headers={"Authorization": f"Bearer {token}"},
202
+ json={"message": message, "saveToSentItems": True})
203
+ except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
204
+ raise MailError(f"Microsoft Graph could not be reached: {exc.__class__.__name__}", retry=True)
205
+ except httpx.HTTPError as exc:
206
+ # The request may have arrived: do not send it again automatically.
207
+ raise MailError(f"Connection to Microsoft Graph broke off ({exc.__class__.__name__}); "
208
+ "check the mailbox's Sent Items before sending again", log=UNKNOWN)
209
+ if response.status_code == 202:
210
+ return
211
+ if response.status_code == 401:
212
+ with _token_lock:
213
+ _token_cache.clear()
214
+ detail = _graph_error(response)
215
+ hint = ""
216
+ if response.status_code == 403:
217
+ hint = " (the app may not send from this mailbox: check Mail.Send consent and the application access policy)"
218
+ elif response.status_code == 404:
219
+ hint = " (no such mailbox in the tenant)"
220
+ raise MailError(f"Microsoft Graph refused the message ({response.status_code}): {detail}{hint}",
221
+ retry=response.status_code in (429, 500, 502, 503, 504))
222
+
223
+
224
+ # -- sending ------------------------------------------------------------------
225
+
226
+ def _recipients(values, label: str) -> list[str]:
227
+ if isinstance(values, str):
228
+ values = [values]
229
+ seen, out = set(), []
230
+ for value in values or []:
231
+ address = _clean_address(value, label)
232
+ if address.lower() not in seen:
233
+ seen.add(address.lower())
234
+ out.append(address)
235
+ return out
236
+
237
+
238
+ def send_mail(to, subject: str, body: str, *, html: bool = False, cc=None, reply_to=None,
239
+ attachments: list[tuple[str, bytes, str]] | None = None, sender: str | None = None,
240
+ idempotency_key: str | None = None, reference: tuple[str, str] | None = None,
241
+ actor: str | None = None) -> dict:
242
+ """Send one message through Microsoft 365 and log it.
243
+
244
+ to / cc / reply_to: addresses (a string or a list). attachments:
245
+ (filename, bytes, content type). sender: the default mailbox, or one of the
246
+ further mailboxes in the settings. idempotency_key: the same key with the
247
+ same content returns the first result (replayed=True); with different
248
+ content it is refused. reference: (doctype, name) the message belongs to.
249
+
250
+ Returns {"name", "status", "replayed"}. Raises MailError when the message
251
+ is refused or not sent; a failed send may be tried again with the same key.
252
+ """
253
+ config = settings()
254
+ if not config["enabled"]:
255
+ raise MailError("Mail is switched off (Settings → E-Mail)")
256
+ sender = (sender or config["sender"] or "").strip()
257
+ if not sender:
258
+ raise MailError("No sending mailbox is set (Settings → E-Mail)")
259
+ permitted = {s.lower() for s in [config["sender"] or "", *config["senders"]] if s}
260
+ if sender.lower() not in permitted:
261
+ raise MailError(f"{sender} is not one of the sending mailboxes in Settings → E-Mail")
262
+ to_list, cc_list = _recipients(to, "To"), _recipients(cc, "Cc")
263
+ reply_list = _recipients(reply_to, "Reply-To")
264
+ if not to_list:
265
+ raise MailError("A message needs at least one recipient")
266
+ if len(to_list) + len(cc_list) > MAX_RECIPIENTS:
267
+ raise MailError(f"At most {MAX_RECIPIENTS} recipients per message")
268
+ allowed = allowed_recipients()
269
+ blocked = [a for a in to_list + cc_list if not _recipient_allowed(a, allowed)]
270
+ if blocked:
271
+ raise MailError(f"This environment only mails {', '.join(allowed)}; refused: {', '.join(blocked)}")
272
+ subject = str(subject or "").strip()
273
+ if not subject or len(subject) > 255:
274
+ raise MailError("A subject of 1 to 255 characters is required")
275
+ files = []
276
+ total = 0
277
+ for filename, data, content_type in attachments or []:
278
+ name = str(filename or "").strip()
279
+ if not name or "/" in name or "\\" in name:
280
+ raise MailError(f"Attachment name {filename!r} is not valid")
281
+ total += len(data)
282
+ files.append({"@odata.type": "#microsoft.graph.fileAttachment", "name": name,
283
+ "contentType": content_type or "application/octet-stream",
284
+ "contentBytes": base64.b64encode(data).decode("ascii")})
285
+ if total > MAX_ATTACHMENT_BYTES:
286
+ raise MailError(f"Attachments are {total / 1048576:.1f} MB; at most {MAX_ATTACHMENT_BYTES // 1048576} MB per message")
287
+
288
+ digest = hashlib.sha256(json.dumps({
289
+ "sender": sender.lower(), "to": to_list, "cc": cc_list, "reply_to": reply_list, "subject": subject,
290
+ "body": body, "html": bool(html),
291
+ "attachments": [[f["name"], hashlib.sha256(base64.b64decode(f["contentBytes"])).hexdigest()] for f in files],
292
+ }, sort_keys=True).encode()).hexdigest()
293
+
294
+ db = get_db()
295
+ stamp = now()
296
+ with db.atomic():
297
+ if idempotency_key:
298
+ if db.dialect == "postgres":
299
+ db.sql("SELECT pg_advisory_xact_lock(hashtext(?))", ["mail:" + idempotency_key])
300
+ earlier = db.sql('SELECT name, digest, status FROM "Mail Log" WHERE idempotency_key = ?', [idempotency_key])
301
+ if earlier:
302
+ row = earlier[0]
303
+ if row["digest"] != digest:
304
+ raise MailError(f"Idempotency key {idempotency_key!r} was used for a different message")
305
+ if row["status"] == SENT:
306
+ return {"name": row["name"], "status": SENT, "replayed": True}
307
+ if row["status"] in (SENDING, UNKNOWN):
308
+ raise MailError("This message may already have been sent (outcome unknown); check the "
309
+ "mailbox's Sent Items before sending it again", log=row["name"])
310
+ # Failed before: try again under the same log row.
311
+ db.sql('UPDATE "Mail Log" SET status = ?, error = NULL, modified = ? WHERE name = ?',
312
+ [SENDING, stamp, row["name"]])
313
+ log = row["name"]
314
+ else:
315
+ log = None
316
+ else:
317
+ log = None
318
+ if not log:
319
+ log = "MAIL-" + uuid.uuid4().hex[:12]
320
+ db.insert("Mail Log", {
321
+ "name": log, "creation": stamp, "modified": stamp, "idempotency_key": idempotency_key,
322
+ "digest": digest, "sender": sender, "recipients": json.dumps({"to": to_list, "cc": cc_list}),
323
+ "subject": subject, "status": SENDING,
324
+ "reference_doctype": reference[0] if reference else None,
325
+ "reference_name": reference[1] if reference else None, "actor": actor})
326
+
327
+ message = {"subject": subject, "body": {"contentType": "HTML" if html else "Text", "content": body or ""},
328
+ "toRecipients": [{"emailAddress": {"address": a}} for a in to_list]}
329
+ if cc_list:
330
+ message["ccRecipients"] = [{"emailAddress": {"address": a}} for a in cc_list]
331
+ if reply_list:
332
+ message["replyTo"] = [{"emailAddress": {"address": a}} for a in reply_list]
333
+ if files:
334
+ message["attachments"] = files
335
+ try:
336
+ _post_send_mail(sender, message)
337
+ except MailError as exc:
338
+ outcome = UNKNOWN if exc.log == UNKNOWN else FAILED
339
+ with db.atomic():
340
+ db.sql('UPDATE "Mail Log" SET status = ?, error = ?, modified = ? WHERE name = ?',
341
+ [outcome, str(exc)[:1000], now(), log])
342
+ exc.log = log
343
+ raise
344
+ with db.atomic():
345
+ db.sql('UPDATE "Mail Log" SET status = ?, error = NULL, modified = ? WHERE name = ?', [SENT, now(), log])
346
+ return {"name": log, "status": SENT, "replayed": False}
347
+
348
+
349
+ def mail_log(limit: int = 50, reference: tuple[str, str] | None = None) -> list[dict]:
350
+ db = get_db()
351
+ where, params = "", []
352
+ if reference:
353
+ where, params = "WHERE reference_doctype = ? AND reference_name = ?", list(reference)
354
+ rows = db.sql(f'SELECT name, creation, modified, sender, recipients, subject, status, error, '
355
+ f'reference_doctype, reference_name, actor FROM "Mail Log" {where} '
356
+ f'ORDER BY creation DESC LIMIT {max(1, min(int(limit), 500))}', params)
357
+ return [{**dict(row), "recipients": json.loads(row["recipients"] or "{}")} for row in rows]
358
+
359
+
360
+ # -- admin endpoints ----------------------------------------------------------
361
+
362
+ _admin = Depends(require_role("admin"))
363
+
364
+
365
+ class MailSettingsInput(BaseModel):
366
+ model_config = ConfigDict(extra="forbid")
367
+ enabled: bool | None = None
368
+ sender: str | None = Field(default=None, max_length=254)
369
+ senders: list[str] | None = Field(default=None, max_length=20)
370
+
371
+
372
+ class TestMailInput(BaseModel):
373
+ model_config = ConfigDict(extra="forbid")
374
+ to: str = Field(min_length=3, max_length=254)
375
+ sender: str | None = Field(default=None, max_length=254)
376
+
377
+
378
+ @router.get("/settings")
379
+ def get_mail_settings(user: dict = _admin):
380
+ return status()
381
+
382
+
383
+ @router.put("/settings")
384
+ def put_mail_settings(data: MailSettingsInput, user: dict = _admin):
385
+ try:
386
+ return update_settings(enabled=data.enabled, sender=data.sender, senders=data.senders)
387
+ except MailError as exc:
388
+ raise HTTPException(status_code=422, detail=str(exc))
389
+
390
+
391
+ @router.post("/test")
392
+ def send_test_mail(data: TestMailInput, user: dict = _admin):
393
+ try:
394
+ return send_mail(data.to, "Test mail from the ERP",
395
+ "This test message was sent by the ERP through Microsoft 365. "
396
+ "If you received it, mail from the ERP works.",
397
+ sender=data.sender, reference=("Mail Test", user.get("name") or ""),
398
+ actor=user.get("name"))
399
+ except MailError as exc:
400
+ raise HTTPException(status_code=422, detail=str(exc))
401
+
402
+
403
+ @router.get("/log")
404
+ def get_mail_log(limit: int = 50, user: dict = _admin):
405
+ return {"messages": mail_log(limit)}
@@ -181,6 +181,8 @@ app.include_router(admin.router, prefix="/api")
181
181
  app.include_router(chat_router, prefix="/api")
182
182
  app.include_router(chat_api.router, prefix="/api")
183
183
  app.include_router(mcp.router, prefix="/api")
184
+ from api.mail import router as mail_router # noqa: E402
185
+ app.include_router(mail_router, prefix="/api")
184
186
 
185
187
 
186
188
  @app.get("/api/health")
@@ -23,6 +23,18 @@ class ReopenOrderLines(mentions.Input):
23
23
  lines: list[str] | None = Field(default=None, max_length=500)
24
24
 
25
25
 
26
+ class CustomerAddresses(mentions.Input):
27
+ customer: str = Field(min_length=1, max_length=200)
28
+
29
+
30
+ def list_customer_addresses(args):
31
+ data = CustomerAddresses.model_validate(args)
32
+ permissions.require_readable("Customer", data.customer)
33
+ permissions.require("Address", "read")
34
+ from lambda_erp.addresses import customer_addresses
35
+ return customer_addresses(data.customer)
36
+
37
+
26
38
  class CollectiveInvoice(mentions.Input):
27
39
  customer: str | None = Field(default=None, max_length=200)
28
40
  company: str | None = Field(default=None, max_length=200)
@@ -69,7 +81,24 @@ def prepare_collective_invoice(args):
69
81
  return services.load_document("sales-invoice", invoice.name)
70
82
 
71
83
 
84
+ def _credit_limit_warning(doc):
85
+ """A warning, never a block: the order or invoice takes the customer over
86
+ its credit limit (lambda_erp/customer_terms.py)."""
87
+ if doc.DOCTYPE not in ("Sales Order", "Sales Invoice") or doc.docstatus == 2:
88
+ return []
89
+ from lambda_erp.customer_terms import credit_check
90
+ check = credit_check(doc)
91
+ if not check:
92
+ return []
93
+ return [{"code": "credit_limit_exceeded", **check, "message": (
94
+ f"Credit limit of {check['limit']:,.2f} exceeded: open receivables {check['open']:,.2f}"
95
+ + (f" plus this document {check['this_document']:,.2f}" if check["this_document"] else "")
96
+ + f" = {check['total']:,.2f}. This is a warning; the document can still be submitted.")}]
97
+
98
+
72
99
  def initialize_order_actions():
100
+ if _credit_limit_warning not in services.DOCUMENT_WARNING_PROVIDERS:
101
+ services.DOCUMENT_WARNING_PROVIDERS.append(_credit_limit_warning)
73
102
  services.register_action(
74
103
  "close_order_lines", close_lines,
75
104
  description=(
@@ -86,6 +115,17 @@ def initialize_order_actions():
86
115
  "Undo close_order_lines on a submitted sales or purchase order: the closed quantity of `lines` (or of "
87
116
  "every closed line) is open again. A released reservation is not restored; reserve again if needed."),
88
117
  parameters=ReopenOrderLines.model_json_schema(), minimum_role="manager")
118
+ services.register_action(
119
+ "list_customer_addresses", list_customer_addresses,
120
+ description=(
121
+ "READ-ONLY: a customer's saved addresses (with label, for invoices / deliveries, defaults, delivery "
122
+ "instructions) and the delivery and invoice addresses its documents used that are NOT on record "
123
+ "(typed for one order), newest first with times used, last used and the last document. Use it when "
124
+ "the user asks which addresses a customer has or has used, or when an order names an address that "
125
+ "differs from the default. To use a saved one, set shipping_address / billing_address (its id) on the "
126
+ "draft; to use an earlier or a new one-off address, set shipping_address_display / "
127
+ "billing_address_display to the text and leave the link empty. Never invent an address."),
128
+ parameters=CustomerAddresses.model_json_schema(), minimum_role="viewer")
89
129
  services.register_action(
90
130
  "prepare_collective_invoice", prepare_collective_invoice,
91
131
  description=(
@@ -357,6 +357,9 @@ def _render_commercial_pdf(doctype, name, doc, contract, layout=None, blocked=No
357
357
  delivery_lines=delivery_lines,
358
358
  delivery_label="Delivery address",
359
359
  delivery_instructions=delivery_instructions(doc) if file == "delivery_note.html" else None,
360
+ # The customer's note for this document type, as copied onto the document
361
+ # (lambda_erp/addresses.py apply_customer_note).
362
+ customer_note=(doc.get("customer_note") or "").strip() or None,
360
363
  currency=currency,
361
364
  meta_fields=meta_fields,
362
365
  items=items,
@@ -685,6 +685,8 @@ Variables:
685
685
  _PARTY_VARIABLES = """- company_name, company_info (email, phone, address, city, zip_code, country, tax_id, iban)
686
686
  - party_label ("Customer"/"Supplier"), party_name, party_info (email, phone, address, city, zip_code, country, tax_id)
687
687
  - title: the document title; pdf_state_notice: "Draft"/"Cancelled" text or empty; pdf_status; page_size ("A4"/"Letter")
688
+ - address_lines (the address the document goes to, first line the recipient), delivery_lines / delivery_label (a differing delivery address), delivery_instructions (delivery notes)
689
+ - customer_note (delivery notes and invoices, may be empty): the customer's note for this document, e.g. "Rechnung per E-Mail an …"; print it close to the address when set
688
690
  """
689
691
 
690
692
  _TEXT_VARIABLES = """- intro_html: the intro text as safe HTML ({{ intro_html|safe }}); print it near the top, usually under the title
@@ -308,6 +308,11 @@ def _validate_master_input(master_type, doctype, data, name=None):
308
308
  _validate_batch(db, merged, name)
309
309
  if master_type == 'serial-no':
310
310
  _validate_serial(db, data, name)
311
+ if master_type == 'customer':
312
+ from lambda_erp.customer_terms import validate_customer_terms
313
+ validate_customer_terms(merged)
314
+ if 'payment_terms_days' in data and merged.get('payment_terms_days') not in (None, ''):
315
+ data['payment_terms_days'] = merged['payment_terms_days']
311
316
  if master_type == 'address':
312
317
  from lambda_erp.addresses import validate_address
313
318
  validate_address(merged)
@@ -544,14 +544,16 @@ def purchase_backlog_report(
544
544
  return _purchase_backlog(get_db(), supplier, item_code, warehouse, overdue_only)
545
545
 
546
546
 
547
- def _unbilled_deliveries(db, customer=None, company=None, from_date=None, to_date=None, delivery_note=None):
547
+ def _unbilled_deliveries(db, customer=None, company=None, from_date=None, to_date=None, delivery_note=None,
548
+ billing_cycle=None):
548
549
  """Delivered and not yet invoiced, per delivery note line: what a
549
550
  collective (monthly) invoice would bill. Selling prices only."""
550
551
  permissions.require_artifact("report", "unbilled-deliveries")
551
552
  permissions.require("Delivery Note", "read")
552
553
  from lambda_erp.stock.delivery_note import unbilled_delivery_lines
553
554
  rows = unbilled_delivery_lines(customer, company=company, from_date=from_date, to_date=to_date,
554
- delivery_notes=[delivery_note] if delivery_note else None)
555
+ delivery_notes=[delivery_note] if delivery_note else None,
556
+ billing_cycle=billing_cycle)
555
557
  return {"rows": permissions.scope_rows("report", "unbilled-deliveries", rows)}
556
558
 
557
559
 
@@ -562,8 +564,9 @@ def unbilled_deliveries_report(
562
564
  from_date: str | None = None,
563
565
  to_date: str | None = None,
564
566
  delivery_note: str | None = None,
567
+ billing_cycle: str | None = None,
565
568
  ):
566
- return _unbilled_deliveries(get_db(), customer, company, from_date, to_date, delivery_note)
569
+ return _unbilled_deliveries(get_db(), customer, company, from_date, to_date, delivery_note, billing_cycle)
567
570
 
568
571
 
569
572
  @router.get("/stock-detail")
@@ -120,6 +120,7 @@
120
120
  {% if delivery_instructions %}<div class="detail" style="margin-top: 4px;">{{ delivery_instructions }}</div>{% endif %}
121
121
  </div>
122
122
  </div>
123
+ {% if customer_note %}<div class="customer-note" style="margin: 0 0 12px; padding: 6px 8px; border-left: 3px solid #334b70; background: #f1f5f9; font-size: 9pt; white-space: pre-wrap;">{{ customer_note }}</div>{% endif %}
123
124
 
124
125
  {# ---- Meta fields ---- #}
125
126
  {% if meta_fields %}
@@ -116,6 +116,7 @@
116
116
  {% if delivery_instructions %}<div class="detail" style="margin-top: 4px;">{{ delivery_instructions }}</div>{% endif %}
117
117
  </div>
118
118
  </div>
119
+ {% if customer_note %}<div class="customer-note" style="margin: 0 0 12px; padding: 6px 8px; border-left: 3px solid #334b70; background: #f1f5f9; font-size: 9pt; white-space: pre-wrap;">{{ customer_note }}</div>{% endif %}
119
120
 
120
121
  {# ---- Meta fields ---- #}
121
122
  {% if meta_fields %}
@@ -114,7 +114,9 @@ class SalesInvoice(Document):
114
114
  self._data["outstanding_amount"] = flt(self.grand_total, 2)
115
115
 
116
116
  if not self.due_date:
117
- self._data["due_date"] = add_days(self.posting_date, 30)
117
+ # The customer's payment terms (customer_terms.py), else 30 days.
118
+ from lambda_erp.customer_terms import due_date
119
+ self._data["due_date"] = due_date(self.customer, self.posting_date)
118
120
 
119
121
  def _set_customer_name(self):
120
122
  if not self.customer_name and self.customer: