lambda-erp 1.4.30__tar.gz → 1.4.32__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.30 → lambda_erp-1.4.32}/PKG-INFO +4 -4
  2. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/README.md +3 -3
  3. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/chat.py +23 -12
  4. lambda_erp-1.4.32/api/mail.py +405 -0
  5. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/main.py +4 -0
  6. lambda_erp-1.4.32/api/order_actions.py +115 -0
  7. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/providers.py +4 -3
  8. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/masters.py +5 -0
  9. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/reports.py +25 -0
  10. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/frontend/src/api/client.ts +3 -0
  11. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/sales_invoice.py +3 -1
  12. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/backlog.py +18 -11
  13. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/buying/purchase_order.py +3 -1
  14. lambda_erp-1.4.32/lambda_erp/customer_terms.py +107 -0
  15. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/database.py +53 -0
  16. lambda_erp-1.4.32/lambda_erp/order_closing.py +184 -0
  17. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/permissions.py +1 -0
  18. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/selling/sales_order.py +3 -1
  19. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/stock/delivery_note.py +150 -26
  20. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/stock/purchase_receipt.py +1 -1
  21. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/stock/reservation.py +7 -4
  22. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/workflow.py +24 -10
  23. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/pyproject.toml +1 -1
  24. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/.gitignore +0 -0
  25. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/LICENSE +0 -0
  26. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/__init__.py +0 -0
  27. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/attachments.py +0 -0
  28. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/auth.py +0 -0
  29. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/bootstrap.py +0 -0
  30. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/chat_links.py +0 -0
  31. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/demo_limits.py +0 -0
  32. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/deps.py +0 -0
  33. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/erp_context.py +0 -0
  34. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/errors.py +0 -0
  35. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/list_columns.py +0 -0
  36. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/list_values.py +0 -0
  37. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/llm_provider.py +0 -0
  38. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/mcp_oauth.py +0 -0
  39. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/mentions.py +0 -0
  40. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/menu_layout.py +0 -0
  41. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/number_series.py +0 -0
  42. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/oauth.py +0 -0
  43. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/pdf.py +0 -0
  44. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/pdf_contract.py +0 -0
  45. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/pdf_exports.py +0 -0
  46. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/pdf_fonts.py +0 -0
  47. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/pdf_pages.py +0 -0
  48. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/pdf_profiles.py +0 -0
  49. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/pdf_templates.py +0 -0
  50. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/pricing_actions.py +0 -0
  51. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/record_attachments.py +0 -0
  52. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/record_notes.py +0 -0
  53. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/remarks_md.py +0 -0
  54. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/__init__.py +0 -0
  55. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/accounting.py +0 -0
  56. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/actions.py +0 -0
  57. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/admin.py +0 -0
  58. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/analytics.py +0 -0
  59. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/availability.py +0 -0
  60. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/bank_reconciliation.py +0 -0
  61. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/bank_statements.py +0 -0
  62. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/chat_api.py +0 -0
  63. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/documents.py +0 -0
  64. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/mcp.py +0 -0
  65. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/pdf_templates.py +0 -0
  66. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/proposals.py +0 -0
  67. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/routers/setup.py +0 -0
  68. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/services.py +0 -0
  69. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/stock_actions.py +0 -0
  70. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/templates/_proposal_totals.html +0 -0
  71. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/templates/_record_base.html +0 -0
  72. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/templates/delivery_note.html +0 -0
  73. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/templates/document.html +0 -0
  74. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/templates/proposal.html +0 -0
  75. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/templates/record.html +0 -0
  76. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/templates/reservation.html +0 -0
  77. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/time_filters.py +0 -0
  78. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/tool_permissions.py +0 -0
  79. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/tool_results.py +0 -0
  80. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/api/write_context.py +0 -0
  81. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/docs/agents/README.md +0 -0
  82. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/frontend/LICENSE +0 -0
  83. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/frontend/README.md +0 -0
  84. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/__init__.py +0 -0
  85. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/__init__.py +0 -0
  86. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/bank_account.py +0 -0
  87. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  88. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/bank_statement_import.py +0 -0
  89. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/bank_transaction.py +0 -0
  90. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/budget.py +0 -0
  91. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/camt.py +0 -0
  92. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  93. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/general_ledger.py +0 -0
  94. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/journal_entry.py +0 -0
  95. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/payment_entry.py +0 -0
  96. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/pos_invoice.py +0 -0
  97. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/purchase_invoice.py +0 -0
  98. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/revaluation.py +0 -0
  99. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/settlement.py +0 -0
  100. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/__init__.py +0 -0
  101. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/engine.py +0 -0
  102. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/pack.py +0 -0
  103. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  104. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  105. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  106. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  107. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  108. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  109. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/profiles.py +0 -0
  110. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/setup/spine.py +0 -0
  111. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/accounting/subscription.py +0 -0
  112. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/addresses.py +0 -0
  113. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/assets/__init__.py +0 -0
  114. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/assets/asset.py +0 -0
  115. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/assets/lifecycle.py +0 -0
  116. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/assets/reservation.py +0 -0
  117. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/bundles.py +0 -0
  118. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/buying/__init__.py +0 -0
  119. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/controllers/__init__.py +0 -0
  120. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/controllers/currency.py +0 -0
  121. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/controllers/defaults.py +0 -0
  122. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/controllers/item_price.py +0 -0
  123. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/controllers/item_prices.py +0 -0
  124. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/controllers/price_resolution.py +0 -0
  125. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/controllers/pricing_rule.py +0 -0
  126. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/controllers/tax_defaults.py +0 -0
  127. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  128. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/exceptions.py +0 -0
  129. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/hooks.py +0 -0
  130. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/master_integrity.py +0 -0
  131. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/model.py +0 -0
  132. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/selling/__init__.py +0 -0
  133. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/selling/proposal.py +0 -0
  134. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/selling/quotation.py +0 -0
  135. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/simulation.py +0 -0
  136. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/stock/__init__.py +0 -0
  137. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/stock/consignment.py +0 -0
  138. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/stock/serial.py +0 -0
  139. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/stock/stock_count.py +0 -0
  140. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/stock/stock_entry.py +0 -0
  141. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/stock/stock_ledger.py +0 -0
  142. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/timestamps.py +0 -0
  143. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/units.py +0 -0
  144. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/utils.py +0 -0
  145. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/lambda_erp/validation.py +0 -0
  146. {lambda_erp-1.4.30 → lambda_erp-1.4.32}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.30
3
+ Version: 1.4.32
4
4
  Summary: Core ERP logic - accounting, sales, purchasing, inventory
5
5
  Author: TORUS INVESTMENTS AG
6
6
  License-Expression: Apache-2.0
@@ -266,8 +266,8 @@ Open `http://localhost:5173`. Vite proxies `/api/*` to the backend.
266
266
 
267
267
  ```
268
268
  OPENAI_API_KEY=sk-...
269
- LAMBDA_ERP_CHAT_MODEL=gpt-6.2-sol # optional chat override; default shown
270
- LAMBDA_ERP_REPORT_MODEL=gpt-6.2-sol # optional specialist override; default shown
269
+ LAMBDA_ERP_CHAT_MODEL=gpt-6.1-sol # optional chat override; default shown
270
+ LAMBDA_ERP_REPORT_MODEL=gpt-6.1-sol # optional specialist override; default shown
271
271
  LAMBDA_ERP_TITLE_MODEL=gpt-6-luna # optional chat-title override; default shown
272
272
  LAMBDA_ERP_ADMIN_EMAIL=admin@example.com # optional, seeds the admin at boot
273
273
  LAMBDA_ERP_ADMIN_PASSWORD=... # optional, required with the line above
@@ -275,7 +275,7 @@ LAMBDA_ERP_ADMIN_NAME=Administrator # optional, display name for the seed
275
275
  ```
276
276
 
277
277
  Chat, chat titles and custom-report specification generation share
278
- `OPENAI_API_KEY`. The chat and the report specialist default to GPT-6.2 Sol,
278
+ `OPENAI_API_KEY`. The chat and the report specialist default to GPT-6.1 Sol,
279
279
  titles to GPT-6 Luna; see [docs/llm-pricing.md](docs/llm-pricing.md) for prices.
280
280
 
281
281
  **Seeded admin.** By default the first person to register becomes the admin. Set `LAMBDA_ERP_ADMIN_EMAIL` + `LAMBDA_ERP_ADMIN_PASSWORD` to instead provision that admin automatically at startup — useful when the database is recreated on every deploy, so a redeployed instance can't be claimed by whoever visits first. It's create-if-missing and idempotent (an existing account with that email is promoted to an enabled admin; its password is left untouched), and the password is only ever read from the environment.
@@ -235,8 +235,8 @@ Open `http://localhost:5173`. Vite proxies `/api/*` to the backend.
235
235
 
236
236
  ```
237
237
  OPENAI_API_KEY=sk-...
238
- LAMBDA_ERP_CHAT_MODEL=gpt-6.2-sol # optional chat override; default shown
239
- LAMBDA_ERP_REPORT_MODEL=gpt-6.2-sol # optional specialist override; default shown
238
+ LAMBDA_ERP_CHAT_MODEL=gpt-6.1-sol # optional chat override; default shown
239
+ LAMBDA_ERP_REPORT_MODEL=gpt-6.1-sol # optional specialist override; default shown
240
240
  LAMBDA_ERP_TITLE_MODEL=gpt-6-luna # optional chat-title override; default shown
241
241
  LAMBDA_ERP_ADMIN_EMAIL=admin@example.com # optional, seeds the admin at boot
242
242
  LAMBDA_ERP_ADMIN_PASSWORD=... # optional, required with the line above
@@ -244,7 +244,7 @@ LAMBDA_ERP_ADMIN_NAME=Administrator # optional, display name for the seed
244
244
  ```
245
245
 
246
246
  Chat, chat titles and custom-report specification generation share
247
- `OPENAI_API_KEY`. The chat and the report specialist default to GPT-6.2 Sol,
247
+ `OPENAI_API_KEY`. The chat and the report specialist default to GPT-6.1 Sol,
248
248
  titles to GPT-6 Luna; see [docs/llm-pricing.md](docs/llm-pricing.md) for prices.
249
249
 
250
250
  **Seeded admin.** By default the first person to register becomes the admin. Set `LAMBDA_ERP_ADMIN_EMAIL` + `LAMBDA_ERP_ADMIN_PASSWORD` to instead provision that admin automatically at startup — useful when the database is recreated on every deploy, so a redeployed instance can't be claimed by whoever visits first. It's create-if-missing and idempotent (an existing account with that email is promoted to an enabled admin; its password is left untouched), and the password is only ever read from the environment.
@@ -1057,7 +1057,7 @@ TOOLS = [
1057
1057
  "properties": {
1058
1058
  "limit": {"type": "integer", "description": "Maximum rows of a list report, default 200, range 1–2000. The general ledger uses filters.limit / filters.offset instead."},
1059
1059
  "offset": {"type": "integer", "description": "Skip this many rows.", "default": 0},
1060
- "report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "stock-availability", "stock-detail", "batch-stock", "batch-movements", "batch-recipients", "batch-changes", "serial-trace", "sales-backlog", "purchase-backlog", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
1060
+ "report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "stock-availability", "stock-detail", "batch-stock", "batch-movements", "batch-recipients", "batch-changes", "serial-trace", "sales-backlog", "purchase-backlog", "unbilled-deliveries", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
1061
1061
  "filters": {"type": "object", "description": "Optional filters: company, account, from_date, to_date, item_code, warehouse; for batch-stock also batch_no, item_prefix, expiring_before, include_empty; for stock-detail also location, batch_no, item_prefix, item_group, expiring_before, expiring_after, include_empty; batch-movements requires batch_no. For trial-balance / profit-and-loss / balance-sheet you may also pass `presentation_currency` (e.g. \"EUR\") to view the report translated from the company's base currency at the period's closing rate — display only, the ledger stays in base currency.", "default": {}},
1062
1062
  },
1063
1063
  "required": ["report_type"],
@@ -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]
@@ -2270,6 +2273,10 @@ def _run_report(args):
2270
2273
  from api.routers.reports import _purchase_backlog
2271
2274
  return _purchase_backlog(db, filters.get("supplier"), filters.get("item_code"), filters.get("warehouse"),
2272
2275
  bool(filters.get("overdue_only")))
2276
+ elif report_type == "unbilled-deliveries":
2277
+ from api.routers.reports import _unbilled_deliveries
2278
+ return _unbilled_deliveries(db, filters.get("customer"), filters.get("company"), filters.get("from_date"),
2279
+ filters.get("to_date"), filters.get("delivery_note"), filters.get("billing_cycle"))
2273
2280
  elif report_type == "stock-availability":
2274
2281
  from api.routers.reports import _stock_availability
2275
2282
  return _stock_availability(db, filters.get("item_code"), filters.get("warehouse"), filters.get("item_prefix"))
@@ -3283,9 +3290,12 @@ For a complete sales return (financial + stock): create and submit both a Credit
3283
3290
  - If it is unclear whether an incoming order is a stocking request, a withdrawal or a normal order, ask.
3284
3291
 
3285
3292
  ### Partial deliveries, backorders and invoicing after delivery
3286
- - 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.
3293
+ - Order progress is derived from the submitted documents, per order line: delivered_qty (net of returns), returned_qty, billed_qty. Never set them. closed_qty is what was closed by hand. Open = qty − closed_qty − delivered_qty.
3287
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.
3288
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.
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
+ - **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.
3298
+ - **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.
3289
3299
  - 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.
3290
3300
  - 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.
3291
3301
  - "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.
@@ -3411,7 +3421,8 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
3411
3421
  - **ar-aging** — Outstanding receivables bucketed by overdue days (Current, 1-30, 31-60, 61-90, 90+). Filters: company, as_of_date.
3412
3422
  - **ap-aging** — Outstanding payables bucketed by overdue days. Filters: company, as_of_date.
3413
3423
  - **stock-balance** — Inventory quantities and valuations. Filters: item_code, warehouse.
3414
- - **sales-backlog** — Open sales order lines (ordered > delivered): ordered_qty, delivered_qty (net of returns), returned_qty, billed_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.
3424
+ - **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.
3425
+ - **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.
3415
3426
  - **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".
3416
3427
  - **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".
3417
3428
  - **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".
@@ -3519,14 +3530,14 @@ Users can attach PDFs and images (receipts, bills, contracts, screenshots) to th
3519
3530
  # ---------------------------------------------------------------------------
3520
3531
  # OpenAI report-spec specialist
3521
3532
  #
3522
- # GPT-6.2 Sol acts as the planner/orchestrator. When it decides a report needs
3533
+ # GPT-6.1 Sol acts as the planner/orchestrator. When it decides a report needs
3523
3534
  # a custom analytics view it calls the create/update custom analytics tools.
3524
- # Those handlers make a separate, narrowly prompted GPT-6.2 Sol call for the bounded
3535
+ # Those handlers make a separate, narrowly prompted GPT-6.1 Sol call for the bounded
3525
3536
  # declarative report spec. Both roles use the same provider and key (api/llm_provider.py).
3526
3537
  # ---------------------------------------------------------------------------
3527
3538
 
3528
3539
 
3529
- REPORT_SPECIALIST_MODEL = "gpt-6.2-sol"
3540
+ REPORT_SPECIALIST_MODEL = "gpt-6.1-sol"
3530
3541
 
3531
3542
 
3532
3543
  def _report_specialist_model() -> str:
@@ -3953,12 +3964,12 @@ async def generate_title(
3953
3964
  # Reasoning loop
3954
3965
  # ---------------------------------------------------------------------------
3955
3966
 
3956
- # GPT-6.2 Sol (default since core 1.4.26; GPT-6.1 Sol before) requires
3967
+ # GPT-6.1 Sol (the default; GPT-6.2 Sol in core 1.4.26 to 1.4.30) requires
3957
3968
  # Responses for function tools and does not support
3958
3969
  # reasoning effort "none", including tool-free wrap-ups after the step limit.
3959
3970
  # LAMBDA_ERP_CHAT_MODEL overrides it per deployment (e.g. to trial a cheaper
3960
3971
  # model on dev); see docs/llm-pricing.md.
3961
- ORCHESTRATOR_MODEL = "gpt-6.2-sol"
3972
+ ORCHESTRATOR_MODEL = "gpt-6.1-sol"
3962
3973
 
3963
3974
 
3964
3975
  def _chat_model() -> str:
@@ -4241,11 +4252,11 @@ async def run_thinking_loop(
4241
4252
  ):
4242
4253
  """Run the agentic reasoning loop.
4243
4254
 
4244
- The orchestrator and the report specialist use GPT-6.2 Sol.
4255
+ The orchestrator and the report specialist use GPT-6.1 Sol.
4245
4256
  When GPT decides to call
4246
4257
  `create_custom_analytics_report` or `update_custom_analytics_report`
4247
4258
  with an intent/feedback hint, the tool handler itself delegates the
4248
- declarative-spec step to a separate narrowly prompted GPT-6.2 Sol call. We emit an
4259
+ declarative-spec step to a separate narrowly prompted GPT-6.1 Sol call. We emit an
4249
4260
  `llm_provider` event around that delegation so the UI can surface it.
4250
4261
  """
4251
4262
  if not llm_configured():
@@ -4461,7 +4472,7 @@ async def run_thinking_loop(
4461
4472
  principal_ref[0] = refresh_auth_principal(principal_ref[0])
4462
4473
  live_role = principal_ref[0].get("role") if principal_ref[0] else None
4463
4474
 
4464
- # If the orchestrator is delegating report-spec generation to GPT-6.2 Sol,
4475
+ # If the orchestrator is delegating report-spec generation to GPT-6.1 Sol,
4465
4476
  # surface the handoff in the UI.
4466
4477
  will_delegate_to_report_specialist = (
4467
4478
  tool_allowed(fn_name, live_role)
@@ -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)}
@@ -72,6 +72,8 @@ async def lifespan(app: FastAPI):
72
72
  initialize_stock_actions()
73
73
  from api.pricing_actions import initialize_pricing_actions
74
74
  initialize_pricing_actions()
75
+ from api.order_actions import initialize_order_actions
76
+ initialize_order_actions()
75
77
  from api.menu_layout import initialize_menu_layout
76
78
  initialize_menu_layout()
77
79
  from api.list_columns import initialize_list_columns
@@ -179,6 +181,8 @@ app.include_router(admin.router, prefix="/api")
179
181
  app.include_router(chat_router, prefix="/api")
180
182
  app.include_router(chat_api.router, prefix="/api")
181
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")
182
186
 
183
187
 
184
188
  @app.get("/api/health")