lambda-erp 1.4.28__tar.gz → 1.4.30__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.28 → lambda_erp-1.4.30}/PKG-INFO +2 -1
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/chat.py +221 -41
- lambda_erp-1.4.30/api/list_columns.py +178 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/main.py +4 -0
- lambda_erp-1.4.30/api/number_series.py +106 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/pdf_templates.py +5 -2
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/providers.py +1 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/documents.py +4 -1
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/mcp.py +1 -1
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/services.py +72 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/database.py +94 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/model.py +12 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/pyproject.toml +2 -1
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/.gitignore +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/LICENSE +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/README.md +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/attachments.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/auth.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/bootstrap.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/chat_links.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/demo_limits.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/deps.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/erp_context.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/errors.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/list_values.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/llm_provider.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/mcp_oauth.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/mentions.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/menu_layout.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/oauth.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/pdf.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/pdf_contract.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/pdf_exports.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/pdf_fonts.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/pdf_pages.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/pdf_profiles.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/pricing_actions.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/record_attachments.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/record_notes.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/remarks_md.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/accounting.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/actions.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/admin.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/analytics.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/availability.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/bank_statements.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/chat_api.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/masters.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/pdf_templates.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/proposals.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/reports.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/routers/setup.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/stock_actions.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/templates/_proposal_totals.html +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/templates/_record_base.html +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/templates/delivery_note.html +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/templates/document.html +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/templates/proposal.html +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/templates/record.html +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/templates/reservation.html +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/time_filters.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/tool_permissions.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/tool_results.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/api/write_context.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/docs/agents/README.md +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/frontend/LICENSE +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/frontend/README.md +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/frontend/src/api/client.ts +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/bank_account.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/bank_statement_import.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/bank_transaction.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/budget.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/camt.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/chart_of_accounts.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/general_ledger.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/journal_entry.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/payment_entry.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/pos_invoice.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/purchase_invoice.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/revaluation.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/sales_invoice.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/settlement.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/engine.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/pack.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/ch.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/generic.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/profiles.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/spine.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/accounting/subscription.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/addresses.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/assets/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/assets/asset.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/assets/lifecycle.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/assets/reservation.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/backlog.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/bundles.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/buying/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/buying/purchase_order.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/controllers/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/controllers/currency.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/controllers/defaults.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/controllers/item_price.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/controllers/item_prices.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/controllers/price_resolution.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/controllers/pricing_rule.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/controllers/tax_defaults.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/controllers/taxes_and_totals.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/exceptions.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/hooks.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/master_integrity.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/permissions.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/selling/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/selling/proposal.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/selling/quotation.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/selling/sales_order.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/simulation.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/stock/__init__.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/stock/consignment.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/stock/delivery_note.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/stock/purchase_receipt.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/stock/reservation.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/stock/serial.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/stock/stock_count.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/stock/stock_entry.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/stock/stock_ledger.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/timestamps.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/units.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/utils.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/validation.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/lambda_erp/workflow.py +0 -0
- {lambda_erp-1.4.28 → lambda_erp-1.4.30}/terraform/README.md +0 -0
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: lambda-erp
|
|
3
|
-
Version: 1.4.
|
|
3
|
+
Version: 1.4.30
|
|
4
4
|
Summary: Core ERP logic - accounting, sales, purchasing, inventory
|
|
5
5
|
Author: TORUS INVESTMENTS AG
|
|
6
6
|
License-Expression: Apache-2.0
|
|
7
7
|
License-File: LICENSE
|
|
8
8
|
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: av<18,>=16
|
|
9
10
|
Requires-Dist: bcrypt>=5
|
|
10
11
|
Requires-Dist: defusedxml>=0.7
|
|
11
12
|
Requires-Dist: fastapi>=0.115
|
|
@@ -22,6 +22,7 @@ import traceback
|
|
|
22
22
|
import uuid
|
|
23
23
|
from datetime import date
|
|
24
24
|
|
|
25
|
+
import av
|
|
25
26
|
import httpx
|
|
26
27
|
from dotenv import load_dotenv
|
|
27
28
|
from fastapi import APIRouter, Depends as _Depends, HTTPException, WebSocket, WebSocketDisconnect
|
|
@@ -242,6 +243,20 @@ async def drain_turns(timeout: float) -> None:
|
|
|
242
243
|
await asyncio.wait(pending, timeout=timeout)
|
|
243
244
|
|
|
244
245
|
|
|
246
|
+
def delete_empty_session(session_id: str) -> bool:
|
|
247
|
+
# History in the sidebar can be stale when another tab adds content.
|
|
248
|
+
db = get_db()
|
|
249
|
+
with db.atomic():
|
|
250
|
+
cursor = db.conn.execute(
|
|
251
|
+
'''DELETE FROM "Chat Session" WHERE id = ?
|
|
252
|
+
AND (active_turn IS NULL OR active_turn_until IS NULL OR active_turn_until < ?)
|
|
253
|
+
AND NOT EXISTS (SELECT 1 FROM "Chat Message" WHERE session_id = ?)
|
|
254
|
+
AND NOT EXISTS (SELECT 1 FROM "Chat Attachment" WHERE session_id = ?)''',
|
|
255
|
+
[session_id, _utc_iso(), session_id, session_id],
|
|
256
|
+
)
|
|
257
|
+
return cursor.rowcount == 1
|
|
258
|
+
|
|
259
|
+
|
|
245
260
|
def delete_session(session_id: str):
|
|
246
261
|
"""Delete a chat session, its messages, and its attachments."""
|
|
247
262
|
try:
|
|
@@ -365,6 +380,87 @@ def serialize_chat_message(
|
|
|
365
380
|
return msg
|
|
366
381
|
|
|
367
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
|
+
|
|
368
464
|
def load_serialized_chat_history(
|
|
369
465
|
session_id: str,
|
|
370
466
|
limit: int = 20,
|
|
@@ -376,6 +472,11 @@ def load_serialized_chat_history(
|
|
|
376
472
|
messages exist beyond this page.
|
|
377
473
|
"""
|
|
378
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 = {}
|
|
379
480
|
history_messages = []
|
|
380
481
|
for row in rows:
|
|
381
482
|
role = row["role"]
|
|
@@ -391,11 +492,12 @@ def load_serialized_chat_history(
|
|
|
391
492
|
except (json.JSONDecodeError, AttributeError):
|
|
392
493
|
pass
|
|
393
494
|
if content or attachments:
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
role, content, row.get("created_at"), attachments, row.get("id"),
|
|
397
|
-
)
|
|
495
|
+
message = serialize_chat_message(
|
|
496
|
+
role, content, row.get("created_at"), attachments, row.get("id"),
|
|
398
497
|
)
|
|
498
|
+
if row.get("id") in steps_by_answer:
|
|
499
|
+
message["steps"] = steps_by_answer[row["id"]]
|
|
500
|
+
history_messages.append(message)
|
|
399
501
|
|
|
400
502
|
oldest_id = history_messages[0].get("id") if history_messages else None
|
|
401
503
|
has_more = False
|
|
@@ -2934,6 +3036,12 @@ Only state that something was done — created, changed, enabled/disabled, booke
|
|
|
2934
3036
|
- 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.
|
|
2935
3037
|
- If you can't confirm an action took effect, re-fetch and look, or tell the user you couldn't confirm it — never guess.
|
|
2936
3038
|
|
|
3039
|
+
## Document numbers
|
|
3040
|
+
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.
|
|
3041
|
+
|
|
3042
|
+
## Step labels (`step_label`)
|
|
3043
|
+
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.
|
|
3044
|
+
|
|
2937
3045
|
## Answering data questions — three paths
|
|
2938
3046
|
|
|
2939
3047
|
**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.
|
|
@@ -3097,27 +3205,35 @@ Purchase Order → Purchase Receipt (receiving) / Purchase Invoice (billing) →
|
|
|
3097
3205
|
|
|
3098
3206
|
### Items vs. charges on an invoice
|
|
3099
3207
|
|
|
3100
|
-
|
|
3208
|
+
An invoice has **two kinds of lines**:
|
|
3101
3209
|
|
|
3102
|
-
- **Items** (`items[]`):
|
|
3103
|
-
- **Charges** (`taxes[]`):
|
|
3210
|
+
- **Items** (`items[]`): goods or services with an Item master record and a qty × rate shape ("10 × Bolt Pack M8", "1 × Engineering Consultation").
|
|
3211
|
+
- **Charges** (`taxes[]`): rows that point at a GL account directly, with no Item: **freight, shipping, postage, handling, customs, import duties, insurance**, and the actual taxes (VAT, GST, sales tax).
|
|
3104
3212
|
|
|
3105
|
-
|
|
3213
|
+
**Defaults, not prohibitions.** These are the defaults when nobody says otherwise. When the user asks for a charge as a line item ("Versand als normale Position", "the shipping should be a line"), do that: an explicit instruction of the user beats these defaults. Never refuse such a request by pointing to this section.
|
|
3106
3214
|
|
|
3107
|
-
|
|
3108
|
-
- `charge_type`: `"Actual"` for a fixed amount (freight, shipping, handling, customs), `"On Net Total"` for a percentage (most VAT/GST), `"On Previous Row Total"` for a percentage applied on top of earlier charges (EU VAT that includes freight in its base).
|
|
3109
|
-
- `account_head`: the GL account to debit. Use the company's defaults:
|
|
3215
|
+
**Purchase invoices (parsing a supplier's invoice):** by default products go into `items[]` and shipping or customs into `taxes[]` with `charge_type="Actual"`, the amount, and the company's account:
|
|
3110
3216
|
- Freight / shipping / postage → `default_freight_in_account` on the Company record
|
|
3111
3217
|
- Customs / duty / tariff → `default_customs_account`
|
|
3112
|
-
|
|
3113
|
-
|
|
3218
|
+
Do not create a new Item master just for a supplier's "Shipping" or "Customs duty" line.
|
|
3219
|
+
|
|
3220
|
+
**Sales documents (quotation, sales order, sales invoice):** re-billed shipping or handling can be either
|
|
3221
|
+
- a **line item** (common in Switzerland, and what most customers expect to see): use a non-stock service item for it (search for one such as "Versand" first; create it once if none exists, is_stock_item=0). It counts into the net total, VAT applies to it like to any line, and it is booked to that item's income account; or
|
|
3222
|
+
- a **charge row** with `charge_type="Actual"`. Then name an income account for it (ask which, if none is known). Do NOT use `default_freight_in_account` on a sales document: that is the purchase freight expense, and re-billed shipping would then reduce costs instead of showing as revenue. VAT that must include it goes after it as `On Previous Row Total`.
|
|
3223
|
+
If the user does not say which, use the line item for a fixed shipping amount and say so.
|
|
3224
|
+
To turn an existing shipping charge row into a line: add the line with the same amount, remove the charge row, and check that net total, VAT and grand total come out as intended (VAT on the new net total).
|
|
3225
|
+
|
|
3226
|
+
Each charge row has:
|
|
3227
|
+
- `charge_type`: `"Actual"` for a fixed amount, `"On Net Total"` for a percentage (most VAT/GST), `"On Previous Row Total"` for a percentage applied on top of earlier charges (VAT that includes freight in its base).
|
|
3228
|
+
- `account_head`: the GL account (see above for which).
|
|
3229
|
+
- `description`: the label as it should print ("Versand", "Customs duty", "MWST 8.1 %").
|
|
3114
3230
|
- `rate` (for percentage charges) or `tax_amount` (for `Actual` charges).
|
|
3115
3231
|
- `add_deduct_tax`: `"Add"` for most charges; `"Deduct"` for discounts/rebates on the bill.
|
|
3116
3232
|
|
|
3117
|
-
When you parse a supplier invoice PDF that has both products and a shipping line, create ONE Purchase Invoice with the items in `items[]` and the shipping as a row in `taxes[]` with `charge_type="Actual"`, the freight amount, and the freight account. Same structure for customs duties.
|
|
3118
|
-
|
|
3119
3233
|
If multiple charges stack (freight + VAT on total incl. freight), put freight first as `Actual`, then VAT second as `On Previous Row Total` referencing the freight row's `idx`.
|
|
3120
3234
|
|
|
3235
|
+
**The PDF shows the document as stored.** A charge row prints in the totals block, an item line in the item list. Never make a PDF layout print a charge as if it were an item or a numbered position, or print totals the document does not hold: the PDF would then disagree with the books (and the PDF check refuses a layout that leaves out the stored net total). If the user wants the structure changed, change the document, not the layout.
|
|
3236
|
+
|
|
3121
3237
|
### Adding VAT to a SALES document (quotation / sales order / sales invoice)
|
|
3122
3238
|
|
|
3123
3239
|
"Add 8.1% VAT / MwSt" needs exactly ONE `taxes[]` row — do it directly with update_document:
|
|
@@ -3910,6 +4026,49 @@ class _ShimUsage:
|
|
|
3910
4026
|
self.prompt_tokens_details = _ShimUsageDetails(cached_tokens)
|
|
3911
4027
|
|
|
3912
4028
|
|
|
4029
|
+
# An optional one-line label the model gives each tool call ("what this step
|
|
4030
|
+
# does"), shown on the step in the chat and kept with the stored step. Added to
|
|
4031
|
+
# the chat's tool schemas only, and taken out of the arguments before a tool
|
|
4032
|
+
# runs, so no tool ever sees it (several forbid unknown fields).
|
|
4033
|
+
# Not "intent": create_custom_analytics_report has a parameter of that name.
|
|
4034
|
+
INTENT_PARAM = "step_label"
|
|
4035
|
+
INTENT_MAX = 160
|
|
4036
|
+
_INTENT_SCHEMA = {
|
|
4037
|
+
"type": "string",
|
|
4038
|
+
"maxLength": INTENT_MAX,
|
|
4039
|
+
"description": "Optional: what this step does and why, in the user's language, at most ~80 characters "
|
|
4040
|
+
"(shown to the user as the step's label).",
|
|
4041
|
+
}
|
|
4042
|
+
|
|
4043
|
+
|
|
4044
|
+
def _with_intent(tools: list) -> list:
|
|
4045
|
+
"""The tool list with the optional `intent` parameter on every function."""
|
|
4046
|
+
out = []
|
|
4047
|
+
for tool in tools or []:
|
|
4048
|
+
fn = tool.get("function") if isinstance(tool, dict) else None
|
|
4049
|
+
params = fn.get("parameters") if fn else None
|
|
4050
|
+
if not isinstance(params, dict) or params.get("type", "object") != "object":
|
|
4051
|
+
out.append(tool)
|
|
4052
|
+
continue
|
|
4053
|
+
props = params.get("properties") or {}
|
|
4054
|
+
if INTENT_PARAM in props: # a tool's own parameter of that name wins
|
|
4055
|
+
out.append(tool)
|
|
4056
|
+
continue
|
|
4057
|
+
out.append({**tool, "function": {**fn, "parameters": {**params, "properties": {**props, INTENT_PARAM: _INTENT_SCHEMA}}}})
|
|
4058
|
+
return out
|
|
4059
|
+
|
|
4060
|
+
|
|
4061
|
+
def _pop_intent(args) -> str | None:
|
|
4062
|
+
"""Remove the step label from a call's arguments; return it trimmed, or None."""
|
|
4063
|
+
if not isinstance(args, dict):
|
|
4064
|
+
return None
|
|
4065
|
+
value = args.pop(INTENT_PARAM, None)
|
|
4066
|
+
if not isinstance(value, str):
|
|
4067
|
+
return None
|
|
4068
|
+
value = " ".join(value.split())
|
|
4069
|
+
return value[:INTENT_MAX] or None
|
|
4070
|
+
|
|
4071
|
+
|
|
3913
4072
|
def _responses_tools_from_chat(tools: list) -> list:
|
|
3914
4073
|
"""Chat tool schema {"type":"function","function":{name,...}} -> the flatter
|
|
3915
4074
|
Responses shape {"type":"function","name",...}."""
|
|
@@ -4240,7 +4399,7 @@ async def run_thinking_loop(
|
|
|
4240
4399
|
# or the legacy API for compatible models. Returns Chat-shaped
|
|
4241
4400
|
# (message, usage) either way, so everything below is unchanged.
|
|
4242
4401
|
message, usage = await asyncio.to_thread(
|
|
4243
|
-
_orchestrator_turn, openai_client, messages, build_tools(user_info, native_chat=True), max_completion,
|
|
4402
|
+
_orchestrator_turn, openai_client, messages, _with_intent(build_tools(user_info, native_chat=True)), max_completion,
|
|
4244
4403
|
)
|
|
4245
4404
|
except Exception as e:
|
|
4246
4405
|
await on_event({"type": "error", "content": f"Error calling LLM: {e}"})
|
|
@@ -4290,10 +4449,11 @@ async def run_thinking_loop(
|
|
|
4290
4449
|
except json.JSONDecodeError:
|
|
4291
4450
|
fn_args = {}
|
|
4292
4451
|
tool_call_id = tc.id
|
|
4452
|
+
intent = _pop_intent(fn_args)
|
|
4293
4453
|
|
|
4294
|
-
await on_event({"type": "tool_call", "tool": fn_name, "args": fn_args})
|
|
4454
|
+
await on_event({"type": "tool_call", "tool": fn_name, "args": fn_args, "intent": intent})
|
|
4295
4455
|
if session_id:
|
|
4296
|
-
_save_tool_trace(session_id, "tool_call", {"tool": fn_name, "args": fn_args})
|
|
4456
|
+
_save_tool_trace(session_id, "tool_call", {"tool": fn_name, "args": fn_args, "intent": intent})
|
|
4297
4457
|
|
|
4298
4458
|
# LLM turns can run for many seconds. Re-resolve the principal at
|
|
4299
4459
|
# the actual execution boundary so a demotion, disable, or key
|
|
@@ -4448,6 +4608,8 @@ async def run_thinking_loop(
|
|
|
4448
4608
|
# Speech-to-text (voice → text)
|
|
4449
4609
|
# ---------------------------------------------------------------------------
|
|
4450
4610
|
|
|
4611
|
+
TRANSCRIPTION_MODEL = "gpt-transcribe"
|
|
4612
|
+
|
|
4451
4613
|
# Domain-vocabulary biasing for the transcription `prompt`. A bare term list,
|
|
4452
4614
|
# NO language constraint — the spoken language is auto-detected, and a
|
|
4453
4615
|
# locale-derived hint would mis-transcribe users who speak another language
|
|
@@ -4463,31 +4625,50 @@ VOICE_TRANSCRIBE_PROMPT = (
|
|
|
4463
4625
|
|
|
4464
4626
|
# Below this the API rejects the clip as "too short"; we treat it as a no-op
|
|
4465
4627
|
# (the user tapped the mic by accident) rather than an error.
|
|
4466
|
-
_MIN_TRANSCRIBE_BYTES = 1500
|
|
4628
|
+
_MIN_TRANSCRIBE_BYTES = 1500
|
|
4629
|
+
|
|
4467
4630
|
|
|
4631
|
+
def recorded_audio_seconds(file) -> float | None:
|
|
4632
|
+
"""Read a voice clip locally. Streaming WebM may omit the duration header."""
|
|
4633
|
+
try:
|
|
4634
|
+
with av.open(file, mode="r", options={
|
|
4635
|
+
"format_whitelist": "matroska,webm,mov,mp4,m4a,3gp,3g2,mj2,ogg,wav,mp3,flac,aac,mpeg",
|
|
4636
|
+
"protocol_whitelist": "",
|
|
4637
|
+
}) as container:
|
|
4638
|
+
stream = container.streams.audio[0]
|
|
4639
|
+
if stream.duration is not None and stream.duration > 0:
|
|
4640
|
+
return float(stream.duration * stream.time_base)
|
|
4641
|
+
# Count samples when the recorder left the stream length unknown.
|
|
4642
|
+
return sum(frame.samples / frame.sample_rate for frame in container.decode(stream)) or None
|
|
4643
|
+
except (av.FFmpegError, IndexError, ValueError, OSError, ZeroDivisionError):
|
|
4644
|
+
return None
|
|
4468
4645
|
|
|
4469
|
-
def transcribe_audio(audio_bytes: bytes, audio_format: str, erp_user: str | None = None) -> str:
|
|
4470
|
-
"""Transcribe audio to text via OpenAI gpt-4o-transcribe.
|
|
4471
4646
|
|
|
4472
|
-
|
|
4473
|
-
|
|
4474
|
-
Raises on an actual API error so the caller can surface it.
|
|
4475
|
-
"""
|
|
4647
|
+
def transcribe_audio(audio_bytes: bytes, audio_format: str, erp_user: str | None = None) -> tuple[str, float]:
|
|
4648
|
+
"""Return the transcript and the audio seconds to record for this paid call."""
|
|
4476
4649
|
client = OpenAI(**client_kwargs(httpx.Timeout(60.0, connect=10.0), erp_user=erp_user))
|
|
4477
4650
|
|
|
4478
4651
|
audio_file = io.BytesIO(audio_bytes)
|
|
4479
4652
|
audio_file.name = f"voice.{audio_format or 'webm'}"
|
|
4480
4653
|
|
|
4481
4654
|
transcription = client.audio.transcriptions.create(
|
|
4482
|
-
model=
|
|
4655
|
+
model=TRANSCRIPTION_MODEL,
|
|
4483
4656
|
file=audio_file,
|
|
4484
|
-
response_format="json",
|
|
4485
4657
|
prompt=VOICE_TRANSCRIBE_PROMPT,
|
|
4486
4658
|
)
|
|
4487
4659
|
|
|
4660
|
+
seconds = getattr(getattr(transcription, "usage", None), "seconds", None)
|
|
4661
|
+
if seconds is None:
|
|
4662
|
+
seconds = getattr(transcription, "duration", None)
|
|
4663
|
+
if seconds is None:
|
|
4664
|
+
seconds = recorded_audio_seconds(io.BytesIO(audio_bytes))
|
|
4665
|
+
if seconds is None:
|
|
4666
|
+
logger.warning("Using estimated duration for an unreadable %s voice clip", audio_format)
|
|
4667
|
+
seconds = len(audio_bytes) / 2000 # Same legacy fallback as the Lambda gateway.
|
|
4668
|
+
|
|
4488
4669
|
text = (getattr(transcription, "text", "") or "").strip()
|
|
4489
4670
|
if len(text) < 2:
|
|
4490
|
-
return ""
|
|
4671
|
+
return "", seconds
|
|
4491
4672
|
|
|
4492
4673
|
# Prompt-echo guard: on silent/noise audio, prompt-biased transcription
|
|
4493
4674
|
# tends to hallucinate the biasing vocabulary back. If (nearly) every word
|
|
@@ -4498,9 +4679,9 @@ def transcribe_audio(audio_bytes: bytes, audio_format: str, erp_user: str | None
|
|
|
4498
4679
|
if text_tokens:
|
|
4499
4680
|
coverage = sum(1 for tok in text_tokens if tok in prompt_tokens) / len(text_tokens)
|
|
4500
4681
|
if coverage >= 0.8:
|
|
4501
|
-
return ""
|
|
4682
|
+
return "", seconds
|
|
4502
4683
|
|
|
4503
|
-
return text
|
|
4684
|
+
return text, seconds
|
|
4504
4685
|
|
|
4505
4686
|
|
|
4506
4687
|
# ---------------------------------------------------------------------------
|
|
@@ -4844,7 +5025,7 @@ async def chat_websocket(
|
|
|
4844
5025
|
)
|
|
4845
5026
|
continue
|
|
4846
5027
|
|
|
4847
|
-
if msg_type
|
|
5028
|
+
if msg_type in ("delete_empty_session", "delete_session"):
|
|
4848
5029
|
session_id = data.get("session_id")
|
|
4849
5030
|
if not session_id:
|
|
4850
5031
|
await send_error("No session_id provided", request_id=request_id)
|
|
@@ -4863,8 +5044,12 @@ async def chat_websocket(
|
|
|
4863
5044
|
)
|
|
4864
5045
|
continue
|
|
4865
5046
|
|
|
4866
|
-
|
|
4867
|
-
|
|
5047
|
+
if msg_type == "delete_empty_session":
|
|
5048
|
+
deleted = delete_empty_session(session_id)
|
|
5049
|
+
await send_event("empty_session_delete_result", request_id=request_id, session_id=session_id, deleted=deleted)
|
|
5050
|
+
else:
|
|
5051
|
+
delete_session(session_id)
|
|
5052
|
+
await send_event("session_deleted", request_id=request_id, session_id=session_id)
|
|
4868
5053
|
continue
|
|
4869
5054
|
|
|
4870
5055
|
if msg_type == "clear_history":
|
|
@@ -5005,7 +5190,7 @@ async def chat_websocket(
|
|
|
5005
5190
|
continue
|
|
5006
5191
|
|
|
5007
5192
|
try:
|
|
5008
|
-
text = await asyncio.to_thread(
|
|
5193
|
+
text, audio_seconds = await asyncio.to_thread(
|
|
5009
5194
|
transcribe_audio, audio_bytes, audio_format, ws_user_id,
|
|
5010
5195
|
)
|
|
5011
5196
|
except Exception as e:
|
|
@@ -5016,17 +5201,12 @@ async def chat_websocket(
|
|
|
5016
5201
|
)
|
|
5017
5202
|
continue
|
|
5018
5203
|
|
|
5019
|
-
# Track the spend. Audio duration is estimated from byte size
|
|
5020
|
-
# (~1.5 KB/s for webm/opus); the Demo Spend Log records every
|
|
5021
|
-
# role for the admin dashboard, and counts public_manager rows
|
|
5022
|
-
# against the hourly cap.
|
|
5023
|
-
estimated_seconds = len(audio_bytes) / 1500
|
|
5024
5204
|
demo_limiter.record(
|
|
5025
5205
|
client_ip or "unknown",
|
|
5026
|
-
cost_of_transcription(
|
|
5206
|
+
cost_of_transcription(TRANSCRIPTION_MODEL, audio_seconds),
|
|
5027
5207
|
role=ws_user_role,
|
|
5028
5208
|
provider="openai",
|
|
5029
|
-
model=
|
|
5209
|
+
model=TRANSCRIPTION_MODEL,
|
|
5030
5210
|
session_id=data.get("session_id"),
|
|
5031
5211
|
)
|
|
5032
5212
|
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Personal list columns of the document lists, readable and changeable from the chat.
|
|
2
|
+
|
|
3
|
+
The web app keeps each user's columns of a document list as the preference
|
|
4
|
+
`columns.<doctype slug>` (comma-separated, in display order) and the sort
|
|
5
|
+
order as `sort.<doctype slug>` (`column:asc|desc`). The column menu of a list
|
|
6
|
+
writes them; these actions let the assistant do the same for the signed-in
|
|
7
|
+
user, and only for them. Since 1.4.29.
|
|
8
|
+
|
|
9
|
+
Columns a list can show: `name`, the document's own columns the user may see,
|
|
10
|
+
the readable name of a linked record (`<link field>__title`, see
|
|
11
|
+
services.linked_title_fields) and, where the document type prints, the PDF link
|
|
12
|
+
`__pdf`. Unset, a list shows the app's default columns.
|
|
13
|
+
"""
|
|
14
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
15
|
+
|
|
16
|
+
from api import services
|
|
17
|
+
from api.menu_layout import _actor
|
|
18
|
+
from lambda_erp import permissions
|
|
19
|
+
from lambda_erp.database import get_db
|
|
20
|
+
|
|
21
|
+
PDF_COLUMN = "__pdf"
|
|
22
|
+
# Bookkeeping columns no list shows.
|
|
23
|
+
_NOT_SHOWN = {"docstatus", "discarded", "idx", "content_hash", "access_stamp"}
|
|
24
|
+
MAX_COLUMNS = 20
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class GetColumns(BaseModel):
|
|
28
|
+
model_config = ConfigDict(extra="forbid")
|
|
29
|
+
doctype: str = Field(min_length=1, max_length=100, description="Document type slug, e.g. sales-invoice")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class UpdateColumns(BaseModel):
|
|
33
|
+
model_config = ConfigDict(extra="forbid")
|
|
34
|
+
doctype: str = Field(min_length=1, max_length=100, description="Document type slug, e.g. sales-invoice")
|
|
35
|
+
columns: list[str] | None = Field(
|
|
36
|
+
default=None, max_length=MAX_COLUMNS,
|
|
37
|
+
description="All columns of the list in display order (replaces the current set). Use the names "
|
|
38
|
+
"from get_list_columns; `name` is always shown first if left out.")
|
|
39
|
+
add: list[str] = Field(default_factory=list, max_length=MAX_COLUMNS,
|
|
40
|
+
description="Columns to append to the current set.")
|
|
41
|
+
remove: list[str] = Field(default_factory=list, max_length=MAX_COLUMNS,
|
|
42
|
+
description="Columns to take out of the current set.")
|
|
43
|
+
sort_by: str | None = Field(default=None, max_length=100,
|
|
44
|
+
description="Column to sort the list by (a stored column, not a looked-up name or the PDF link).")
|
|
45
|
+
sort_order: str | None = Field(default=None, pattern="^(asc|desc)$")
|
|
46
|
+
reset: bool = Field(default=False, description="Back to the app's default columns and sort order.")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _doctype(slug):
|
|
50
|
+
doctype = services.SLUG_TO_DOCTYPE.get(slug)
|
|
51
|
+
if not doctype:
|
|
52
|
+
raise ValueError(f"Unknown document type {slug!r}; use a slug such as sales-invoice.")
|
|
53
|
+
permissions.require(doctype, "read")
|
|
54
|
+
return doctype
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _catalog(slug, doctype):
|
|
58
|
+
"""{column: what it is} for the columns this user's list of `slug` can show."""
|
|
59
|
+
db = get_db()
|
|
60
|
+
hidden = permissions.hidden_fields(doctype)
|
|
61
|
+
columns = sorted(db._get_table_columns(doctype) - hidden - _NOT_SHOWN)
|
|
62
|
+
catalog = {"name": "the document's id"}
|
|
63
|
+
catalog.update({column: "a column of the document" for column in columns if column != "name"})
|
|
64
|
+
cls = services.DOCUMENT_CLASSES.get(doctype)
|
|
65
|
+
for field in sorted(getattr(cls, "LINK_FIELDS", {}) or {}):
|
|
66
|
+
title = f"{field}{services.TITLE_SUFFIX}"
|
|
67
|
+
if field in catalog and services.linked_title_fields(doctype, [title]):
|
|
68
|
+
catalog[title] = f"the name of the linked {cls.LINK_FIELDS[field]} (looked up, not sortable)"
|
|
69
|
+
try:
|
|
70
|
+
from api.pdf_profiles import pdf_metadata
|
|
71
|
+
if (pdf_metadata(doctype) or {}).get("supported"):
|
|
72
|
+
catalog[PDF_COLUMN] = "a link that opens the document's PDF (not sortable)"
|
|
73
|
+
except Exception: # noqa: BLE001 - no PDF column rather than no columns
|
|
74
|
+
pass
|
|
75
|
+
return catalog
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _read(user_name, key):
|
|
79
|
+
rows = get_db().sql('SELECT value FROM "User Preference" WHERE user_name = ? AND key = ?', [user_name, key])
|
|
80
|
+
return rows[0]["value"] if rows else ""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _write(user_name, key, value):
|
|
84
|
+
db = get_db()
|
|
85
|
+
with db.atomic():
|
|
86
|
+
if db.sql('SELECT 1 FROM "User Preference" WHERE user_name = ? AND key = ?', [user_name, key]):
|
|
87
|
+
if value:
|
|
88
|
+
db.sql('UPDATE "User Preference" SET value = ? WHERE user_name = ? AND key = ?', [value, user_name, key])
|
|
89
|
+
else:
|
|
90
|
+
db.sql('DELETE FROM "User Preference" WHERE user_name = ? AND key = ?', [user_name, key])
|
|
91
|
+
elif value:
|
|
92
|
+
db.sql('INSERT INTO "User Preference" (user_name, key, value) VALUES (?, ?, ?)', [user_name, key, value])
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _state(user_name, slug, catalog):
|
|
96
|
+
saved = [column.strip() for column in _read(user_name, f"columns.{slug}").split(",") if column.strip()]
|
|
97
|
+
sort = _read(user_name, f"sort.{slug}")
|
|
98
|
+
by, _, order = sort.partition(":")
|
|
99
|
+
return {
|
|
100
|
+
"doctype": slug,
|
|
101
|
+
"columns": saved or None,
|
|
102
|
+
"columns_note": None if saved else "Not set: the list shows the app's default columns.",
|
|
103
|
+
"sort_by": by or None,
|
|
104
|
+
"sort_order": order or None,
|
|
105
|
+
"available": catalog,
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def get_list_columns(args, user):
|
|
110
|
+
data = GetColumns.model_validate(args)
|
|
111
|
+
user_name, doctype = _actor(user), _doctype(data.doctype)
|
|
112
|
+
return _state(user_name, data.doctype, _catalog(data.doctype, doctype))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def update_list_columns(args, user):
|
|
116
|
+
data = UpdateColumns.model_validate(args)
|
|
117
|
+
user_name, doctype = _actor(user), _doctype(data.doctype)
|
|
118
|
+
catalog = _catalog(data.doctype, doctype)
|
|
119
|
+
slug = data.doctype
|
|
120
|
+
|
|
121
|
+
def check(names):
|
|
122
|
+
unknown = [name for name in names if name not in catalog]
|
|
123
|
+
if unknown:
|
|
124
|
+
raise ValueError(f"Unknown column(s) for {slug}: {', '.join(unknown)}. "
|
|
125
|
+
"Call get_list_columns for the columns this list can show.")
|
|
126
|
+
return names
|
|
127
|
+
|
|
128
|
+
if data.reset:
|
|
129
|
+
_write(user_name, f"columns.{slug}", "")
|
|
130
|
+
_write(user_name, f"sort.{slug}", "")
|
|
131
|
+
current = [c.strip() for c in _read(user_name, f"columns.{slug}").split(",") if c.strip()]
|
|
132
|
+
if data.columns is not None:
|
|
133
|
+
columns = check(list(dict.fromkeys(data.columns)))
|
|
134
|
+
elif data.add or data.remove:
|
|
135
|
+
if not current:
|
|
136
|
+
raise ValueError(f"The {slug} list shows its default columns, which are set by the app. "
|
|
137
|
+
"Send the whole set with columns=[...] (see get_list_columns) instead of add/remove.")
|
|
138
|
+
columns = [c for c in current if c not in set(check(data.remove))] + \
|
|
139
|
+
[c for c in check(data.add) if c not in current]
|
|
140
|
+
else:
|
|
141
|
+
columns = None
|
|
142
|
+
if columns is not None:
|
|
143
|
+
if not columns:
|
|
144
|
+
raise ValueError("A list needs at least one column.")
|
|
145
|
+
if "name" not in columns:
|
|
146
|
+
columns = ["name", *columns]
|
|
147
|
+
_write(user_name, f"columns.{slug}", ",".join(columns[:MAX_COLUMNS]))
|
|
148
|
+
if data.sort_by is not None or data.sort_order is not None:
|
|
149
|
+
by = data.sort_by or (_read(user_name, f"sort.{slug}").partition(":")[0] or None)
|
|
150
|
+
if not by:
|
|
151
|
+
raise ValueError("sort_order needs sort_by.")
|
|
152
|
+
if by not in catalog or by == PDF_COLUMN or by.endswith(services.TITLE_SUFFIX):
|
|
153
|
+
raise ValueError(f"{by!r} cannot be sorted by; use a stored column of the document.")
|
|
154
|
+
_write(user_name, f"sort.{slug}", f"{by}:{data.sort_order or 'asc'}")
|
|
155
|
+
result = _state(user_name, slug, catalog)
|
|
156
|
+
result["note"] = "Saved for the signed-in user only. The list shows it on its next load."
|
|
157
|
+
return result
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def initialize_list_columns():
|
|
161
|
+
services.register_action(
|
|
162
|
+
"get_list_columns", get_list_columns, minimum_role="viewer", pass_user=True,
|
|
163
|
+
parameters=GetColumns.model_json_schema(),
|
|
164
|
+
description=(
|
|
165
|
+
"Show the current user's own columns and sort order of a document list (e.g. doctype "
|
|
166
|
+
"'sales-invoice') and the columns that list can show: the document's columns, the names of "
|
|
167
|
+
"linked records (customer__title, item_code__title) and __pdf, a link to each document's "
|
|
168
|
+
"PDF. Call this before update_list_columns."))
|
|
169
|
+
services.register_action(
|
|
170
|
+
"update_list_columns", update_list_columns, minimum_role="viewer", pass_user=True,
|
|
171
|
+
parameters=UpdateColumns.model_json_schema(),
|
|
172
|
+
description=(
|
|
173
|
+
"Change which columns the current user's own list of a document type shows, their order, "
|
|
174
|
+
"and the sort order (no one else's). columns replaces the whole set in display order; "
|
|
175
|
+
"add / remove change the current set; reset=true restores the app's defaults. Use column "
|
|
176
|
+
"names from get_list_columns: e.g. customer_name for the customer's name stored on a sales "
|
|
177
|
+
"invoice, item_code__title for an item's name, __pdf for a PDF link. Only stored columns "
|
|
178
|
+
"can be sorted by. It changes the display only, never data or permissions."))
|
|
@@ -74,6 +74,10 @@ async def lifespan(app: FastAPI):
|
|
|
74
74
|
initialize_pricing_actions()
|
|
75
75
|
from api.menu_layout import initialize_menu_layout
|
|
76
76
|
initialize_menu_layout()
|
|
77
|
+
from api.list_columns import initialize_list_columns
|
|
78
|
+
initialize_list_columns()
|
|
79
|
+
from api.number_series import initialize_number_series
|
|
80
|
+
initialize_number_series()
|
|
77
81
|
from api.pdf_templates import initialize_pdf_templates
|
|
78
82
|
initialize_pdf_templates()
|
|
79
83
|
from api.pdf_pages import initialize_pdf_pages
|