lambda-erp 1.4.29__tar.gz → 1.4.31__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.
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/PKG-INFO +4 -4
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/README.md +3 -3
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/chat.py +162 -18
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/main.py +4 -0
- lambda_erp-1.4.31/api/number_series.py +106 -0
- lambda_erp-1.4.31/api/order_actions.py +98 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/providers.py +4 -3
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/mcp.py +1 -1
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/reports.py +22 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/frontend/src/api/client.ts +3 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/backlog.py +18 -11
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/buying/purchase_order.py +3 -1
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/database.py +106 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/model.py +12 -0
- lambda_erp-1.4.31/lambda_erp/order_closing.py +184 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/permissions.py +1 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/selling/sales_order.py +3 -1
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/stock/delivery_note.py +141 -26
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/stock/purchase_receipt.py +1 -1
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/stock/reservation.py +7 -4
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/workflow.py +24 -10
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/pyproject.toml +1 -1
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/.gitignore +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/LICENSE +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/attachments.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/auth.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/bootstrap.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/chat_links.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/demo_limits.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/deps.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/erp_context.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/errors.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/list_columns.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/list_values.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/llm_provider.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/mcp_oauth.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/mentions.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/menu_layout.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/oauth.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/pdf.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/pdf_contract.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/pdf_exports.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/pdf_fonts.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/pdf_pages.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/pdf_profiles.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/pdf_templates.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/pricing_actions.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/record_attachments.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/record_notes.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/remarks_md.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/accounting.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/actions.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/admin.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/analytics.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/availability.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/bank_statements.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/chat_api.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/documents.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/masters.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/pdf_templates.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/proposals.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/routers/setup.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/services.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/stock_actions.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/templates/_proposal_totals.html +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/templates/_record_base.html +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/templates/delivery_note.html +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/templates/document.html +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/templates/proposal.html +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/templates/record.html +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/templates/reservation.html +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/time_filters.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/tool_permissions.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/tool_results.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/api/write_context.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/docs/agents/README.md +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/frontend/LICENSE +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/frontend/README.md +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/bank_account.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/bank_statement_import.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/bank_transaction.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/budget.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/camt.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/chart_of_accounts.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/general_ledger.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/journal_entry.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/payment_entry.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/pos_invoice.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/purchase_invoice.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/revaluation.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/sales_invoice.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/settlement.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/engine.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/pack.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/packs/ch.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/packs/generic.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/profiles.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/setup/spine.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/accounting/subscription.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/addresses.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/assets/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/assets/asset.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/assets/lifecycle.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/assets/reservation.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/bundles.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/buying/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/controllers/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/controllers/currency.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/controllers/defaults.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/controllers/item_price.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/controllers/item_prices.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/controllers/price_resolution.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/controllers/pricing_rule.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/controllers/tax_defaults.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/controllers/taxes_and_totals.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/exceptions.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/hooks.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/master_integrity.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/selling/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/selling/proposal.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/selling/quotation.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/simulation.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/stock/__init__.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/stock/consignment.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/stock/serial.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/stock/stock_count.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/stock/stock_entry.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/stock/stock_ledger.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/timestamps.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/units.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/utils.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/lambda_erp/validation.py +0 -0
- {lambda_erp-1.4.29 → lambda_erp-1.4.31}/terraform/README.md +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: lambda-erp
|
|
3
|
-
Version: 1.4.
|
|
3
|
+
Version: 1.4.31
|
|
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.
|
|
270
|
-
LAMBDA_ERP_REPORT_MODEL=gpt-6.
|
|
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.
|
|
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.
|
|
239
|
-
LAMBDA_ERP_REPORT_MODEL=gpt-6.
|
|
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.
|
|
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.
|
|
@@ -380,6 +380,87 @@ def serialize_chat_message(
|
|
|
380
380
|
return msg
|
|
381
381
|
|
|
382
382
|
|
|
383
|
+
# A stored step as the chat shows it: the call, its label and a bounded view of
|
|
384
|
+
# the result (the stored result itself can be large).
|
|
385
|
+
STEP_TEXT_MAX = 500
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _step_from_trace(call: dict | None, result: dict | None) -> dict:
|
|
389
|
+
call = call or {}
|
|
390
|
+
result = result or {}
|
|
391
|
+
step: dict = {"tool": call.get("tool") or result.get("tool") or ""}
|
|
392
|
+
if call.get("intent"):
|
|
393
|
+
step["intent"] = call["intent"]
|
|
394
|
+
if isinstance(call.get("args"), dict):
|
|
395
|
+
step["args"] = call["args"]
|
|
396
|
+
if result:
|
|
397
|
+
step["success"] = bool(result.get("success"))
|
|
398
|
+
summary = result.get("summary")
|
|
399
|
+
if not isinstance(summary, str):
|
|
400
|
+
raw = result.get("result")
|
|
401
|
+
summary = raw if isinstance(raw, str) else json.dumps(raw, default=str) if raw is not None else ""
|
|
402
|
+
step["summary"] = summary[:STEP_TEXT_MAX] + ("..." if len(summary) > STEP_TEXT_MAX else "")
|
|
403
|
+
if result.get("error"):
|
|
404
|
+
step["error"] = str(result["error"])[:STEP_TEXT_MAX]
|
|
405
|
+
return step
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _steps_by_answer(session_id: str, rows: list[dict]) -> dict[int, list[dict]]:
|
|
409
|
+
"""{assistant message id: the tool steps of the turn that ended in it}.
|
|
410
|
+
|
|
411
|
+
Steps are the stored tool rows after the previous user or assistant message
|
|
412
|
+
and before the answer. A turn that ended without an answer (an error, a
|
|
413
|
+
closed tab) has no message to hang its steps on; they stay stored only.
|
|
414
|
+
"""
|
|
415
|
+
answer_ids = [row["id"] for row in rows if row.get("role") == "assistant" and row.get("id") is not None]
|
|
416
|
+
if not answer_ids:
|
|
417
|
+
return {}
|
|
418
|
+
first = min(row["id"] for row in rows if row.get("id") is not None)
|
|
419
|
+
db = get_db()
|
|
420
|
+
before = db.sql(
|
|
421
|
+
'SELECT MAX(id) AS id FROM "Chat Message" WHERE session_id = ? AND role IN (\'user\', \'assistant\') AND id < ?',
|
|
422
|
+
[session_id, int(first)],
|
|
423
|
+
)
|
|
424
|
+
low = (before[0]["id"] if before and before[0]["id"] is not None else 0)
|
|
425
|
+
trace = db.sql(
|
|
426
|
+
'SELECT id, role, message_type, content FROM "Chat Message" '
|
|
427
|
+
'WHERE session_id = ? AND id > ? AND id <= ? '
|
|
428
|
+
'AND (role IN (\'user\', \'assistant\') OR message_type IN (\'tool_call\', \'tool_result\')) ORDER BY id',
|
|
429
|
+
[session_id, int(low), int(max(answer_ids))],
|
|
430
|
+
)
|
|
431
|
+
out: dict[int, list[dict]] = {}
|
|
432
|
+
steps: list[dict] = []
|
|
433
|
+
open_calls: list[tuple[dict, int]] = [] # (call payload, index in steps) still without a result
|
|
434
|
+
for row in trace:
|
|
435
|
+
if row["role"] in ("user", "assistant"):
|
|
436
|
+
if row["role"] == "assistant" and steps:
|
|
437
|
+
out[row["id"]] = steps
|
|
438
|
+
steps, open_calls = [], []
|
|
439
|
+
continue
|
|
440
|
+
try:
|
|
441
|
+
payload = json.loads(row.get("content") or "{}")
|
|
442
|
+
except (json.JSONDecodeError, TypeError):
|
|
443
|
+
continue
|
|
444
|
+
if not isinstance(payload, dict):
|
|
445
|
+
continue
|
|
446
|
+
if row["message_type"] == "tool_call":
|
|
447
|
+
steps.append(_step_from_trace(payload, None))
|
|
448
|
+
open_calls.append((payload, len(steps) - 1))
|
|
449
|
+
continue
|
|
450
|
+
# A result belongs to the latest open call of the same tool.
|
|
451
|
+
match = next((i for i in range(len(open_calls) - 1, -1, -1) if open_calls[i][0].get("tool") == payload.get("tool")), None)
|
|
452
|
+
if match is None:
|
|
453
|
+
if steps and steps[-1].get("tool") == payload.get("tool"):
|
|
454
|
+
# A second verdict on the same step (e.g. the PDF check after export).
|
|
455
|
+
steps[-1] = {**steps[-1], **{k: v for k, v in _step_from_trace(None, payload).items() if k != "tool"}}
|
|
456
|
+
else:
|
|
457
|
+
steps.append(_step_from_trace(None, payload))
|
|
458
|
+
continue
|
|
459
|
+
call, index = open_calls.pop(match)
|
|
460
|
+
steps[index] = _step_from_trace(call, payload)
|
|
461
|
+
return out
|
|
462
|
+
|
|
463
|
+
|
|
383
464
|
def load_serialized_chat_history(
|
|
384
465
|
session_id: str,
|
|
385
466
|
limit: int = 20,
|
|
@@ -391,6 +472,11 @@ def load_serialized_chat_history(
|
|
|
391
472
|
messages exist beyond this page.
|
|
392
473
|
"""
|
|
393
474
|
rows = load_chat_history(session_id, limit=limit, before_id=before_id)
|
|
475
|
+
try:
|
|
476
|
+
steps_by_answer = _steps_by_answer(session_id, rows)
|
|
477
|
+
except Exception: # noqa: BLE001 - the answers matter more than their steps
|
|
478
|
+
logger.warning("Could not load the steps of session %s", session_id, exc_info=True)
|
|
479
|
+
steps_by_answer = {}
|
|
394
480
|
history_messages = []
|
|
395
481
|
for row in rows:
|
|
396
482
|
role = row["role"]
|
|
@@ -406,11 +492,12 @@ def load_serialized_chat_history(
|
|
|
406
492
|
except (json.JSONDecodeError, AttributeError):
|
|
407
493
|
pass
|
|
408
494
|
if content or attachments:
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
role, content, row.get("created_at"), attachments, row.get("id"),
|
|
412
|
-
)
|
|
495
|
+
message = serialize_chat_message(
|
|
496
|
+
role, content, row.get("created_at"), attachments, row.get("id"),
|
|
413
497
|
)
|
|
498
|
+
if row.get("id") in steps_by_answer:
|
|
499
|
+
message["steps"] = steps_by_answer[row["id"]]
|
|
500
|
+
history_messages.append(message)
|
|
414
501
|
|
|
415
502
|
oldest_id = history_messages[0].get("id") if history_messages else None
|
|
416
503
|
has_more = False
|
|
@@ -970,7 +1057,7 @@ TOOLS = [
|
|
|
970
1057
|
"properties": {
|
|
971
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."},
|
|
972
1059
|
"offset": {"type": "integer", "description": "Skip this many rows.", "default": 0},
|
|
973
|
-
"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"]},
|
|
974
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": {}},
|
|
975
1062
|
},
|
|
976
1063
|
"required": ["report_type"],
|
|
@@ -2183,6 +2270,10 @@ def _run_report(args):
|
|
|
2183
2270
|
from api.routers.reports import _purchase_backlog
|
|
2184
2271
|
return _purchase_backlog(db, filters.get("supplier"), filters.get("item_code"), filters.get("warehouse"),
|
|
2185
2272
|
bool(filters.get("overdue_only")))
|
|
2273
|
+
elif report_type == "unbilled-deliveries":
|
|
2274
|
+
from api.routers.reports import _unbilled_deliveries
|
|
2275
|
+
return _unbilled_deliveries(db, filters.get("customer"), filters.get("company"), filters.get("from_date"),
|
|
2276
|
+
filters.get("to_date"), filters.get("delivery_note"))
|
|
2186
2277
|
elif report_type == "stock-availability":
|
|
2187
2278
|
from api.routers.reports import _stock_availability
|
|
2188
2279
|
return _stock_availability(db, filters.get("item_code"), filters.get("warehouse"), filters.get("item_prefix"))
|
|
@@ -2949,6 +3040,12 @@ Only state that something was done — created, changed, enabled/disabled, booke
|
|
|
2949
3040
|
- Respect document requirements from get_document_fields. Missing required data or ambiguous matches require a targeted question, not guessed IDs, omitted links, or zero quantities. A tool error means the action failed; _validation.warnings must be explained.
|
|
2950
3041
|
- If you can't confirm an action took effect, re-fetch and look, or tell the user you couldn't confirm it — never guess.
|
|
2951
3042
|
|
|
3043
|
+
## Document numbers
|
|
3044
|
+
Each document type numbers its records from a range ("SINV-0006" comes after "SINV-0005"). To say which number comes next, call `get_number_series`, never guess from a list. When someone wants numbers to start higher ("invoices from 320 on"), an admin sets the range with `set_next_number`; do not give single documents hand-picked numbers for that. A document created with a hand-set number ahead of the range moves the range past it. Existing documents keep their numbers; a draft keeps the number it was created with.
|
|
3045
|
+
|
|
3046
|
+
## Step labels (`step_label`)
|
|
3047
|
+
Every tool takes an optional `step_label`: a short phrase in the user's language saying what this step does, e.g. "Versand als eigene Position erfassen" or "Find the customer's open invoices". The user sees it as the label of the step, so say what and why in plain words (no tool names, no JSON), at most about 80 characters. It is shown only to people who can read this chat; it changes nothing about what the tool does.
|
|
3048
|
+
|
|
2952
3049
|
## Answering data questions — three paths
|
|
2953
3050
|
|
|
2954
3051
|
**Path 1: single-record lookup → `list_documents` / `get_document`.** For "is SINV-0042 paid", "what did customer X order last", "show me the latest 5 purchase orders" — fetch the rows directly. Don't try to aggregate in your head unless there are only a handful of rows in front of you.
|
|
@@ -3190,9 +3287,11 @@ For a complete sales return (financial + stock): create and submit both a Credit
|
|
|
3190
3287
|
- If it is unclear whether an incoming order is a stocking request, a withdrawal or a normal order, ask.
|
|
3191
3288
|
|
|
3192
3289
|
### Partial deliveries, backorders and invoicing after delivery
|
|
3193
|
-
- 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.
|
|
3290
|
+
- 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.
|
|
3194
3291
|
- 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.
|
|
3195
3292
|
- 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
|
+
- **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.
|
|
3294
|
+
- **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.
|
|
3196
3295
|
- 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.
|
|
3197
3296
|
- 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.
|
|
3198
3297
|
- "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.
|
|
@@ -3318,7 +3417,8 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
|
|
|
3318
3417
|
- **ar-aging** — Outstanding receivables bucketed by overdue days (Current, 1-30, 31-60, 61-90, 90+). Filters: company, as_of_date.
|
|
3319
3418
|
- **ap-aging** — Outstanding payables bucketed by overdue days. Filters: company, as_of_date.
|
|
3320
3419
|
- **stock-balance** — Inventory quantities and valuations. Filters: item_code, warehouse.
|
|
3321
|
-
- **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.
|
|
3420
|
+
- **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.
|
|
3322
3422
|
- **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".
|
|
3323
3423
|
- **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".
|
|
3324
3424
|
- **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".
|
|
@@ -3426,14 +3526,14 @@ Users can attach PDFs and images (receipts, bills, contracts, screenshots) to th
|
|
|
3426
3526
|
# ---------------------------------------------------------------------------
|
|
3427
3527
|
# OpenAI report-spec specialist
|
|
3428
3528
|
#
|
|
3429
|
-
# GPT-6.
|
|
3529
|
+
# GPT-6.1 Sol acts as the planner/orchestrator. When it decides a report needs
|
|
3430
3530
|
# a custom analytics view it calls the create/update custom analytics tools.
|
|
3431
|
-
# Those handlers make a separate, narrowly prompted GPT-6.
|
|
3531
|
+
# Those handlers make a separate, narrowly prompted GPT-6.1 Sol call for the bounded
|
|
3432
3532
|
# declarative report spec. Both roles use the same provider and key (api/llm_provider.py).
|
|
3433
3533
|
# ---------------------------------------------------------------------------
|
|
3434
3534
|
|
|
3435
3535
|
|
|
3436
|
-
REPORT_SPECIALIST_MODEL = "gpt-6.
|
|
3536
|
+
REPORT_SPECIALIST_MODEL = "gpt-6.1-sol"
|
|
3437
3537
|
|
|
3438
3538
|
|
|
3439
3539
|
def _report_specialist_model() -> str:
|
|
@@ -3860,12 +3960,12 @@ async def generate_title(
|
|
|
3860
3960
|
# Reasoning loop
|
|
3861
3961
|
# ---------------------------------------------------------------------------
|
|
3862
3962
|
|
|
3863
|
-
# GPT-6.
|
|
3963
|
+
# GPT-6.1 Sol (the default; GPT-6.2 Sol in core 1.4.26 to 1.4.30) requires
|
|
3864
3964
|
# Responses for function tools and does not support
|
|
3865
3965
|
# reasoning effort "none", including tool-free wrap-ups after the step limit.
|
|
3866
3966
|
# LAMBDA_ERP_CHAT_MODEL overrides it per deployment (e.g. to trial a cheaper
|
|
3867
3967
|
# model on dev); see docs/llm-pricing.md.
|
|
3868
|
-
ORCHESTRATOR_MODEL = "gpt-6.
|
|
3968
|
+
ORCHESTRATOR_MODEL = "gpt-6.1-sol"
|
|
3869
3969
|
|
|
3870
3970
|
|
|
3871
3971
|
def _chat_model() -> str:
|
|
@@ -3933,6 +4033,49 @@ class _ShimUsage:
|
|
|
3933
4033
|
self.prompt_tokens_details = _ShimUsageDetails(cached_tokens)
|
|
3934
4034
|
|
|
3935
4035
|
|
|
4036
|
+
# An optional one-line label the model gives each tool call ("what this step
|
|
4037
|
+
# does"), shown on the step in the chat and kept with the stored step. Added to
|
|
4038
|
+
# the chat's tool schemas only, and taken out of the arguments before a tool
|
|
4039
|
+
# runs, so no tool ever sees it (several forbid unknown fields).
|
|
4040
|
+
# Not "intent": create_custom_analytics_report has a parameter of that name.
|
|
4041
|
+
INTENT_PARAM = "step_label"
|
|
4042
|
+
INTENT_MAX = 160
|
|
4043
|
+
_INTENT_SCHEMA = {
|
|
4044
|
+
"type": "string",
|
|
4045
|
+
"maxLength": INTENT_MAX,
|
|
4046
|
+
"description": "Optional: what this step does and why, in the user's language, at most ~80 characters "
|
|
4047
|
+
"(shown to the user as the step's label).",
|
|
4048
|
+
}
|
|
4049
|
+
|
|
4050
|
+
|
|
4051
|
+
def _with_intent(tools: list) -> list:
|
|
4052
|
+
"""The tool list with the optional `intent` parameter on every function."""
|
|
4053
|
+
out = []
|
|
4054
|
+
for tool in tools or []:
|
|
4055
|
+
fn = tool.get("function") if isinstance(tool, dict) else None
|
|
4056
|
+
params = fn.get("parameters") if fn else None
|
|
4057
|
+
if not isinstance(params, dict) or params.get("type", "object") != "object":
|
|
4058
|
+
out.append(tool)
|
|
4059
|
+
continue
|
|
4060
|
+
props = params.get("properties") or {}
|
|
4061
|
+
if INTENT_PARAM in props: # a tool's own parameter of that name wins
|
|
4062
|
+
out.append(tool)
|
|
4063
|
+
continue
|
|
4064
|
+
out.append({**tool, "function": {**fn, "parameters": {**params, "properties": {**props, INTENT_PARAM: _INTENT_SCHEMA}}}})
|
|
4065
|
+
return out
|
|
4066
|
+
|
|
4067
|
+
|
|
4068
|
+
def _pop_intent(args) -> str | None:
|
|
4069
|
+
"""Remove the step label from a call's arguments; return it trimmed, or None."""
|
|
4070
|
+
if not isinstance(args, dict):
|
|
4071
|
+
return None
|
|
4072
|
+
value = args.pop(INTENT_PARAM, None)
|
|
4073
|
+
if not isinstance(value, str):
|
|
4074
|
+
return None
|
|
4075
|
+
value = " ".join(value.split())
|
|
4076
|
+
return value[:INTENT_MAX] or None
|
|
4077
|
+
|
|
4078
|
+
|
|
3936
4079
|
def _responses_tools_from_chat(tools: list) -> list:
|
|
3937
4080
|
"""Chat tool schema {"type":"function","function":{name,...}} -> the flatter
|
|
3938
4081
|
Responses shape {"type":"function","name",...}."""
|
|
@@ -4105,11 +4248,11 @@ async def run_thinking_loop(
|
|
|
4105
4248
|
):
|
|
4106
4249
|
"""Run the agentic reasoning loop.
|
|
4107
4250
|
|
|
4108
|
-
The orchestrator and the report specialist use GPT-6.
|
|
4251
|
+
The orchestrator and the report specialist use GPT-6.1 Sol.
|
|
4109
4252
|
When GPT decides to call
|
|
4110
4253
|
`create_custom_analytics_report` or `update_custom_analytics_report`
|
|
4111
4254
|
with an intent/feedback hint, the tool handler itself delegates the
|
|
4112
|
-
declarative-spec step to a separate narrowly prompted GPT-6.
|
|
4255
|
+
declarative-spec step to a separate narrowly prompted GPT-6.1 Sol call. We emit an
|
|
4113
4256
|
`llm_provider` event around that delegation so the UI can surface it.
|
|
4114
4257
|
"""
|
|
4115
4258
|
if not llm_configured():
|
|
@@ -4263,7 +4406,7 @@ async def run_thinking_loop(
|
|
|
4263
4406
|
# or the legacy API for compatible models. Returns Chat-shaped
|
|
4264
4407
|
# (message, usage) either way, so everything below is unchanged.
|
|
4265
4408
|
message, usage = await asyncio.to_thread(
|
|
4266
|
-
_orchestrator_turn, openai_client, messages, build_tools(user_info, native_chat=True), max_completion,
|
|
4409
|
+
_orchestrator_turn, openai_client, messages, _with_intent(build_tools(user_info, native_chat=True)), max_completion,
|
|
4267
4410
|
)
|
|
4268
4411
|
except Exception as e:
|
|
4269
4412
|
await on_event({"type": "error", "content": f"Error calling LLM: {e}"})
|
|
@@ -4313,10 +4456,11 @@ async def run_thinking_loop(
|
|
|
4313
4456
|
except json.JSONDecodeError:
|
|
4314
4457
|
fn_args = {}
|
|
4315
4458
|
tool_call_id = tc.id
|
|
4459
|
+
intent = _pop_intent(fn_args)
|
|
4316
4460
|
|
|
4317
|
-
await on_event({"type": "tool_call", "tool": fn_name, "args": fn_args})
|
|
4461
|
+
await on_event({"type": "tool_call", "tool": fn_name, "args": fn_args, "intent": intent})
|
|
4318
4462
|
if session_id:
|
|
4319
|
-
_save_tool_trace(session_id, "tool_call", {"tool": fn_name, "args": fn_args})
|
|
4463
|
+
_save_tool_trace(session_id, "tool_call", {"tool": fn_name, "args": fn_args, "intent": intent})
|
|
4320
4464
|
|
|
4321
4465
|
# LLM turns can run for many seconds. Re-resolve the principal at
|
|
4322
4466
|
# the actual execution boundary so a demotion, disable, or key
|
|
@@ -4324,7 +4468,7 @@ async def run_thinking_loop(
|
|
|
4324
4468
|
principal_ref[0] = refresh_auth_principal(principal_ref[0])
|
|
4325
4469
|
live_role = principal_ref[0].get("role") if principal_ref[0] else None
|
|
4326
4470
|
|
|
4327
|
-
# If the orchestrator is delegating report-spec generation to GPT-6.
|
|
4471
|
+
# If the orchestrator is delegating report-spec generation to GPT-6.1 Sol,
|
|
4328
4472
|
# surface the handoff in the UI.
|
|
4329
4473
|
will_delegate_to_report_specialist = (
|
|
4330
4474
|
tool_allowed(fn_name, live_role)
|
|
@@ -72,10 +72,14 @@ 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
|
|
78
80
|
initialize_list_columns()
|
|
81
|
+
from api.number_series import initialize_number_series
|
|
82
|
+
initialize_number_series()
|
|
79
83
|
from api.pdf_templates import initialize_pdf_templates
|
|
80
84
|
initialize_pdf_templates()
|
|
81
85
|
from api.pdf_pages import initialize_pdf_pages
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Number ranges of the document types: read them, and (admins) set the next number.
|
|
2
|
+
|
|
3
|
+
Each document type numbers its records "PREFIX-<n>" from one shared counter
|
|
4
|
+
(Database.next_in_series), e.g. SINV-0006. An admin can move a range up, for
|
|
5
|
+
example so invoices continue at 320, or back down as far as the highest number
|
|
6
|
+
already used, never onto a taken number. A record saved with a hand-set number
|
|
7
|
+
ahead of its range moves the range past it (BaseDocument._follow_hand_set_name).
|
|
8
|
+
Since 1.4.30.
|
|
9
|
+
"""
|
|
10
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
11
|
+
|
|
12
|
+
from api import services
|
|
13
|
+
from lambda_erp import permissions
|
|
14
|
+
from lambda_erp.database import get_db
|
|
15
|
+
|
|
16
|
+
MAX_NUMBER = 999_999_999
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class GetSeries(BaseModel):
|
|
20
|
+
model_config = ConfigDict(extra="forbid")
|
|
21
|
+
doctype: str | None = Field(default=None, max_length=100,
|
|
22
|
+
description="Document type slug, e.g. sales-invoice. Omit for every type you may read.")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SetNext(BaseModel):
|
|
26
|
+
model_config = ConfigDict(extra="forbid")
|
|
27
|
+
doctype: str = Field(min_length=1, max_length=100, description="Document type slug, e.g. sales-invoice")
|
|
28
|
+
next_number: int = Field(ge=1, le=MAX_NUMBER,
|
|
29
|
+
description="The number the next new document of this type gets, e.g. 321 for SINV-0321.")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _format(prefix: str, number: int) -> str:
|
|
33
|
+
return f"{prefix}-{number:04d}"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _types(slug: str | None):
|
|
37
|
+
if slug:
|
|
38
|
+
doctype = services.SLUG_TO_DOCTYPE.get(slug)
|
|
39
|
+
if not doctype or doctype not in services.DOCUMENT_CLASSES:
|
|
40
|
+
raise ValueError(f"Unknown document type {slug!r}; use a slug such as sales-invoice.")
|
|
41
|
+
permissions.require(doctype, "read")
|
|
42
|
+
return [(slug, doctype)]
|
|
43
|
+
out = []
|
|
44
|
+
for doctype in services.DOCUMENT_CLASSES:
|
|
45
|
+
slug = services.DOCTYPE_TO_SLUG.get(doctype)
|
|
46
|
+
if slug and permissions.can(doctype, "read"):
|
|
47
|
+
out.append((slug, doctype))
|
|
48
|
+
return sorted(out, key=lambda pair: pair[1])
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _row(slug: str, doctype: str) -> dict | None:
|
|
52
|
+
prefix = getattr(services.DOCUMENT_CLASSES[doctype], "PREFIX", None)
|
|
53
|
+
if not prefix:
|
|
54
|
+
return None
|
|
55
|
+
state = get_db().series_state(prefix)
|
|
56
|
+
next_number = state["current"] + 1
|
|
57
|
+
return {
|
|
58
|
+
"doctype": slug,
|
|
59
|
+
"doctype_name": doctype,
|
|
60
|
+
"prefix": prefix,
|
|
61
|
+
"last_number": state["current"],
|
|
62
|
+
"next_number": next_number,
|
|
63
|
+
"next_name": _format(prefix, next_number),
|
|
64
|
+
"highest_used": state["highest_used"],
|
|
65
|
+
"lowest_allowed_next": state["highest_used"] + 1,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def get_number_series(args, user=None):
|
|
70
|
+
data = GetSeries.model_validate(args or {})
|
|
71
|
+
rows = [row for row in (_row(slug, doctype) for slug, doctype in _types(data.doctype)) if row]
|
|
72
|
+
return {"series": rows,
|
|
73
|
+
"note": "next_name is what the next new document of the type gets. Numbers already used are skipped."}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def set_next_number(args, user=None):
|
|
77
|
+
data = SetNext.model_validate(args)
|
|
78
|
+
(slug, doctype), = _types(data.doctype)
|
|
79
|
+
prefix = getattr(services.DOCUMENT_CLASSES[doctype], "PREFIX", None)
|
|
80
|
+
if not prefix:
|
|
81
|
+
raise ValueError(f"{doctype} has no number range.")
|
|
82
|
+
get_db().set_series_next(prefix, data.next_number)
|
|
83
|
+
row = _row(slug, doctype)
|
|
84
|
+
shared = [other for other, cls in services.DOCUMENT_CLASSES.items()
|
|
85
|
+
if other != doctype and getattr(cls, "PREFIX", None) == prefix]
|
|
86
|
+
row["note"] = (f"The next new {doctype} gets {row['next_name']}. Existing documents keep their numbers."
|
|
87
|
+
+ (f" The range is shared with {', '.join(shared)}." if shared else ""))
|
|
88
|
+
return row
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def initialize_number_series():
|
|
92
|
+
services.register_action(
|
|
93
|
+
"get_number_series", get_number_series, minimum_role="viewer", pass_user=True,
|
|
94
|
+
parameters=GetSeries.model_json_schema(),
|
|
95
|
+
description=(
|
|
96
|
+
"Show the number ranges of document types: the prefix, the last number handed out and the "
|
|
97
|
+
"number the next new document gets (next_name, e.g. SINV-0006). Use it to answer which number "
|
|
98
|
+
"comes next instead of guessing from a list of documents."))
|
|
99
|
+
services.register_action(
|
|
100
|
+
"set_next_number", set_next_number, minimum_role="admin", pass_user=True,
|
|
101
|
+
parameters=SetNext.model_json_schema(),
|
|
102
|
+
description=(
|
|
103
|
+
"Admins only: set the number the next new document of a type gets, e.g. sales-invoice 321 so "
|
|
104
|
+
"invoices continue at SINV-0321. It cannot be at or below a number already used. Existing "
|
|
105
|
+
"documents keep their numbers. Use this when someone wants numbers to start higher, instead "
|
|
106
|
+
"of giving single documents hand-picked numbers."))
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Order actions beyond a single document save: closing what is left open on
|
|
2
|
+
order lines and one invoice for several deliveries. REST
|
|
3
|
+
(/api/actions/...), chat and MCP."""
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from pydantic import Field
|
|
7
|
+
|
|
8
|
+
from api import mentions, services
|
|
9
|
+
from lambda_erp import permissions
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CloseOrderLines(mentions.Input):
|
|
13
|
+
doctype: Literal["Sales Order", "Purchase Order"] = "Sales Order"
|
|
14
|
+
order: str = Field(min_length=1, max_length=200)
|
|
15
|
+
reason: str = Field(min_length=1, max_length=500)
|
|
16
|
+
lines: list[str] | None = Field(default=None, max_length=500)
|
|
17
|
+
qty: float | None = Field(default=None, gt=0)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ReopenOrderLines(mentions.Input):
|
|
21
|
+
doctype: Literal["Sales Order", "Purchase Order"] = "Sales Order"
|
|
22
|
+
order: str = Field(min_length=1, max_length=200)
|
|
23
|
+
lines: list[str] | None = Field(default=None, max_length=500)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CollectiveInvoice(mentions.Input):
|
|
27
|
+
customer: str | None = Field(default=None, max_length=200)
|
|
28
|
+
company: str | None = Field(default=None, max_length=200)
|
|
29
|
+
from_date: str | None = Field(default=None, max_length=10)
|
|
30
|
+
to_date: str | None = Field(default=None, max_length=10)
|
|
31
|
+
delivery_notes: list[str] | None = Field(default=None, max_length=500)
|
|
32
|
+
lines: list[str] | None = Field(default=None, max_length=2000)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _user_id(user):
|
|
36
|
+
return (user or {}).get("user_id") or (user or {}).get("name")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def close_lines(args, user=None):
|
|
40
|
+
data = CloseOrderLines.model_validate(args)
|
|
41
|
+
permissions.require_readable(data.doctype, data.order)
|
|
42
|
+
permissions.require(data.doctype, "update")
|
|
43
|
+
from lambda_erp.order_closing import close_order_lines
|
|
44
|
+
return close_order_lines(data.doctype, data.order, reason=data.reason, lines=data.lines, qty=data.qty,
|
|
45
|
+
closed_by=_user_id(user))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def reopen_lines(args):
|
|
49
|
+
data = ReopenOrderLines.model_validate(args)
|
|
50
|
+
permissions.require_readable(data.doctype, data.order)
|
|
51
|
+
permissions.require(data.doctype, "update")
|
|
52
|
+
from lambda_erp.order_closing import reopen_order_lines
|
|
53
|
+
return reopen_order_lines(data.doctype, data.order, lines=data.lines)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def prepare_collective_invoice(args):
|
|
57
|
+
data = CollectiveInvoice.model_validate(args)
|
|
58
|
+
permissions.require_writable("Sales Invoice", "create", keeps_hidden_fields=True)
|
|
59
|
+
permissions.require("Delivery Note", "read")
|
|
60
|
+
permissions.require_in_scope("customer", data.customer, optional=True)
|
|
61
|
+
for name in data.delivery_notes or []:
|
|
62
|
+
permissions.require_readable("Delivery Note", name)
|
|
63
|
+
from lambda_erp.stock.delivery_note import make_collective_sales_invoice
|
|
64
|
+
invoice = make_collective_sales_invoice(
|
|
65
|
+
data.customer, company=data.company, from_date=data.from_date, to_date=data.to_date,
|
|
66
|
+
delivery_notes=data.delivery_notes, lines=data.lines)
|
|
67
|
+
permissions.require_in_scope("customer", invoice.customer)
|
|
68
|
+
invoice.save()
|
|
69
|
+
return services.load_document("sales-invoice", invoice.name)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def initialize_order_actions():
|
|
73
|
+
services.register_action(
|
|
74
|
+
"close_order_lines", close_lines,
|
|
75
|
+
description=(
|
|
76
|
+
"Close what is left OPEN on lines of a SUBMITTED sales order (doctype 'Sales Order', the default) or "
|
|
77
|
+
"purchase order ('Purchase Order'): the customer cancelled the rest, or the supplier will never send it. "
|
|
78
|
+
"All lines with something open, or `lines` (row names or positions); `qty` closes only part of one "
|
|
79
|
+
"line. A reason is required. The closed quantity is no longer to deliver, receive or bill; deliveries "
|
|
80
|
+
"and invoices already posted stay as they are; a reservation for it is released. Delivered or invoiced "
|
|
81
|
+
"quantities cannot be closed. Confirm with the user which lines before closing."),
|
|
82
|
+
parameters=CloseOrderLines.model_json_schema(), minimum_role="manager", pass_user=True)
|
|
83
|
+
services.register_action(
|
|
84
|
+
"reopen_order_lines", reopen_lines,
|
|
85
|
+
description=(
|
|
86
|
+
"Undo close_order_lines on a submitted sales or purchase order: the closed quantity of `lines` (or of "
|
|
87
|
+
"every closed line) is open again. A released reservation is not restored; reserve again if needed."),
|
|
88
|
+
parameters=ReopenOrderLines.model_json_schema(), minimum_role="manager")
|
|
89
|
+
services.register_action(
|
|
90
|
+
"prepare_collective_invoice", prepare_collective_invoice,
|
|
91
|
+
description=(
|
|
92
|
+
"Create ONE DRAFT Sales Invoice for what several deliveries delivered and has not been billed yet "
|
|
93
|
+
"(monthly / collective invoice): every unbilled line of the customer's submitted delivery notes, "
|
|
94
|
+
"optionally from_date / to_date (posting dates, YYYY-MM-DD), or the named delivery_notes, or only the "
|
|
95
|
+
"delivery note lines in `lines`. Each invoice line keeps its delivery note and order line; already "
|
|
96
|
+
"billed lines are never taken again. Check what is open first with the unbilled-deliveries report. "
|
|
97
|
+
"Nothing is posted until the draft is submitted."),
|
|
98
|
+
parameters=CollectiveInvoice.model_json_schema(), minimum_role="manager")
|
|
@@ -34,7 +34,8 @@ OPENAI_PRICING: dict[str, dict[str, Any]] = {
|
|
|
34
34
|
],
|
|
35
35
|
},
|
|
36
36
|
# The models available to us, Standard tier, verified 2026-10-30 (the
|
|
37
|
-
# GPT-6.2 models 2026-11-18,
|
|
37
|
+
# GPT-6.2 models 2026-11-18, all rechecked 2026-11-24,
|
|
38
|
+
# developers.openai.com/api/docs/pricing; there is no GPT-6.1 Astra). Above
|
|
38
39
|
# 272K input tokens the higher rates apply to the entire request
|
|
39
40
|
# (including cache hits). cache_write is the 30-minute retention rate,
|
|
40
41
|
# cache_write_12h the 12-hour one.
|
|
@@ -78,14 +79,14 @@ TRANSCRIBE_PRICING: dict[str, dict[str, float]] = {
|
|
|
78
79
|
|
|
79
80
|
|
|
80
81
|
# ---------------------------------------------------------------------------
|
|
81
|
-
# Rate lookup — unknown model IDs are estimated at the gpt-6.
|
|
82
|
+
# Rate lookup — unknown model IDs are estimated at the gpt-6.1-sol rates.
|
|
82
83
|
# Register a model explicitly before using it; this fallback is not a price cap.
|
|
83
84
|
# ---------------------------------------------------------------------------
|
|
84
85
|
|
|
85
86
|
def get_openai_rates(model: str, input_tokens: int = 0) -> dict[str, float]:
|
|
86
87
|
entry = OPENAI_PRICING.get(model)
|
|
87
88
|
if entry is None:
|
|
88
|
-
entry = OPENAI_PRICING["gpt-6.
|
|
89
|
+
entry = OPENAI_PRICING["gpt-6.1-sol"]
|
|
89
90
|
if entry.get("tiered"):
|
|
90
91
|
for tier in entry["tiers"]:
|
|
91
92
|
cap = tier.get("max_input_tokens")
|
|
@@ -52,7 +52,7 @@ _EXCLUDE = {
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
_READ_ONLY = {
|
|
55
|
-
'search_mention_users', 'list_my_mentions', 'list_record_notes', 'get_menu_layout', 'get_list_columns',
|
|
55
|
+
'search_mention_users', 'list_my_mentions', 'list_record_notes', 'get_menu_layout', 'get_list_columns', 'get_number_series',
|
|
56
56
|
'list_pdf_templates', 'get_pdf_template', 'view_pdf_pages', 'get_pdf_text_defaults',
|
|
57
57
|
'get_erp_context',
|
|
58
58
|
'list_documents', 'get_document_fields', 'get_document', 'get_master_fields',
|
|
@@ -544,6 +544,28 @@ 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):
|
|
548
|
+
"""Delivered and not yet invoiced, per delivery note line: what a
|
|
549
|
+
collective (monthly) invoice would bill. Selling prices only."""
|
|
550
|
+
permissions.require_artifact("report", "unbilled-deliveries")
|
|
551
|
+
permissions.require("Delivery Note", "read")
|
|
552
|
+
from lambda_erp.stock.delivery_note import unbilled_delivery_lines
|
|
553
|
+
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
|
+
return {"rows": permissions.scope_rows("report", "unbilled-deliveries", rows)}
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
@router.get("/unbilled-deliveries")
|
|
559
|
+
def unbilled_deliveries_report(
|
|
560
|
+
customer: str | None = None,
|
|
561
|
+
company: str | None = None,
|
|
562
|
+
from_date: str | None = None,
|
|
563
|
+
to_date: str | None = None,
|
|
564
|
+
delivery_note: str | None = None,
|
|
565
|
+
):
|
|
566
|
+
return _unbilled_deliveries(get_db(), customer, company, from_date, to_date, delivery_note)
|
|
567
|
+
|
|
568
|
+
|
|
547
569
|
@router.get("/stock-detail")
|
|
548
570
|
def stock_detail(
|
|
549
571
|
item_code: str | None = None,
|