lambda-erp 1.4.29__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.
Files changed (142) hide show
  1. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/PKG-INFO +1 -1
  2. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/chat.py +144 -7
  3. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/main.py +2 -0
  4. lambda_erp-1.4.30/api/number_series.py +106 -0
  5. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/mcp.py +1 -1
  6. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/database.py +94 -0
  7. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/model.py +12 -0
  8. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/pyproject.toml +1 -1
  9. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/.gitignore +0 -0
  10. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/LICENSE +0 -0
  11. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/README.md +0 -0
  12. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/__init__.py +0 -0
  13. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/attachments.py +0 -0
  14. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/auth.py +0 -0
  15. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/bootstrap.py +0 -0
  16. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/chat_links.py +0 -0
  17. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/demo_limits.py +0 -0
  18. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/deps.py +0 -0
  19. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/erp_context.py +0 -0
  20. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/errors.py +0 -0
  21. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/list_columns.py +0 -0
  22. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/list_values.py +0 -0
  23. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/llm_provider.py +0 -0
  24. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/mcp_oauth.py +0 -0
  25. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/mentions.py +0 -0
  26. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/menu_layout.py +0 -0
  27. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/oauth.py +0 -0
  28. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/pdf.py +0 -0
  29. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/pdf_contract.py +0 -0
  30. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/pdf_exports.py +0 -0
  31. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/pdf_fonts.py +0 -0
  32. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/pdf_pages.py +0 -0
  33. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/pdf_profiles.py +0 -0
  34. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/pdf_templates.py +0 -0
  35. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/pricing_actions.py +0 -0
  36. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/providers.py +0 -0
  37. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/record_attachments.py +0 -0
  38. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/record_notes.py +0 -0
  39. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/remarks_md.py +0 -0
  40. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/__init__.py +0 -0
  41. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/accounting.py +0 -0
  42. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/actions.py +0 -0
  43. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/admin.py +0 -0
  44. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/analytics.py +0 -0
  45. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/availability.py +0 -0
  46. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/bank_reconciliation.py +0 -0
  47. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/bank_statements.py +0 -0
  48. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/chat_api.py +0 -0
  49. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/documents.py +0 -0
  50. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/masters.py +0 -0
  51. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/pdf_templates.py +0 -0
  52. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/proposals.py +0 -0
  53. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/reports.py +0 -0
  54. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/routers/setup.py +0 -0
  55. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/services.py +0 -0
  56. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/stock_actions.py +0 -0
  57. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/templates/_proposal_totals.html +0 -0
  58. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/templates/_record_base.html +0 -0
  59. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/templates/delivery_note.html +0 -0
  60. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/templates/document.html +0 -0
  61. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/templates/proposal.html +0 -0
  62. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/templates/record.html +0 -0
  63. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/templates/reservation.html +0 -0
  64. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/time_filters.py +0 -0
  65. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/tool_permissions.py +0 -0
  66. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/tool_results.py +0 -0
  67. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/api/write_context.py +0 -0
  68. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/docs/agents/README.md +0 -0
  69. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/frontend/LICENSE +0 -0
  70. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/frontend/README.md +0 -0
  71. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/frontend/src/api/client.ts +0 -0
  72. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/__init__.py +0 -0
  73. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/__init__.py +0 -0
  74. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/bank_account.py +0 -0
  75. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/bank_reconciliation.py +0 -0
  76. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/bank_statement_import.py +0 -0
  77. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/bank_transaction.py +0 -0
  78. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/budget.py +0 -0
  79. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/camt.py +0 -0
  80. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/chart_of_accounts.py +0 -0
  81. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/general_ledger.py +0 -0
  82. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/journal_entry.py +0 -0
  83. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/payment_entry.py +0 -0
  84. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/pos_invoice.py +0 -0
  85. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/purchase_invoice.py +0 -0
  86. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/revaluation.py +0 -0
  87. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/sales_invoice.py +0 -0
  88. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/settlement.py +0 -0
  89. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/__init__.py +0 -0
  90. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/engine.py +0 -0
  91. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/pack.py +0 -0
  92. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
  93. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/ch.py +0 -0
  94. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
  95. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
  96. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
  97. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/packs/generic.py +0 -0
  98. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/profiles.py +0 -0
  99. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/setup/spine.py +0 -0
  100. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/accounting/subscription.py +0 -0
  101. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/addresses.py +0 -0
  102. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/assets/__init__.py +0 -0
  103. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/assets/asset.py +0 -0
  104. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/assets/lifecycle.py +0 -0
  105. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/assets/reservation.py +0 -0
  106. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/backlog.py +0 -0
  107. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/bundles.py +0 -0
  108. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/buying/__init__.py +0 -0
  109. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/buying/purchase_order.py +0 -0
  110. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/controllers/__init__.py +0 -0
  111. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/controllers/currency.py +0 -0
  112. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/controllers/defaults.py +0 -0
  113. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/controllers/item_price.py +0 -0
  114. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/controllers/item_prices.py +0 -0
  115. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/controllers/price_resolution.py +0 -0
  116. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/controllers/pricing_rule.py +0 -0
  117. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/controllers/tax_defaults.py +0 -0
  118. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/controllers/taxes_and_totals.py +0 -0
  119. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/exceptions.py +0 -0
  120. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/hooks.py +0 -0
  121. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/master_integrity.py +0 -0
  122. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/permissions.py +0 -0
  123. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/selling/__init__.py +0 -0
  124. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/selling/proposal.py +0 -0
  125. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/selling/quotation.py +0 -0
  126. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/selling/sales_order.py +0 -0
  127. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/simulation.py +0 -0
  128. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/stock/__init__.py +0 -0
  129. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/stock/consignment.py +0 -0
  130. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/stock/delivery_note.py +0 -0
  131. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/stock/purchase_receipt.py +0 -0
  132. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/stock/reservation.py +0 -0
  133. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/stock/serial.py +0 -0
  134. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/stock/stock_count.py +0 -0
  135. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/stock/stock_entry.py +0 -0
  136. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/stock/stock_ledger.py +0 -0
  137. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/timestamps.py +0 -0
  138. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/units.py +0 -0
  139. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/utils.py +0 -0
  140. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/validation.py +0 -0
  141. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/lambda_erp/workflow.py +0 -0
  142. {lambda_erp-1.4.29 → lambda_erp-1.4.30}/terraform/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.29
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
@@ -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
- history_messages.append(
410
- serialize_chat_message(
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
@@ -2949,6 +3036,12 @@ Only state that something was done — created, changed, enabled/disabled, booke
2949
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.
2950
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.
2951
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
+
2952
3045
  ## Answering data questions — three paths
2953
3046
 
2954
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.
@@ -3933,6 +4026,49 @@ class _ShimUsage:
3933
4026
  self.prompt_tokens_details = _ShimUsageDetails(cached_tokens)
3934
4027
 
3935
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
+
3936
4072
  def _responses_tools_from_chat(tools: list) -> list:
3937
4073
  """Chat tool schema {"type":"function","function":{name,...}} -> the flatter
3938
4074
  Responses shape {"type":"function","name",...}."""
@@ -4263,7 +4399,7 @@ async def run_thinking_loop(
4263
4399
  # or the legacy API for compatible models. Returns Chat-shaped
4264
4400
  # (message, usage) either way, so everything below is unchanged.
4265
4401
  message, usage = await asyncio.to_thread(
4266
- _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,
4267
4403
  )
4268
4404
  except Exception as e:
4269
4405
  await on_event({"type": "error", "content": f"Error calling LLM: {e}"})
@@ -4313,10 +4449,11 @@ async def run_thinking_loop(
4313
4449
  except json.JSONDecodeError:
4314
4450
  fn_args = {}
4315
4451
  tool_call_id = tc.id
4452
+ intent = _pop_intent(fn_args)
4316
4453
 
4317
- 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})
4318
4455
  if session_id:
4319
- _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})
4320
4457
 
4321
4458
  # LLM turns can run for many seconds. Re-resolve the principal at
4322
4459
  # the actual execution boundary so a demotion, disable, or key
@@ -76,6 +76,8 @@ async def lifespan(app: FastAPI):
76
76
  initialize_menu_layout()
77
77
  from api.list_columns import initialize_list_columns
78
78
  initialize_list_columns()
79
+ from api.number_series import initialize_number_series
80
+ initialize_number_series()
79
81
  from api.pdf_templates import initialize_pdf_templates
80
82
  initialize_pdf_templates()
81
83
  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."))
@@ -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',
@@ -2409,6 +2409,100 @@ class Database:
2409
2409
  if attempt == 2:
2410
2410
  raise
2411
2411
 
2412
+ # --- Setting a series (admins) and following hand-set numbers ---------
2413
+
2414
+ def _series_pg(self, work):
2415
+ """Run `work(conn)` on the autocommit series connection (as
2416
+ next_in_series does), reconnecting once after a dropped connection."""
2417
+ import psycopg
2418
+
2419
+ with self._series_lock:
2420
+ for attempt in (1, 2):
2421
+ try:
2422
+ conn = self._series_conn
2423
+ if conn is None or conn.closed:
2424
+ conn = self._series_conn = psycopg.connect(self.db_path, autocommit=True)
2425
+ return work(conn)
2426
+ except psycopg.OperationalError:
2427
+ if self._series_conn is not None:
2428
+ try:
2429
+ self._series_conn.close()
2430
+ except Exception:
2431
+ pass
2432
+ self._series_conn = None
2433
+ if attempt == 2:
2434
+ raise
2435
+
2436
+ def _series_fetch(self):
2437
+ if self.dialect == "postgres":
2438
+ return lambda sql, params: [list(r.values()) for r in self.sql(sql, params)]
2439
+ return lambda sql, params: self.conn.execute(sql, params).fetchall()
2440
+
2441
+ def series_state(self, prefix: str) -> dict:
2442
+ """{prefix, current, highest_used}: `current` is the last number handed
2443
+ out (the next is current + 1), `highest_used` the highest
2444
+ "PREFIX-<digits>" stored anywhere. A series never used yet starts after
2445
+ the highest stored number, as next_in_series would seed it."""
2446
+ highest = self._series_floor(prefix, self._series_fetch())
2447
+ rows = self.sql('SELECT current FROM "_NamingSeries" WHERE prefix = ?', [prefix])
2448
+ current = int(rows[0]["current"]) if rows else highest
2449
+ return {"prefix": prefix, "current": current, "highest_used": highest}
2450
+
2451
+ def set_series_next(self, prefix: str, next_number: int) -> dict:
2452
+ """Make `next_number` the next number of the series.
2453
+
2454
+ It may not be at or below a number already used, so a series can be
2455
+ moved up freely and back down only as far as the highest stored number:
2456
+ never to a number that would collide.
2457
+ """
2458
+ next_number = int(next_number)
2459
+ highest = self._series_floor(prefix, self._series_fetch())
2460
+ if next_number <= highest:
2461
+ raise ValueError(f"{prefix}-{highest:04d} is already used: the next number must be at least {highest + 1}.")
2462
+ current = next_number - 1
2463
+ if self.dialect == "postgres":
2464
+ self._series_pg(lambda conn: conn.execute(
2465
+ 'INSERT INTO "_NamingSeries" (prefix, current) VALUES (%s, %s) '
2466
+ 'ON CONFLICT (prefix) DO UPDATE SET current = EXCLUDED.current', [prefix, current]))
2467
+ else:
2468
+ with self._lock:
2469
+ conn = self.conn
2470
+ if conn.execute('UPDATE "_NamingSeries" SET current = ? WHERE prefix = ?',
2471
+ [current, prefix]).rowcount == 0:
2472
+ conn.execute('INSERT INTO "_NamingSeries" (prefix, current) VALUES (?, ?)', [prefix, current])
2473
+ if not self._in_transaction:
2474
+ conn.commit()
2475
+ return self.series_state(prefix)
2476
+
2477
+ def advance_series(self, prefix: str, number: int) -> None:
2478
+ """Move the series past `number` if it is behind: a record saved with a
2479
+ hand-set "PREFIX-<number>" means the next automatic one follows it,
2480
+ instead of the series climbing up to it and skipping it later."""
2481
+ number = int(number)
2482
+ if self.dialect == "postgres":
2483
+ def work(conn):
2484
+ updated = conn.execute(
2485
+ 'UPDATE "_NamingSeries" SET current = GREATEST(current, %s) WHERE prefix = %s',
2486
+ [number, prefix]).rowcount
2487
+ if not updated:
2488
+ floor = self._series_floor(
2489
+ prefix, lambda sql, params: conn.execute(sql.replace("?", "%s"), params).fetchall())
2490
+ conn.execute(
2491
+ 'INSERT INTO "_NamingSeries" (prefix, current) VALUES (%s, %s) '
2492
+ 'ON CONFLICT (prefix) DO UPDATE SET current = '
2493
+ 'GREATEST("_NamingSeries".current, EXCLUDED.current)', [prefix, max(floor, number)])
2494
+ self._series_pg(work)
2495
+ return
2496
+ with self._lock:
2497
+ conn = self.conn
2498
+ if conn.execute('UPDATE "_NamingSeries" SET current = MAX(current, ?) WHERE prefix = ?',
2499
+ [number, prefix]).rowcount == 0:
2500
+ floor = self._series_floor(prefix, lambda sql, params: conn.execute(sql, params).fetchall())
2501
+ conn.execute('INSERT INTO "_NamingSeries" (prefix, current) VALUES (?, ?)',
2502
+ [prefix, max(floor, number)])
2503
+ if not self._in_transaction:
2504
+ conn.commit()
2505
+
2412
2506
  def _series_floor(self, prefix: str, fetch) -> int:
2413
2507
  """Highest number already used as "PREFIX-<digits>" in any table.
2414
2508
 
@@ -364,8 +364,20 @@ class Document:
364
364
  except Exception:
365
365
  self._persisted, self._loaded_modified = persisted
366
366
  raise
367
+ if not persisted[0]:
368
+ self._follow_hand_set_name()
367
369
  return self
368
370
 
371
+ def _follow_hand_set_name(self):
372
+ """A new record saved as "PREFIX-<n>" with a number the series has not
373
+ reached yet moves the series past it: SINV-0321 entered by hand makes
374
+ the next automatic invoice SINV-0322, not SINV-0006 (which would later
375
+ climb to 0320 and skip 0321)."""
376
+ import re
377
+ match = re.fullmatch(rf"{re.escape(self.PREFIX)}-(\d+)", str(self.name or ""))
378
+ if match and self.PREFIX:
379
+ get_db().advance_series(self.PREFIX, int(match.group(1)))
380
+
369
381
  def _require_in_scope(self):
370
382
  """A user restricted to assigned customers or warehouses cannot write
371
383
  a document outside of them, by whatever path it is written."""
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "lambda-erp"
3
- version = "1.4.29"
3
+ version = "1.4.30"
4
4
  description = "Core ERP logic - accounting, sales, purchasing, inventory"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes