lambda-erp 1.4.18__tar.gz → 1.4.20__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.18 → lambda_erp-1.4.20}/PKG-INFO +1 -1
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/chat.py +23 -2
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/main.py +4 -0
- lambda_erp-1.4.20/api/record_attachments.py +303 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/record_notes.py +9 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/masters.py +2 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/services.py +9 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/frontend/src/api/client.ts +33 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/revaluation.py +6 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/database.py +36 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/model.py +2 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/permissions.py +38 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/validation.py +28 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/pyproject.toml +1 -1
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/.gitignore +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/LICENSE +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/README.md +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/attachments.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/auth.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/bootstrap.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/chat_links.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/demo_limits.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/deps.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/erp_context.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/errors.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/list_values.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/llm_provider.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/mcp_oauth.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/mentions.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/menu_layout.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/oauth.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/pdf.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/pdf_contract.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/pdf_exports.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/pdf_fonts.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/pdf_pages.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/pdf_profiles.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/pdf_templates.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/pricing_actions.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/providers.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/remarks_md.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/accounting.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/actions.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/admin.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/analytics.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/availability.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/bank_statements.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/chat_api.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/documents.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/mcp.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/pdf_templates.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/proposals.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/reports.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/routers/setup.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/stock_actions.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/templates/_proposal_totals.html +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/templates/_record_base.html +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/templates/delivery_note.html +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/templates/document.html +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/templates/proposal.html +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/templates/record.html +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/templates/reservation.html +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/time_filters.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/tool_permissions.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/api/write_context.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/docs/agents/README.md +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/frontend/LICENSE +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/frontend/README.md +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/bank_account.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/bank_statement_import.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/bank_transaction.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/budget.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/camt.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/chart_of_accounts.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/general_ledger.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/journal_entry.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/payment_entry.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/pos_invoice.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/purchase_invoice.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/sales_invoice.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/settlement.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/engine.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/pack.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/packs/ch.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/packs/generic.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/profiles.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/setup/spine.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/accounting/subscription.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/addresses.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/assets/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/assets/asset.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/assets/lifecycle.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/assets/reservation.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/backlog.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/bundles.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/buying/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/buying/purchase_order.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/controllers/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/controllers/currency.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/controllers/defaults.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/controllers/item_price.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/controllers/item_prices.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/controllers/price_resolution.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/controllers/pricing_rule.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/controllers/taxes_and_totals.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/exceptions.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/hooks.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/master_integrity.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/selling/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/selling/proposal.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/selling/quotation.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/selling/sales_order.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/simulation.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/stock/__init__.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/stock/consignment.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/stock/delivery_note.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/stock/purchase_receipt.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/stock/reservation.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/stock/serial.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/stock/stock_count.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/stock/stock_entry.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/stock/stock_ledger.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/timestamps.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/utils.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/lambda_erp/workflow.py +0 -0
- {lambda_erp-1.4.18 → lambda_erp-1.4.20}/terraform/README.md +0 -0
|
@@ -1960,6 +1960,10 @@ def _handle_get_current_time(args):
|
|
|
1960
1960
|
|
|
1961
1961
|
|
|
1962
1962
|
def _handle_retrieve_chat_history(args, session_id=None):
|
|
1963
|
+
# Only ever the conversation the caller is in; without one there is
|
|
1964
|
+
# nothing to retrieve (and never other people's conversations).
|
|
1965
|
+
if not session_id:
|
|
1966
|
+
return {"error": "retrieve_chat_history is only available inside a chat conversation."}
|
|
1963
1967
|
db = get_db()
|
|
1964
1968
|
date_from = args.get("date_from")
|
|
1965
1969
|
date_to = args.get("date_to")
|
|
@@ -2582,13 +2586,25 @@ def _prompt_company_context() -> str:
|
|
|
2582
2586
|
)
|
|
2583
2587
|
|
|
2584
2588
|
|
|
2585
|
-
def _prompt_analytics_context() -> str:
|
|
2589
|
+
def _prompt_analytics_context(user_info: dict | None = None) -> str:
|
|
2586
2590
|
db = get_db()
|
|
2587
2591
|
datasets = [
|
|
2588
2592
|
("sales invoices", "Sales Invoice", "posting_date", "docstatus = 1"),
|
|
2589
2593
|
("purchase invoices", "Purchase Invoice", "posting_date", "docstatus = 1"),
|
|
2590
2594
|
("payments", "Payment Entry", "posting_date", "docstatus = 1"),
|
|
2591
2595
|
]
|
|
2596
|
+
# The prompt is data that reaches the model: a restricted user gets no
|
|
2597
|
+
# counts or date ranges of what their access profile or record scope hides.
|
|
2598
|
+
from lambda_erp import permissions
|
|
2599
|
+
restrictions = (user_info or {}).get("restrictions")
|
|
2600
|
+
if restrictions:
|
|
2601
|
+
if restrictions.get("scope"):
|
|
2602
|
+
datasets = []
|
|
2603
|
+
else:
|
|
2604
|
+
names = {"Sales Invoice": "sales_invoices", "Purchase Invoice": "purchase_invoices", "Payment Entry": "payments"}
|
|
2605
|
+
with permissions.acting_as(user_info):
|
|
2606
|
+
datasets = [entry for entry in datasets
|
|
2607
|
+
if permissions.can(entry[1], "read") and not permissions.artifact_denied("dataset", names[entry[1]])]
|
|
2592
2608
|
lines: list[str] = []
|
|
2593
2609
|
for label, table, date_field, where in datasets:
|
|
2594
2610
|
try:
|
|
@@ -2667,7 +2683,7 @@ def build_system_prompt(user_info: dict | None = None, channel: str = "web"):
|
|
|
2667
2683
|
user_name = user_info.get("full_name", "User") if user_info else "User"
|
|
2668
2684
|
user_role = user_info.get("role", "viewer") if user_info else "viewer"
|
|
2669
2685
|
company_context = _prompt_company_context()
|
|
2670
|
-
analytics_context = _prompt_analytics_context()
|
|
2686
|
+
analytics_context = _prompt_analytics_context(user_info)
|
|
2671
2687
|
uom_context = _prompt_uom_context()
|
|
2672
2688
|
validation_context = _prompt_validation_context()
|
|
2673
2689
|
|
|
@@ -3034,6 +3050,11 @@ For a complete sales return (financial + stock): create and submit both a Credit
|
|
|
3034
3050
|
- Never invent or guess a serial number. If the user has not given them, ask; to see what is in stock use search_masters master_type="serial-no" (filter item_code, warehouse) or the serial-trace report for one number.
|
|
3035
3051
|
- Units from before the item was serial-tracked have no number: give them one with a Stock Entry of type "Serial Assignment" (item_code, qty, t_warehouse, serial_no).
|
|
3036
3052
|
|
|
3053
|
+
### Attachments
|
|
3054
|
+
- Any document or master record can keep files (the customer's order e-mail or PDF, a signed slip, a certificate). They never change the record and are never printed. See what is there with the `list_record_attachments` action.
|
|
3055
|
+
- When the user uploads a file to the conversation and a record is created from it or it belongs to one, keep it with that record using `attach_chat_file` (record_type = the type slug, record_id = the record's name, attachment_id = the uploaded file's id). Do this for a customer's order that became a sales order without being asked twice; otherwise only when the user asks.
|
|
3056
|
+
- A Delivery Note has `tracking_reference` for the carrier's consignment number.
|
|
3057
|
+
|
|
3037
3058
|
### Item bundles
|
|
3038
3059
|
- An **Item Bundle** (doctype `item-bundle`: item_code = the bundle, items = rows of item_code and qty per bundle) makes one item code stand for several items. The bundle's own item is not a stock item.
|
|
3039
3060
|
- On quotations, sales orders, delivery notes and sales / POS invoices, put the bundle's item_code and qty on a line and save: the line is replaced by one line per item of the bundle, which are then ordinary lines. Do not give a bundle line a rate, discount or batch; do not expand a bundle by hand.
|
|
@@ -66,6 +66,8 @@ async def lifespan(app: FastAPI):
|
|
|
66
66
|
initialize_mentions()
|
|
67
67
|
from api.record_notes import initialize_record_notes
|
|
68
68
|
initialize_record_notes()
|
|
69
|
+
from api.record_attachments import initialize_record_attachments
|
|
70
|
+
initialize_record_attachments()
|
|
69
71
|
from api.stock_actions import initialize_stock_actions
|
|
70
72
|
initialize_stock_actions()
|
|
71
73
|
from api.pricing_actions import initialize_pricing_actions
|
|
@@ -155,6 +157,8 @@ app.include_router(auth_router, prefix="/api")
|
|
|
155
157
|
app.include_router(oauth_router, prefix="/api")
|
|
156
158
|
app.include_router(mcp_oauth_router)
|
|
157
159
|
app.include_router(attachments_router, prefix="/api")
|
|
160
|
+
from api.record_attachments import router as record_attachments_router
|
|
161
|
+
app.include_router(record_attachments_router, prefix="/api")
|
|
158
162
|
app.include_router(documents.router, prefix="/api")
|
|
159
163
|
app.include_router(proposals.router, prefix="/api")
|
|
160
164
|
app.include_router(pdf_templates_router.router, prefix="/api")
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Files kept with a document or master record.
|
|
2
|
+
|
|
3
|
+
The customer's order as it arrived, a signed delivery slip, a certificate:
|
|
4
|
+
kept next to the record they belong to instead of in a folder. An attachment
|
|
5
|
+
never changes the record (no `modified` bump, allowed on submitted documents
|
|
6
|
+
too) and is never printed with it.
|
|
7
|
+
|
|
8
|
+
Whoever may read the record may list and download its files; adding and
|
|
9
|
+
removing them needs the manager role. The demo user gets neither.
|
|
10
|
+
|
|
11
|
+
A file's content cannot be redacted like a field, so each file carries a
|
|
12
|
+
sensitivity class as a whole (lambda_erp.permissions, free content): its own
|
|
13
|
+
when one was set, else the class of the record type it is kept with. A file
|
|
14
|
+
on a purchase order or a supplier counts as purchase prices and does not
|
|
15
|
+
exist for a user who does not see those.
|
|
16
|
+
|
|
17
|
+
REST:
|
|
18
|
+
GET /api/record-attachments?record_type=sales-order&record_id=SO-0001
|
|
19
|
+
POST /api/record-attachments (multipart: record_type, record_id, file, description)
|
|
20
|
+
GET /api/record-attachments/{id} (the file)
|
|
21
|
+
DELETE /api/record-attachments/{id}
|
|
22
|
+
|
|
23
|
+
Chat / MCP: actions list_record_attachments and attach_chat_file (keeps a
|
|
24
|
+
file that was uploaded to the conversation with a record).
|
|
25
|
+
|
|
26
|
+
See docs/attachments.md.
|
|
27
|
+
"""
|
|
28
|
+
import hashlib
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import uuid
|
|
32
|
+
|
|
33
|
+
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
|
|
34
|
+
from fastapi.responses import Response
|
|
35
|
+
from pydantic import Field
|
|
36
|
+
|
|
37
|
+
from api import mentions, services
|
|
38
|
+
from api.auth import get_current_user
|
|
39
|
+
from lambda_erp.database import get_db
|
|
40
|
+
from lambda_erp.utils import now
|
|
41
|
+
|
|
42
|
+
TABLE = "Record Attachment"
|
|
43
|
+
MAX_SIZE = 15 * 1024 * 1024
|
|
44
|
+
MAX_PER_RECORD = 50
|
|
45
|
+
# What may be kept: documents, images, mail, spreadsheets. Nothing a browser
|
|
46
|
+
# would run; files are always sent back as downloads.
|
|
47
|
+
ALLOWED = {
|
|
48
|
+
".pdf": "application/pdf",
|
|
49
|
+
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp",
|
|
50
|
+
".tif": "image/tiff", ".tiff": "image/tiff",
|
|
51
|
+
".eml": "message/rfc822", ".msg": "application/vnd.ms-outlook",
|
|
52
|
+
".txt": "text/plain", ".csv": "text/csv",
|
|
53
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
54
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
55
|
+
".xml": "application/xml",
|
|
56
|
+
}
|
|
57
|
+
_UNSAFE = re.compile(r"[^\w.\- ()\[\]]+", re.UNICODE)
|
|
58
|
+
|
|
59
|
+
router = APIRouter(prefix="/record-attachments", tags=["attachments"])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _target(record_type):
|
|
63
|
+
doctype = services.SLUG_TO_DOCTYPE.get(record_type)
|
|
64
|
+
if doctype:
|
|
65
|
+
return doctype
|
|
66
|
+
master = services.MASTER_TABLES.get(record_type)
|
|
67
|
+
return master[0] if master else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _require_record(record_type, record_id, user, write=False):
|
|
71
|
+
"""The record exists and the caller may read it (and, to write, is at
|
|
72
|
+
least a manager). Refusals do not say whether the record exists."""
|
|
73
|
+
from lambda_erp import permissions
|
|
74
|
+
from lambda_erp.exceptions import PermissionDenied
|
|
75
|
+
|
|
76
|
+
table = _target(record_type)
|
|
77
|
+
role = (user or {}).get("role")
|
|
78
|
+
if not table or role not in mentions.REAL_ROLES or not get_db().exists(table, record_id):
|
|
79
|
+
raise HTTPException(404, "Record is unavailable")
|
|
80
|
+
try:
|
|
81
|
+
with permissions.acting_as(user):
|
|
82
|
+
permissions.require_readable(table, record_id)
|
|
83
|
+
except PermissionDenied:
|
|
84
|
+
raise HTTPException(404, "Record is unavailable")
|
|
85
|
+
if write and role not in ("manager", "admin"):
|
|
86
|
+
raise HTTPException(403, "Adding or removing attachments requires the manager role")
|
|
87
|
+
return table
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def safe_filename(filename):
|
|
91
|
+
name = os.path.basename(str(filename or "").replace("\\", "/")).strip()
|
|
92
|
+
name = _UNSAFE.sub("_", name).strip(". ")[:150]
|
|
93
|
+
return name or "attachment"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def effective_class(row):
|
|
97
|
+
"""The sensitivity class of a stored file: its own, else its record type's."""
|
|
98
|
+
from lambda_erp import permissions
|
|
99
|
+
own = row.get("sensitivity")
|
|
100
|
+
if own:
|
|
101
|
+
return None if own == permissions.HARMLESS else own
|
|
102
|
+
return permissions.content_class(_target(row["record_type"]))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _hidden_from(row, user):
|
|
106
|
+
from lambda_erp import permissions
|
|
107
|
+
with permissions.acting_as(user):
|
|
108
|
+
return permissions.content_hidden(effective_class(row))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _check_sensitivity(value, record_type, user, current=None):
|
|
112
|
+
"""A sensitivity setting a caller may give: empty (the record type's
|
|
113
|
+
class), 'none' (nothing sensitive) or a class. Only someone who sees the
|
|
114
|
+
classes involved can set or lift one."""
|
|
115
|
+
from lambda_erp import permissions
|
|
116
|
+
value = (str(value).strip() or None) if value is not None else None
|
|
117
|
+
if value not in (None, permissions.HARMLESS) and value not in permissions.SENSITIVITY_CLASSES:
|
|
118
|
+
raise HTTPException(422, f"sensitivity must be empty, '{permissions.HARMLESS}' or one of "
|
|
119
|
+
f"{', '.join(sorted(permissions.SENSITIVITY_CLASSES))}")
|
|
120
|
+
default = permissions.content_class(_target(record_type))
|
|
121
|
+
with permissions.acting_as(user):
|
|
122
|
+
involved = {default, current, value} - {None, permissions.HARMLESS}
|
|
123
|
+
blind = sorted(cls for cls in involved if permissions.content_hidden(cls))
|
|
124
|
+
if blind and (value is not None or current is not None):
|
|
125
|
+
raise HTTPException(403, "Your access profile hides this kind of content, so you cannot classify files "
|
|
126
|
+
"kept with this record")
|
|
127
|
+
return value
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _public(row):
|
|
131
|
+
return {"id": row["name"], "record_type": row["record_type"], "record_id": row["record_id"],
|
|
132
|
+
"filename": row["filename"], "content_type": row["content_type"], "size": row["size"],
|
|
133
|
+
"sensitivity": row.get("sensitivity") or None, "sensitivity_class": effective_class(row),
|
|
134
|
+
"description": row.get("description"), "uploaded_by": row.get("uploaded_by_name") or row.get("uploaded_by"),
|
|
135
|
+
"created_at": row.get("creation"), "url": f"/api/record-attachments/{row['name']}"}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def list_attachments(record_type, record_id, user):
|
|
139
|
+
_require_record(record_type, record_id, user)
|
|
140
|
+
from lambda_erp import permissions
|
|
141
|
+
rows = get_db().sql(
|
|
142
|
+
f'SELECT name, record_type, record_id, filename, content_type, size, description, uploaded_by, '
|
|
143
|
+
f'uploaded_by_name, creation, sensitivity FROM "{TABLE}" WHERE record_type = ? AND record_id = ? '
|
|
144
|
+
f'ORDER BY creation, name', [record_type, record_id])
|
|
145
|
+
# Files of a class hidden from the caller are not there for them, name included.
|
|
146
|
+
return {"attachments": [_public(row) for row in rows if not _hidden_from(row, user)],
|
|
147
|
+
"default_class": permissions.content_class(_target(record_type)),
|
|
148
|
+
"sensitivity_classes": dict(permissions.SENSITIVITY_CLASSES)}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def add_attachment(record_type, record_id, filename, data, user, description=None, sensitivity=None):
|
|
152
|
+
"""Keep a file with a record. Returns its public description.
|
|
153
|
+
|
|
154
|
+
`sensitivity`: empty for the record type's class, 'none' for "nothing
|
|
155
|
+
sensitive in here", or a sensitivity class."""
|
|
156
|
+
_require_record(record_type, record_id, user, write=True)
|
|
157
|
+
sensitivity = _check_sensitivity(sensitivity, record_type, user)
|
|
158
|
+
filename = safe_filename(filename)
|
|
159
|
+
extension = os.path.splitext(filename)[1].lower()
|
|
160
|
+
if extension not in ALLOWED:
|
|
161
|
+
raise HTTPException(415, f"{extension or 'This file type'} cannot be attached. "
|
|
162
|
+
f"Allowed: {', '.join(sorted(ALLOWED))}")
|
|
163
|
+
if not data:
|
|
164
|
+
raise HTTPException(400, "The file is empty")
|
|
165
|
+
if len(data) > MAX_SIZE:
|
|
166
|
+
raise HTTPException(413, f"The file is too large (at most {MAX_SIZE // (1024 * 1024)} MB)")
|
|
167
|
+
db = get_db()
|
|
168
|
+
count = db.sql(f'SELECT COUNT(*) AS n FROM "{TABLE}" WHERE record_type = ? AND record_id = ?',
|
|
169
|
+
[record_type, record_id])[0]["n"]
|
|
170
|
+
if count >= MAX_PER_RECORD:
|
|
171
|
+
raise HTTPException(409, f"A record holds at most {MAX_PER_RECORD} attachments")
|
|
172
|
+
name = uuid.uuid4().hex
|
|
173
|
+
db.sql(
|
|
174
|
+
f'INSERT INTO "{TABLE}" (name, record_type, record_id, filename, content_type, size, sha256, data, '
|
|
175
|
+
f'description, uploaded_by, uploaded_by_name, creation, sensitivity) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
|
176
|
+
[name, record_type, record_id, filename, ALLOWED[extension], len(data), hashlib.sha256(data).hexdigest(),
|
|
177
|
+
data, (str(description).strip()[:500] or None) if description else None,
|
|
178
|
+
user.get("user_id") or user.get("name"), user.get("full_name") or user.get("email"), now(), sensitivity])
|
|
179
|
+
db.commit()
|
|
180
|
+
row = db.sql(f'SELECT name, record_type, record_id, filename, content_type, size, description, uploaded_by, '
|
|
181
|
+
f'uploaded_by_name, creation, sensitivity FROM "{TABLE}" WHERE name = ?', [name])[0]
|
|
182
|
+
return _public(row)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _load(attachment_id, user, write=False):
|
|
186
|
+
rows = get_db().sql(f'SELECT * FROM "{TABLE}" WHERE name = ?', [attachment_id])
|
|
187
|
+
if not rows:
|
|
188
|
+
raise HTTPException(404, "Attachment not found")
|
|
189
|
+
_require_record(rows[0]["record_type"], rows[0]["record_id"], user, write=write)
|
|
190
|
+
if _hidden_from(rows[0], user):
|
|
191
|
+
raise HTTPException(404, "Attachment not found")
|
|
192
|
+
return rows[0]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def delete_attachments_for(record_type, record_id):
|
|
196
|
+
"""Drop a hard-deleted record's files."""
|
|
197
|
+
get_db().sql(f'DELETE FROM "{TABLE}" WHERE record_type = ? AND record_id = ?', [record_type, record_id])
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# -- REST ---------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
@router.get("")
|
|
203
|
+
def list_route(record_type: str, record_id: str, user: dict = Depends(get_current_user)):
|
|
204
|
+
return list_attachments(record_type, record_id, user)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@router.post("")
|
|
208
|
+
async def upload_route(record_type: str = Form(...), record_id: str = Form(...), file: UploadFile = File(...),
|
|
209
|
+
description: str | None = Form(None), sensitivity: str | None = Form(None),
|
|
210
|
+
user: dict = Depends(get_current_user)):
|
|
211
|
+
# Check access before reading the body into memory.
|
|
212
|
+
_require_record(record_type, record_id, user, write=True)
|
|
213
|
+
_check_sensitivity(sensitivity, record_type, user)
|
|
214
|
+
data = await file.read(MAX_SIZE + 1)
|
|
215
|
+
return add_attachment(record_type, record_id, file.filename, data, user, description, sensitivity)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class Classify(mentions.Input):
|
|
219
|
+
sensitivity: str | None = Field(default=None, max_length=40)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@router.put("/{attachment_id}")
|
|
223
|
+
def classify_route(attachment_id: str, body: Classify, user: dict = Depends(get_current_user)):
|
|
224
|
+
"""Change what a file counts as: empty (the record type's class), 'none'
|
|
225
|
+
or a sensitivity class."""
|
|
226
|
+
row = _load(attachment_id, user, write=True)
|
|
227
|
+
value = _check_sensitivity(body.sensitivity, row["record_type"], user, current=row.get("sensitivity") or "default")
|
|
228
|
+
db = get_db()
|
|
229
|
+
db.sql(f'UPDATE "{TABLE}" SET sensitivity = ? WHERE name = ?', [value, row["name"]])
|
|
230
|
+
db.commit()
|
|
231
|
+
return _public({**row, "sensitivity": value})
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@router.get("/{attachment_id}")
|
|
235
|
+
def download_route(attachment_id: str, user: dict = Depends(get_current_user)):
|
|
236
|
+
row = _load(attachment_id, user)
|
|
237
|
+
data = row["data"]
|
|
238
|
+
if isinstance(data, memoryview):
|
|
239
|
+
data = data.tobytes()
|
|
240
|
+
ascii_name = row["filename"].encode("ascii", "replace").decode().replace('"', "_")
|
|
241
|
+
return Response(content=bytes(data), media_type=row["content_type"], headers={
|
|
242
|
+
# Always a download, never rendered in the application's origin.
|
|
243
|
+
"Content-Disposition": f'attachment; filename="{ascii_name}"',
|
|
244
|
+
"X-Content-Type-Options": "nosniff",
|
|
245
|
+
"Cache-Control": "private, no-store",
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@router.delete("/{attachment_id}")
|
|
250
|
+
def delete_route(attachment_id: str, user: dict = Depends(get_current_user)):
|
|
251
|
+
row = _load(attachment_id, user, write=True)
|
|
252
|
+
db = get_db()
|
|
253
|
+
db.sql(f'DELETE FROM "{TABLE}" WHERE name = ?', [row["name"]])
|
|
254
|
+
db.commit()
|
|
255
|
+
return {"ok": True}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# -- chat / MCP ---------------------------------------------------------------
|
|
259
|
+
|
|
260
|
+
class ListAttachments(mentions.Input):
|
|
261
|
+
record_type: str = Field(min_length=1, max_length=100)
|
|
262
|
+
record_id: str = Field(min_length=1, max_length=200)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
class AttachChatFile(mentions.Input):
|
|
266
|
+
record_type: str = Field(min_length=1, max_length=100)
|
|
267
|
+
record_id: str = Field(min_length=1, max_length=200)
|
|
268
|
+
attachment_id: str = Field(min_length=1, max_length=100)
|
|
269
|
+
description: str | None = Field(default=None, max_length=500)
|
|
270
|
+
sensitivity: str | None = Field(default=None, max_length=40)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _list_action(args, user):
|
|
274
|
+
data = ListAttachments.model_validate(args)
|
|
275
|
+
return list_attachments(data.record_type, data.record_id, user)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _attach_chat_file(args, user):
|
|
279
|
+
data = AttachChatFile.model_validate(args)
|
|
280
|
+
from api.attachments import get_attachments_by_ids
|
|
281
|
+
found = get_attachments_by_ids([data.attachment_id], user.get("user_id") or user.get("name"))
|
|
282
|
+
if not found:
|
|
283
|
+
raise HTTPException(404, "That file was not uploaded to one of your conversations")
|
|
284
|
+
return add_attachment(data.record_type, data.record_id, found[0]["filename"], found[0]["data"], user,
|
|
285
|
+
data.description, data.sensitivity)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def initialize_record_attachments():
|
|
289
|
+
services.register_action(
|
|
290
|
+
"list_record_attachments", _list_action, minimum_role="viewer", pass_user=True,
|
|
291
|
+
parameters=ListAttachments.model_json_schema(),
|
|
292
|
+
description="List the files kept with one document or master record (name, type, size, who added it). "
|
|
293
|
+
"record_type is the document or master type slug (e.g. sales-order, item) and record_id its "
|
|
294
|
+
"name. The files themselves are downloaded in the application.")
|
|
295
|
+
services.register_action(
|
|
296
|
+
"attach_chat_file", _attach_chat_file, minimum_role="manager", pass_user=True,
|
|
297
|
+
parameters=AttachChatFile.model_json_schema(),
|
|
298
|
+
description="Keep a file the user uploaded to this conversation with a document or master record, e.g. "
|
|
299
|
+
"the customer's order e-mail or PDF with the sales order made from it. attachment_id is the "
|
|
300
|
+
"id of the uploaded file. It does not change the record and is never printed. Leave sensitivity "
|
|
301
|
+
"empty: the file then counts as what its record type is about (a file on a purchase order or "
|
|
302
|
+
"supplier is hidden from users who do not see purchase prices). Set a sensitivity class only "
|
|
303
|
+
"when the user says what the file contains.")
|
|
@@ -82,6 +82,10 @@ def _can_access(record_type, record_id, user):
|
|
|
82
82
|
try:
|
|
83
83
|
with permissions.acting_as(user):
|
|
84
84
|
permissions.require_readable(target[0], record_id)
|
|
85
|
+
# A note is free text: what colleagues write on a purchase order or
|
|
86
|
+
# a supplier counts as what those records are about.
|
|
87
|
+
if permissions.content_hidden(permissions.content_class(target[0])):
|
|
88
|
+
return False
|
|
85
89
|
except PermissionDenied:
|
|
86
90
|
return False
|
|
87
91
|
return True
|
|
@@ -103,6 +107,11 @@ def _resolve(record_type, note_ids, user):
|
|
|
103
107
|
rows = get_db().sql(f'SELECT name, record_id, body FROM "{TABLE}" WHERE record_type = ? AND name IN ('
|
|
104
108
|
+ ','.join('?' for _ in note_ids) + ')', [record_type, *note_ids])
|
|
105
109
|
records = _existing(target[0], {row["record_id"] for row in rows})
|
|
110
|
+
# A mention does not open a record: a note on a record the reader may not
|
|
111
|
+
# see (access profile, record scope, hidden content) stays out of their
|
|
112
|
+
# inbox, excerpt and title included.
|
|
113
|
+
records = {record_id: record for record_id, record in records.items()
|
|
114
|
+
if _can_access(record_type, record_id, user)}
|
|
106
115
|
return {row["name"]: {
|
|
107
116
|
"record_id": row["record_id"], "title": _title(record_type, records[row["record_id"]]),
|
|
108
117
|
"body": row["body"], "view_url": view_url(record_type, row["record_id"], row["name"]),
|
|
@@ -908,8 +908,10 @@ def delete_master_record(master_type: str, name: str) -> dict:
|
|
|
908
908
|
raise HTTPException(status_code=409, detail=f"Cannot delete {doctype} {name}: referenced by {reference}")
|
|
909
909
|
|
|
910
910
|
from api.record_notes import delete_record_notes_for
|
|
911
|
+
from api.record_attachments import delete_attachments_for
|
|
911
912
|
with db.atomic():
|
|
912
913
|
delete_record_notes_for(master_type, name)
|
|
914
|
+
delete_attachments_for(master_type, name)
|
|
913
915
|
db.delete(doctype, name=name)
|
|
914
916
|
return {"ok": True, "status": "deleted"}
|
|
915
917
|
|
|
@@ -650,6 +650,15 @@ def _document_validation(doc):
|
|
|
650
650
|
warnings.append({'code': 'price_missing', 'message': (
|
|
651
651
|
f"Row {idx}: no price found for {row.get('item_code')} (no Item Price applies and the item "
|
|
652
652
|
f"has no standard rate); the line is priced at 0.")})
|
|
653
|
+
# A tax row without an account cannot be posted. Said on the draft, and
|
|
654
|
+
# on quotations and orders too, where it would otherwise travel unnoticed
|
|
655
|
+
# into the invoice.
|
|
656
|
+
from lambda_erp.validation import tax_rows_without_account
|
|
657
|
+
if doc.docstatus == 0:
|
|
658
|
+
for idx, label in tax_rows_without_account(doc):
|
|
659
|
+
warnings.append({'code': 'tax_account_missing', 'field': 'taxes', 'message': (
|
|
660
|
+
f"Taxes row {idx} ({label}) has no account. An invoice with this tax row cannot be submitted "
|
|
661
|
+
f"until the tax account is set on the row.")})
|
|
653
662
|
if doc.DOCTYPE == 'Proposal' and (not doc.get('customer') or not doc.get('company') or not doc.get('quotations')):
|
|
654
663
|
warnings.append({'code': 'proposal_incomplete', 'message': 'Draft saved; PDF output requires Customer, Company and at least one Quotation.'})
|
|
655
664
|
if doc.DOCTYPE == "Reservation" and not doc.get("asset") and doc.get("status") in {"Reserved", "Out"}:
|
|
@@ -260,6 +260,20 @@ export interface FleetCalendarFeed {
|
|
|
260
260
|
|
|
261
261
|
/** Narrows what a user's role allows: hidden classes of sensitive data and,
|
|
262
262
|
* per document or master type, the actions that remain. */
|
|
263
|
+
export interface RecordAttachment {
|
|
264
|
+
id: string;
|
|
265
|
+
filename: string;
|
|
266
|
+
content_type: string;
|
|
267
|
+
size: number;
|
|
268
|
+
description?: string | null;
|
|
269
|
+
uploaded_by?: string | null;
|
|
270
|
+
created_at?: string | null;
|
|
271
|
+
// What the file counts as: its own setting ("none" = nothing sensitive, a
|
|
272
|
+
// class, or null for the record type's class) and the class that results.
|
|
273
|
+
sensitivity?: string | null;
|
|
274
|
+
sensitivity_class?: string | null;
|
|
275
|
+
}
|
|
276
|
+
|
|
263
277
|
export interface AccessProfile {
|
|
264
278
|
name: string;
|
|
265
279
|
description?: string;
|
|
@@ -807,6 +821,25 @@ export const api = {
|
|
|
807
821
|
),
|
|
808
822
|
authDeleteAccessProfile: (name: string) =>
|
|
809
823
|
request<any>(`/auth/access-profiles/${encodeURIComponent(name)}`, { method: "DELETE" }),
|
|
824
|
+
// Files kept with a document or master record.
|
|
825
|
+
listRecordAttachments: (recordType: string, recordId: string) =>
|
|
826
|
+
request<{ attachments: RecordAttachment[]; default_class?: string | null; sensitivity_classes?: Record<string, string> }>(
|
|
827
|
+
`/record-attachments${qs({ record_type: recordType, record_id: recordId })}`),
|
|
828
|
+
classifyRecordAttachment: (id: string, sensitivity: string | null) =>
|
|
829
|
+
request<RecordAttachment>(`/record-attachments/${encodeURIComponent(id)}`, {
|
|
830
|
+
method: "PUT", body: JSON.stringify({ sensitivity }),
|
|
831
|
+
}),
|
|
832
|
+
uploadRecordAttachment: (recordType: string, recordId: string, file: File, description?: string) => {
|
|
833
|
+
const form = new FormData();
|
|
834
|
+
form.append("record_type", recordType);
|
|
835
|
+
form.append("record_id", recordId);
|
|
836
|
+
form.append("file", file);
|
|
837
|
+
if (description) form.append("description", description);
|
|
838
|
+
return multipartRequest<RecordAttachment>("/record-attachments", form);
|
|
839
|
+
},
|
|
840
|
+
deleteRecordAttachment: (id: string) =>
|
|
841
|
+
request<any>(`/record-attachments/${encodeURIComponent(id)}`, { method: "DELETE" }),
|
|
842
|
+
recordAttachmentUrl: (id: string) => `${BASE}/record-attachments/${encodeURIComponent(id)}`,
|
|
810
843
|
authAssignRecordScope: (userName: string, record_scope: Record<string, string[]> | null) =>
|
|
811
844
|
request<any>(`/auth/users/${encodeURIComponent(userName)}/record-scope`, {
|
|
812
845
|
method: "PUT", body: JSON.stringify({ record_scope }),
|
|
@@ -130,6 +130,12 @@ def run_period_revaluation(company, date=None, *, post=True):
|
|
|
130
130
|
breakdown only, nothing posted. Raises if a foreign balance exists but no
|
|
131
131
|
Unrealized Exchange Gain/Loss account is configured.
|
|
132
132
|
"""
|
|
133
|
+
# It lists open receivables and payables and posts to the ledger: closed
|
|
134
|
+
# to a user whose access profile hides the ledger, or who is restricted
|
|
135
|
+
# to assigned records (lambda_erp.permissions).
|
|
136
|
+
from lambda_erp import permissions
|
|
137
|
+
permissions.require("Journal Entry", "create" if post else "read")
|
|
138
|
+
permissions.require_no_record_scope("the currency revaluation")
|
|
133
139
|
db = get_db()
|
|
134
140
|
on_date = date or nowdate()
|
|
135
141
|
base_ccy = db.get_value("Company", company, "default_currency") or "USD"
|
|
@@ -3661,6 +3661,40 @@ def _m064_item_bundles(db: "Database") -> None:
|
|
|
3661
3661
|
db.ensure_column(table, "bundle_qty", "REAL")
|
|
3662
3662
|
|
|
3663
3663
|
|
|
3664
|
+
def _m065_record_attachments(db: "Database") -> None:
|
|
3665
|
+
"""Files kept with a document or master record, and a tracking reference
|
|
3666
|
+
on delivery notes (see docs/attachments.md)."""
|
|
3667
|
+
db.conn.execute(db._ddl(
|
|
3668
|
+
"""CREATE TABLE IF NOT EXISTS "Record Attachment" (
|
|
3669
|
+
name TEXT PRIMARY KEY,
|
|
3670
|
+
record_type TEXT NOT NULL,
|
|
3671
|
+
record_id TEXT NOT NULL,
|
|
3672
|
+
filename TEXT NOT NULL,
|
|
3673
|
+
content_type TEXT NOT NULL,
|
|
3674
|
+
size INTEGER NOT NULL,
|
|
3675
|
+
sha256 TEXT,
|
|
3676
|
+
data BLOB NOT NULL,
|
|
3677
|
+
description TEXT,
|
|
3678
|
+
uploaded_by TEXT,
|
|
3679
|
+
uploaded_by_name TEXT,
|
|
3680
|
+
creation TEXT
|
|
3681
|
+
)"""))
|
|
3682
|
+
db.conn.execute(db._ddl(
|
|
3683
|
+
'CREATE INDEX IF NOT EXISTS "ix_record_attachment_record" ON "Record Attachment" (record_type, record_id)'))
|
|
3684
|
+
db.conn.commit()
|
|
3685
|
+
db._col_cache.pop("Record Attachment", None)
|
|
3686
|
+
db._text_col_cache.pop("Record Attachment", None)
|
|
3687
|
+
db.ensure_column("Delivery Note", "tracking_reference", "TEXT")
|
|
3688
|
+
|
|
3689
|
+
|
|
3690
|
+
def _m066_attachment_sensitivity(db: "Database") -> None:
|
|
3691
|
+
"""A sensitivity class per attachment (see docs/attachments.md). Files
|
|
3692
|
+
that exist get none of their own and so take the class of the record
|
|
3693
|
+
type they are kept with: what hangs on a purchase order or a supplier is
|
|
3694
|
+
hidden from users who do not see purchase prices."""
|
|
3695
|
+
db.ensure_column("Record Attachment", "sensitivity", "TEXT")
|
|
3696
|
+
|
|
3697
|
+
|
|
3664
3698
|
def _m052_access_profiles(db: "Database") -> None:
|
|
3665
3699
|
"""Access profiles narrow what a user's role allows (lambda_erp.permissions).
|
|
3666
3700
|
No profile is created and no user is assigned one: nothing changes for
|
|
@@ -3765,6 +3799,8 @@ Database.MIGRATIONS = [
|
|
|
3765
3799
|
(62, "stock_document_pricing", _m062_stock_document_pricing),
|
|
3766
3800
|
(63, "addresses", _m063_addresses),
|
|
3767
3801
|
(64, "item_bundles", _m064_item_bundles),
|
|
3802
|
+
(65, "record_attachments", _m065_record_attachments),
|
|
3803
|
+
(66, "attachment_sensitivity", _m066_attachment_sensitivity),
|
|
3768
3804
|
]
|
|
3769
3805
|
|
|
3770
3806
|
|
|
@@ -419,6 +419,8 @@ class Document:
|
|
|
419
419
|
self._require_in_scope()
|
|
420
420
|
from lambda_erp.validation import validate_document_requirements
|
|
421
421
|
validate_document_requirements(self)
|
|
422
|
+
from lambda_erp.validation import validate_tax_accounts
|
|
423
|
+
validate_tax_accounts(self)
|
|
422
424
|
self._validate_links()
|
|
423
425
|
self.before_submit()
|
|
424
426
|
self._data["docstatus"] = SUBMITTED
|
|
@@ -164,6 +164,44 @@ def register_sensitive_artifact(kind, name, cls=None, fields=None):
|
|
|
164
164
|
SENSITIVE_ARTIFACT_FIELDS.setdefault(kind, {}).setdefault(name, {}).update(fields)
|
|
165
165
|
|
|
166
166
|
|
|
167
|
+
# -- free content kept with a record ------------------------------------------
|
|
168
|
+
#
|
|
169
|
+
# Fields can be left out of a record. A file attached to it, or an internal
|
|
170
|
+
# note written on it, cannot: nobody knows what is in a supplier's quotation
|
|
171
|
+
# or in "agreed 73.91 with them". So free content carries a sensitivity class
|
|
172
|
+
# as a whole. By default it is the class of the record type it hangs on: what
|
|
173
|
+
# is kept with a purchase order or a supplier counts as purchase prices.
|
|
174
|
+
|
|
175
|
+
# doctype -> class, for types whose fields carry no class themselves.
|
|
176
|
+
RECORD_CONTENT_CLASSES = {"Supplier": "purchase_price"}
|
|
177
|
+
HARMLESS = "none"
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def register_content_class(doctype, cls):
|
|
181
|
+
"""Plugin seam: files and internal notes kept with records of this type
|
|
182
|
+
are hidden with class `cls` (None: they are open, whatever the fields)."""
|
|
183
|
+
if cls is not None:
|
|
184
|
+
_check_class(cls)
|
|
185
|
+
RECORD_CONTENT_CLASSES[doctype] = cls
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def content_class(doctype):
|
|
189
|
+
"""The sensitivity class of free content kept with a record of this type,
|
|
190
|
+
or None: registered explicitly, else the class that hides the type, else
|
|
191
|
+
the first class among its sensitive fields."""
|
|
192
|
+
if doctype in RECORD_CONTENT_CLASSES:
|
|
193
|
+
return RECORD_CONTENT_CLASSES[doctype]
|
|
194
|
+
if doctype in SENSITIVE_DOCTYPES:
|
|
195
|
+
return SENSITIVE_DOCTYPES[doctype]
|
|
196
|
+
present = {cls for fields in SENSITIVE_FIELDS.get(doctype, {}).values() for cls in fields.values()}
|
|
197
|
+
return next((cls for cls in SENSITIVITY_CLASSES if cls in present), None)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def content_hidden(cls):
|
|
201
|
+
"""Is free content of this class hidden from the current principal?"""
|
|
202
|
+
return bool(cls) and cls != HARMLESS and cls in hidden_classes()
|
|
203
|
+
|
|
204
|
+
|
|
167
205
|
# -- record scope -------------------------------------------------------------
|
|
168
206
|
#
|
|
169
207
|
# A user can be restricted to assigned records of a dimension (customers,
|
|
@@ -116,6 +116,34 @@ def validate_document_requirements(doc):
|
|
|
116
116
|
raise ValidationError(f'{prefix}: Warehouse is required for stock item {row["item_code"]}')
|
|
117
117
|
|
|
118
118
|
|
|
119
|
+
# Documents whose taxes are posted to the ledger when they are submitted.
|
|
120
|
+
TAX_POSTING_TYPES = {'Sales Invoice', 'Purchase Invoice', 'POS Invoice'}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def tax_rows_without_account(doc):
|
|
124
|
+
"""[(row number, description)] of tax rows that carry an amount but name
|
|
125
|
+
no account: they cannot be posted."""
|
|
126
|
+
if 'taxes' not in getattr(doc, 'CHILD_TABLES', {}):
|
|
127
|
+
return []
|
|
128
|
+
return [(idx, row.get('description') or row.get('charge_type') or 'tax')
|
|
129
|
+
for idx, row in enumerate(doc.get('taxes') or [], 1)
|
|
130
|
+
if missing(row.get('account_head')) and abs(flt(row.get('tax_amount')) or flt(row.get('rate'))) > 0]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def validate_tax_accounts(doc):
|
|
134
|
+
"""Before an invoice posts: every tax row with an amount names the account
|
|
135
|
+
it is booked on. Said here in words, instead of the ledger refusing an
|
|
136
|
+
entry without an account."""
|
|
137
|
+
if doc.DOCTYPE not in TAX_POSTING_TYPES:
|
|
138
|
+
return
|
|
139
|
+
rows = tax_rows_without_account(doc)
|
|
140
|
+
if rows:
|
|
141
|
+
named = '; '.join(f'row {idx} ({label})' for idx, label in rows)
|
|
142
|
+
raise ValidationError(
|
|
143
|
+
f'{doc.DOCTYPE}: Taxes {named}: Account is required. Set the tax account on the row in the Taxes '
|
|
144
|
+
f'table (for VAT: the VAT payable / input tax account) before submitting')
|
|
145
|
+
|
|
146
|
+
|
|
119
147
|
def document_requirements(cls):
|
|
120
148
|
"""Machine-readable minimums plus conditional rules owned by the class."""
|
|
121
149
|
required = list(getattr(cls, 'REQUIRED_FIELDS', ()))
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
File without changes
|
|
File without changes
|