lambda-erp 1.4.9__tar.gz → 1.4.10__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.9 → lambda_erp-1.4.10}/PKG-INFO +1 -1
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/chat.py +19 -1
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/reports.py +44 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/services.py +4 -1
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/stock_actions.py +28 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/frontend/src/api/client.ts +6 -0
- lambda_erp-1.4.10/lambda_erp/backlog.py +196 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/database.py +18 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/hooks.py +6 -2
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/model.py +4 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/stock/delivery_note.py +58 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/validation.py +10 -1
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/workflow.py +91 -1
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/pyproject.toml +1 -1
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/.gitignore +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/LICENSE +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/README.md +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/attachments.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/auth.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/bootstrap.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/chat_links.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/demo_limits.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/deps.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/erp_context.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/errors.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/list_values.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/llm_provider.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/main.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/mcp_oauth.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/mentions.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/menu_layout.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/oauth.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/pdf.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/pdf_contract.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/pdf_exports.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/pdf_fonts.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/pdf_pages.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/pdf_profiles.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/pdf_templates.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/pricing_actions.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/providers.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/record_notes.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/remarks_md.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/accounting.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/actions.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/admin.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/analytics.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/availability.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/bank_statements.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/chat_api.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/documents.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/masters.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/mcp.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/pdf_templates.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/proposals.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/routers/setup.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/templates/_proposal_totals.html +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/templates/_record_base.html +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/templates/delivery_note.html +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/templates/document.html +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/templates/proposal.html +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/templates/record.html +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/templates/reservation.html +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/time_filters.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/tool_permissions.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/api/write_context.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/docs/agents/README.md +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/frontend/LICENSE +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/frontend/README.md +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/bank_account.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/bank_statement_import.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/bank_transaction.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/budget.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/camt.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/chart_of_accounts.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/general_ledger.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/journal_entry.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/payment_entry.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/pos_invoice.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/purchase_invoice.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/revaluation.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/sales_invoice.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/settlement.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/engine.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/pack.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/packs/ch.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/packs/generic.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/profiles.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/setup/spine.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/accounting/subscription.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/assets/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/assets/asset.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/assets/lifecycle.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/assets/reservation.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/buying/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/buying/purchase_order.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/controllers/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/controllers/currency.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/controllers/defaults.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/controllers/item_price.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/controllers/item_prices.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/controllers/price_resolution.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/controllers/pricing_rule.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/controllers/taxes_and_totals.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/exceptions.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/master_integrity.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/permissions.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/selling/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/selling/proposal.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/selling/quotation.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/selling/sales_order.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/simulation.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/stock/__init__.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/stock/purchase_receipt.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/stock/reservation.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/stock/stock_entry.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/stock/stock_ledger.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/timestamps.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/lambda_erp/utils.py +0 -0
- {lambda_erp-1.4.9 → lambda_erp-1.4.10}/terraform/README.md +0 -0
|
@@ -878,7 +878,7 @@ TOOLS = [
|
|
|
878
878
|
"parameters": {
|
|
879
879
|
"type": "object",
|
|
880
880
|
"properties": {
|
|
881
|
-
"report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "stock-availability", "stock-detail", "batch-stock", "batch-movements", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
|
|
881
|
+
"report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "stock-availability", "stock-detail", "batch-stock", "batch-movements", "sales-backlog", "purchase-backlog", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
|
|
882
882
|
"filters": {"type": "object", "description": "Optional filters: company, account, from_date, to_date, item_code, warehouse; for batch-stock also batch_no, item_prefix, expiring_before, include_empty; for stock-detail also location, batch_no, item_prefix, item_group, expiring_before, expiring_after, include_empty; batch-movements requires batch_no. For trial-balance / profit-and-loss / balance-sheet you may also pass `presentation_currency` (e.g. \"EUR\") to view the report translated from the company's base currency at the period's closing rate — display only, the ledger stays in base currency.", "default": {}},
|
|
883
883
|
},
|
|
884
884
|
"required": ["report_type"],
|
|
@@ -1974,6 +1974,15 @@ def _handle_get_report(args):
|
|
|
1974
1974
|
return _batch_stock(db, filters.get("item_code"), filters.get("warehouse"), filters.get("batch_no"),
|
|
1975
1975
|
filters.get("item_prefix"), filters.get("expiring_before"),
|
|
1976
1976
|
bool(filters.get("include_empty")))
|
|
1977
|
+
elif report_type == "sales-backlog":
|
|
1978
|
+
from api.routers.reports import _sales_backlog
|
|
1979
|
+
return _sales_backlog(db, filters.get("customer"), filters.get("item_code"), filters.get("warehouse"),
|
|
1980
|
+
filters.get("sales_order"), filters.get("item_prefix"),
|
|
1981
|
+
bool(filters.get("only_deliverable")))
|
|
1982
|
+
elif report_type == "purchase-backlog":
|
|
1983
|
+
from api.routers.reports import _purchase_backlog
|
|
1984
|
+
return _purchase_backlog(db, filters.get("supplier"), filters.get("item_code"), filters.get("warehouse"),
|
|
1985
|
+
bool(filters.get("overdue_only")))
|
|
1977
1986
|
elif report_type == "stock-availability":
|
|
1978
1987
|
from api.routers.reports import _stock_availability
|
|
1979
1988
|
return _stock_availability(db, filters.get("item_code"), filters.get("warehouse"), filters.get("item_prefix"))
|
|
@@ -2918,6 +2927,13 @@ For a complete sales return (financial + stock): create and submit both a Credit
|
|
|
2918
2927
|
- **Material Transfer:** Moves stock between warehouses. No GL impact.
|
|
2919
2928
|
- **Batch Assignment:** Gives stock that has no batch (from before the item was batch-tracked) its batch, in place: row = item_code, qty, t_warehouse, batch_no (+ expiry_date for a new batch). No GL impact, no quantity or value change.
|
|
2920
2929
|
|
|
2930
|
+
### Partial deliveries, backorders and invoicing after delivery
|
|
2931
|
+
- Order progress is derived from the submitted documents, per order line: delivered_qty (net of returns), returned_qty, billed_qty. Never set them. Open = qty − delivered_qty.
|
|
2932
|
+
- A delivery for less than ordered leaves the rest of the line open; convert the order again later for the remainder. Converters only ever propose what is left, and submit rechecks, so a repeated conversion cannot deliver or bill twice.
|
|
2933
|
+
- Deliver first, invoice after: convert the submitted **Delivery Note** to a Sales Invoice (convert_document doctype="delivery-note", target_doctype="Sales Invoice"). It bills what that delivery delivered and has not been billed, and does not move stock again. Converting the Sales Order to a Sales Invoice instead bills the ordered quantity regardless of delivery.
|
|
2934
|
+
- "What is still open / on backorder / can go out now" → sales-backlog report. "Is it on order, and when does it come" → the same report's purchase order columns, or purchase-backlog.
|
|
2935
|
+
- When a supplier's order confirmation arrives, record its date with the `confirm_purchase_order` action.
|
|
2936
|
+
|
|
2921
2937
|
### Prices: how they are found, and explaining them
|
|
2922
2938
|
- A line without a rate is priced when the document is saved: the Item Price of the document's price list (a row for this customer/supplier beats the list price; the highest min_qty reached; the narrower, then newer validity), else the item's standard rate. Then at most ONE Pricing Rule applies on top: highest priority, then the most specific match, then min_qty, validity and name.
|
|
2923
2939
|
- Prices and rules are looked up for the document's date (`pricing_date` if set, else posting/transaction date). A price valid from next month does not apply to a document dated today.
|
|
@@ -3003,6 +3019,8 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
|
|
|
3003
3019
|
- **ar-aging** — Outstanding receivables bucketed by overdue days (Current, 1-30, 31-60, 61-90, 90+). Filters: company, as_of_date.
|
|
3004
3020
|
- **ap-aging** — Outstanding payables bucketed by overdue days. Filters: company, as_of_date.
|
|
3005
3021
|
- **stock-balance** — Inventory quantities and valuations. Filters: item_code, warehouse.
|
|
3022
|
+
- **sales-backlog** — Open sales order lines (ordered > delivered): ordered_qty, delivered_qty (net of returns), returned_qty, billed_qty, open_qty, reserved_qty, deliverable_qty (what can be delivered NOW; stock is shared out in due-date order, so it is never promised twice), short_qty, on_purchase_order_qty, next_expected_date and the purchase orders behind it. Filters: customer, item_code, item_prefix, warehouse, sales_order, only_deliverable. Use only_deliverable=true after a goods receipt to see which open orders can now go out. Read-only: it books nothing.
|
|
3023
|
+
- **purchase-backlog** — Open purchase order lines with expected_date (the supplier's confirmed date, else the order's schedule date), confirmed, overdue and days_overdue. Filters: supplier, item_code, warehouse, overdue_only. Use overdue_only=true for "what should have arrived".
|
|
3006
3024
|
- **stock-availability** — Per item × warehouse: physical_qty (in stock), blocked_qty (expired or blocked batches), reserved_qty (open Stock Reservations), available_qty (= physical − blocked − reserved), plus open_sales_order_qty (ordered by customers, not yet delivered) and on_purchase_order_qty (ordered from suppliers, not yet received). Filters: item_code, warehouse, item_prefix. Use this to answer "can we deliver X" and "is it already on order".
|
|
3007
3025
|
- **stock-detail** — Where stock is, in one view: item, warehouse, storage location, batch, expiry date, quantity. Filters: item_code, warehouse, location, batch_no, item_prefix, item_group, expiring_before, expiring_after, include_empty. Use this for "what is in location B4", "where is item X", "what expires in the next 3 months in warehouse Y".
|
|
3008
3026
|
- **batch-stock** — Quantity per item × warehouse × batch with the batch's expiry date (batch-tracked items only). Filters: item_code, warehouse, batch_no, item_prefix (item codes starting with…), expiring_before (date), include_empty. A batch label is NOT unique: the same label can exist on several items, so a batch_no-only lookup can return several items — show them all, never pick one.
|
|
@@ -481,6 +481,50 @@ def stock_availability(
|
|
|
481
481
|
return _stock_availability(get_db(), item_code, warehouse, item_prefix)
|
|
482
482
|
|
|
483
483
|
|
|
484
|
+
def _sales_backlog(db, customer=None, item_code=None, warehouse=None, sales_order=None, item_prefix=None,
|
|
485
|
+
only_deliverable=False):
|
|
486
|
+
"""Open sales order lines: ordered, delivered, returned, billed, open,
|
|
487
|
+
reserved, what can be delivered now, and what is on purchase order with
|
|
488
|
+
its expected date."""
|
|
489
|
+
permissions.require_artifact("report", "sales-backlog")
|
|
490
|
+
permissions.require("Sales Order", "read")
|
|
491
|
+
from lambda_erp.backlog import sales_backlog
|
|
492
|
+
# Purchase orders behind a shortage are shown to those who may read them.
|
|
493
|
+
return {"rows": sales_backlog(customer, item_code, warehouse, sales_order, item_prefix, only_deliverable,
|
|
494
|
+
with_purchase_orders=permissions.can("Purchase Order", "read"))}
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
@router.get("/sales-backlog")
|
|
498
|
+
def sales_backlog_report(
|
|
499
|
+
customer: str | None = None,
|
|
500
|
+
item_code: str | None = None,
|
|
501
|
+
warehouse: str | None = None,
|
|
502
|
+
sales_order: str | None = None,
|
|
503
|
+
item_prefix: str | None = None,
|
|
504
|
+
only_deliverable: bool = False,
|
|
505
|
+
):
|
|
506
|
+
return _sales_backlog(get_db(), customer, item_code, warehouse, sales_order, item_prefix, only_deliverable)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _purchase_backlog(db, supplier=None, item_code=None, warehouse=None, overdue_only=False):
|
|
510
|
+
"""Open purchase order lines with the supplier's confirmed date and
|
|
511
|
+
whether they are overdue. Quantities and dates only, no prices."""
|
|
512
|
+
permissions.require_artifact("report", "purchase-backlog")
|
|
513
|
+
permissions.require("Purchase Order", "read")
|
|
514
|
+
from lambda_erp.backlog import purchase_backlog
|
|
515
|
+
return {"rows": purchase_backlog(supplier, item_code, warehouse, overdue_only)}
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
@router.get("/purchase-backlog")
|
|
519
|
+
def purchase_backlog_report(
|
|
520
|
+
supplier: str | None = None,
|
|
521
|
+
item_code: str | None = None,
|
|
522
|
+
warehouse: str | None = None,
|
|
523
|
+
overdue_only: bool = False,
|
|
524
|
+
):
|
|
525
|
+
return _purchase_backlog(get_db(), supplier, item_code, warehouse, overdue_only)
|
|
526
|
+
|
|
527
|
+
|
|
484
528
|
@router.get("/stock-detail")
|
|
485
529
|
def stock_detail(
|
|
486
530
|
item_code: str | None = None,
|
|
@@ -20,7 +20,9 @@ from lambda_erp.accounting.purchase_invoice import PurchaseInvoice, make_purchas
|
|
|
20
20
|
from lambda_erp.accounting.payment_entry import PaymentEntry
|
|
21
21
|
from lambda_erp.accounting.journal_entry import JournalEntry
|
|
22
22
|
from lambda_erp.stock.stock_entry import StockEntry
|
|
23
|
-
from lambda_erp.stock.delivery_note import
|
|
23
|
+
from lambda_erp.stock.delivery_note import (
|
|
24
|
+
DeliveryNote, make_delivery_note, make_delivery_return, make_sales_invoice_from_delivery_note,
|
|
25
|
+
)
|
|
24
26
|
from lambda_erp.stock.purchase_receipt import PurchaseReceipt, make_purchase_receipt, make_purchase_receipt_return
|
|
25
27
|
from lambda_erp.accounting.pos_invoice import POSInvoice
|
|
26
28
|
from lambda_erp.controllers.pricing_rule import PricingRule
|
|
@@ -71,6 +73,7 @@ CONVERTERS = {
|
|
|
71
73
|
("Quotation", "Delivery Note"): make_delivery_note_from_quotation,
|
|
72
74
|
("Sales Order", "Sales Invoice"): make_sales_invoice,
|
|
73
75
|
("Sales Order", "Delivery Note"): make_delivery_note,
|
|
76
|
+
("Delivery Note", "Sales Invoice"): make_sales_invoice_from_delivery_note,
|
|
74
77
|
("Purchase Order", "Purchase Invoice"): make_purchase_invoice,
|
|
75
78
|
("Purchase Order", "Purchase Receipt"): make_purchase_receipt,
|
|
76
79
|
# Returns (same-to-same conversion creates a return document)
|
|
@@ -52,7 +52,35 @@ def suggest(args):
|
|
|
52
52
|
sales_order_item=data.sales_order_item, include_short_dated=data.include_short_dated)
|
|
53
53
|
|
|
54
54
|
|
|
55
|
+
class ConfirmPurchaseOrder(mentions.Input):
|
|
56
|
+
purchase_order: str = Field(min_length=1, max_length=200)
|
|
57
|
+
confirmed_date: str = Field(min_length=8, max_length=10)
|
|
58
|
+
lines: list[str] | None = Field(default=None, max_length=500)
|
|
59
|
+
confirmed_qty: float | None = Field(default=None, gt=0)
|
|
60
|
+
confirmation_reference: str | None = Field(default=None, max_length=200)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def confirm_purchase_order(args, user=None):
|
|
64
|
+
data = ConfirmPurchaseOrder.model_validate(args)
|
|
65
|
+
permissions.require_readable("Purchase Order", data.purchase_order)
|
|
66
|
+
permissions.require("Purchase Order", "update")
|
|
67
|
+
from lambda_erp.backlog import confirm_purchase_order_lines
|
|
68
|
+
return confirm_purchase_order_lines(
|
|
69
|
+
data.purchase_order, data.confirmed_date, lines=data.lines, confirmed_qty=data.confirmed_qty,
|
|
70
|
+
confirmation_reference=data.confirmation_reference,
|
|
71
|
+
confirmed_by=(user or {}).get("user_id") or (user or {}).get("name"))
|
|
72
|
+
|
|
73
|
+
|
|
55
74
|
def initialize_stock_actions():
|
|
75
|
+
services.register_action(
|
|
76
|
+
"confirm_purchase_order", confirm_purchase_order,
|
|
77
|
+
description=(
|
|
78
|
+
"Record the supplier's confirmed delivery date on a SUBMITTED purchase order: on all open lines, or on "
|
|
79
|
+
"`lines` (row names or positions). Optional confirmation_reference (the supplier's confirmation number) "
|
|
80
|
+
"and, for one line, confirmed_qty. Use it when an order confirmation arrives; the date then shows in the "
|
|
81
|
+
"sales-backlog and purchase-backlog reports. Only assign a confirmation to an order when the order number "
|
|
82
|
+
"is stated or the user confirms which order it belongs to."),
|
|
83
|
+
parameters=ConfirmPurchaseOrder.model_json_schema(), minimum_role="manager", pass_user=True)
|
|
56
84
|
services.register_action(
|
|
57
85
|
"reserve_sales_order", reserve_order,
|
|
58
86
|
description=(
|
|
@@ -568,6 +568,12 @@ export const api = {
|
|
|
568
568
|
batchStock: (params?: Record<string, string>) =>
|
|
569
569
|
request<{ rows: any[] }>(`/reports/batch-stock${qs(params)}`),
|
|
570
570
|
|
|
571
|
+
salesBacklog: (params?: Record<string, string>) =>
|
|
572
|
+
request<{ rows: any[] }>(`/reports/sales-backlog${qs(params)}`),
|
|
573
|
+
|
|
574
|
+
purchaseBacklog: (params?: Record<string, string>) =>
|
|
575
|
+
request<{ rows: any[] }>(`/reports/purchase-backlog${qs(params)}`),
|
|
576
|
+
|
|
571
577
|
stockAvailability: (params?: Record<string, string>) =>
|
|
572
578
|
request<{ rows: any[] }>(`/reports/stock-availability${qs(params)}`),
|
|
573
579
|
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Open order quantities: what is still to deliver, what can be delivered
|
|
2
|
+
now, and what is on its way from suppliers.
|
|
3
|
+
|
|
4
|
+
Everything here is read from the orders and the stock as they are; nothing
|
|
5
|
+
is stored, reserved, delivered or invoiced by asking.
|
|
6
|
+
|
|
7
|
+
Per sales order line:
|
|
8
|
+
|
|
9
|
+
ordered the line's qty
|
|
10
|
+
delivered delivered and not returned (delivery notes and direct-stock
|
|
11
|
+
invoices, net of returns)
|
|
12
|
+
returned how much of what was delivered came back
|
|
13
|
+
billed invoiced, net of credit notes for returned goods
|
|
14
|
+
reserved still held by the line's stock reservation
|
|
15
|
+
open ordered - delivered
|
|
16
|
+
|
|
17
|
+
See docs/order-progress-and-backlog.md.
|
|
18
|
+
"""
|
|
19
|
+
from collections import defaultdict
|
|
20
|
+
|
|
21
|
+
from lambda_erp.database import get_db
|
|
22
|
+
from lambda_erp.exceptions import ValidationError
|
|
23
|
+
from lambda_erp.utils import flt, getdate, now, nowdate
|
|
24
|
+
|
|
25
|
+
EPSILON = 1e-9
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _open_purchase_lines(item_codes=None, supplier=None, item_code=None, warehouse=None):
|
|
29
|
+
db = get_db()
|
|
30
|
+
where = ["p.docstatus = 1", "COALESCE(p.discarded, 0) = 0", "i.qty > COALESCE(i.received_qty, 0)"]
|
|
31
|
+
params = []
|
|
32
|
+
if item_codes is not None:
|
|
33
|
+
if not item_codes:
|
|
34
|
+
return []
|
|
35
|
+
where.append(f"i.item_code IN ({', '.join('?' for _ in item_codes)})")
|
|
36
|
+
params += list(item_codes)
|
|
37
|
+
for column, value in (("p.supplier", supplier), ("i.item_code", item_code), ("i.warehouse", warehouse)):
|
|
38
|
+
if value:
|
|
39
|
+
where.append(f"{column} = ?")
|
|
40
|
+
params.append(value)
|
|
41
|
+
return db.sql(
|
|
42
|
+
'SELECT p.name AS purchase_order, p.supplier, p.supplier_name, p.transaction_date, p.schedule_date, '
|
|
43
|
+
'i.name AS purchase_order_item, i.idx, i.item_code, i.item_name, i.warehouse, i.qty, '
|
|
44
|
+
'COALESCE(i.received_qty, 0) AS received_qty, i.confirmed_date, i.confirmed_qty, '
|
|
45
|
+
'i.confirmation_reference '
|
|
46
|
+
'FROM "Purchase Order Item" i JOIN "Purchase Order" p ON p.name = i.parent '
|
|
47
|
+
f'WHERE {" AND ".join(where)} ORDER BY p.transaction_date, p.name, i.idx', params)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _expected_date(row):
|
|
51
|
+
return row.get("confirmed_date") or row.get("schedule_date") or None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def sales_backlog(customer=None, item_code=None, warehouse=None, sales_order=None, item_prefix=None,
|
|
55
|
+
only_deliverable=False, with_purchase_orders=True):
|
|
56
|
+
"""Open sales order lines with what could be delivered now.
|
|
57
|
+
|
|
58
|
+
Stock is shared out in the order the lines are due (delivery date, then
|
|
59
|
+
order date, order and line): a line first gets what its own reservation
|
|
60
|
+
holds, then free stock (in stock, not blocked, not reserved for anyone)
|
|
61
|
+
as far as it lasts. So `deliverable_qty` over all lines never exceeds
|
|
62
|
+
what is there.
|
|
63
|
+
"""
|
|
64
|
+
from lambda_erp.stock.reservation import availability_rows
|
|
65
|
+
|
|
66
|
+
db = get_db()
|
|
67
|
+
where = ["o.docstatus = 1", "COALESCE(o.discarded, 0) = 0", "i.qty > COALESCE(i.delivered_qty, 0)"]
|
|
68
|
+
params = []
|
|
69
|
+
for column, value in (("o.customer", customer), ("i.item_code", item_code), ("i.warehouse", warehouse),
|
|
70
|
+
("o.name", sales_order)):
|
|
71
|
+
if value:
|
|
72
|
+
where.append(f"{column} = ?")
|
|
73
|
+
params.append(value)
|
|
74
|
+
if item_prefix:
|
|
75
|
+
where.append("i.item_code LIKE ?")
|
|
76
|
+
params.append(str(item_prefix).replace("%", "") + "%")
|
|
77
|
+
held = "CASE WHEN r.reserved_qty > COALESCE(i.delivered_qty, 0) THEN r.reserved_qty - COALESCE(i.delivered_qty, 0) ELSE 0 END"
|
|
78
|
+
lines = db.sql(
|
|
79
|
+
'SELECT o.name AS sales_order, o.customer, o.customer_name, o.transaction_date, o.delivery_date, '
|
|
80
|
+
'i.name AS sales_order_item, i.idx, i.item_code, i.item_name, i.warehouse, i.qty AS ordered_qty, '
|
|
81
|
+
'COALESCE(i.delivered_qty, 0) AS delivered_qty, COALESCE(i.returned_qty, 0) AS returned_qty, '
|
|
82
|
+
'COALESCE(i.billed_qty, 0) AS billed_qty, '
|
|
83
|
+
f'COALESCE((SELECT SUM({held}) FROM "Stock Reservation" r WHERE r.sales_order_item = i.name '
|
|
84
|
+
"AND r.status IN ('Reserved', 'Partially Delivered') AND COALESCE(r.discarded, 0) = 0), 0) AS reserved_qty "
|
|
85
|
+
'FROM "Sales Order Item" i JOIN "Sales Order" o ON o.name = i.parent '
|
|
86
|
+
f'WHERE {" AND ".join(where)} '
|
|
87
|
+
'ORDER BY COALESCE(o.delivery_date, o.transaction_date), o.transaction_date, o.name, i.idx', params)
|
|
88
|
+
|
|
89
|
+
free = {}
|
|
90
|
+
incoming = defaultdict(list)
|
|
91
|
+
if with_purchase_orders:
|
|
92
|
+
for row in _open_purchase_lines(sorted({line["item_code"] for line in lines if line.get("item_code")})):
|
|
93
|
+
incoming[(row["item_code"], row["warehouse"])].append(row)
|
|
94
|
+
|
|
95
|
+
result = []
|
|
96
|
+
for line in lines:
|
|
97
|
+
key = (line["item_code"], line["warehouse"])
|
|
98
|
+
if key not in free:
|
|
99
|
+
rows = availability_rows(line["item_code"], line["warehouse"]) if line["warehouse"] else []
|
|
100
|
+
free[key] = rows[0].available_qty if rows else 0.0
|
|
101
|
+
open_qty = flt(line["ordered_qty"]) - flt(line["delivered_qty"])
|
|
102
|
+
reserved = min(flt(line["reserved_qty"]), open_qty)
|
|
103
|
+
from_free = min(open_qty - reserved, free[key])
|
|
104
|
+
free[key] -= from_free
|
|
105
|
+
deliverable = reserved + from_free
|
|
106
|
+
if only_deliverable and deliverable <= EPSILON:
|
|
107
|
+
continue
|
|
108
|
+
entry = {**dict(line), "ordered_qty": flt(line["ordered_qty"]), "delivered_qty": flt(line["delivered_qty"]),
|
|
109
|
+
"returned_qty": flt(line["returned_qty"]), "billed_qty": flt(line["billed_qty"]),
|
|
110
|
+
"open_qty": open_qty, "reserved_qty": reserved, "deliverable_qty": deliverable,
|
|
111
|
+
"short_qty": max(0.0, open_qty - deliverable)}
|
|
112
|
+
if with_purchase_orders:
|
|
113
|
+
orders = incoming.get(key, [])
|
|
114
|
+
dated = sorted((str(_expected_date(row))[:10] for row in orders if _expected_date(row)))
|
|
115
|
+
entry["on_purchase_order_qty"] = sum(flt(row["qty"]) - flt(row["received_qty"]) for row in orders)
|
|
116
|
+
entry["next_expected_date"] = dated[0] if dated else None
|
|
117
|
+
entry["purchase_orders"] = [
|
|
118
|
+
{"purchase_order": row["purchase_order"], "open_qty": flt(row["qty"]) - flt(row["received_qty"]),
|
|
119
|
+
"confirmed_date": row.get("confirmed_date") or None,
|
|
120
|
+
"schedule_date": row.get("schedule_date") or None,
|
|
121
|
+
"confirmation_reference": row.get("confirmation_reference") or None}
|
|
122
|
+
for row in orders]
|
|
123
|
+
result.append(entry)
|
|
124
|
+
return result
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def purchase_backlog(supplier=None, item_code=None, warehouse=None, overdue_only=False, on_date=None):
|
|
128
|
+
"""Open purchase order lines with the supplier's confirmed date. A line
|
|
129
|
+
is overdue when its expected date (confirmed, else the order's schedule
|
|
130
|
+
date) has passed and it is not fully received."""
|
|
131
|
+
today = str(on_date or nowdate())[:10]
|
|
132
|
+
result = []
|
|
133
|
+
for row in _open_purchase_lines(supplier=supplier, item_code=item_code, warehouse=warehouse):
|
|
134
|
+
expected = _expected_date(row)
|
|
135
|
+
overdue = bool(expected and str(expected)[:10] < today)
|
|
136
|
+
if overdue_only and not overdue:
|
|
137
|
+
continue
|
|
138
|
+
result.append({**dict(row), "qty": flt(row["qty"]), "received_qty": flt(row["received_qty"]),
|
|
139
|
+
"open_qty": flt(row["qty"]) - flt(row["received_qty"]),
|
|
140
|
+
"confirmed_qty": flt(row["confirmed_qty"]) if row.get("confirmed_qty") is not None else None,
|
|
141
|
+
"expected_date": str(expected)[:10] if expected else None,
|
|
142
|
+
"confirmed": bool(row.get("confirmed_date")), "overdue": overdue,
|
|
143
|
+
"days_overdue": (getdate(today) - getdate(str(expected)[:10])).days if overdue else 0})
|
|
144
|
+
return result
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def confirm_purchase_order_lines(purchase_order, confirmed_date, *, lines=None, confirmed_qty=None,
|
|
148
|
+
confirmation_reference=None, confirmed_by=None):
|
|
149
|
+
"""Record the supplier's confirmed delivery date on lines of a submitted
|
|
150
|
+
purchase order (all open lines, or those named by row name or position).
|
|
151
|
+
|
|
152
|
+
The confirmation belongs to exactly these order lines: it is stored on
|
|
153
|
+
them with the supplier's reference, who recorded it and when. Recording
|
|
154
|
+
it again replaces the earlier date. Nothing else on the order changes.
|
|
155
|
+
"""
|
|
156
|
+
db = get_db()
|
|
157
|
+
if not db._in_transaction:
|
|
158
|
+
with db.atomic():
|
|
159
|
+
return confirm_purchase_order_lines(
|
|
160
|
+
purchase_order, confirmed_date, lines=lines, confirmed_qty=confirmed_qty,
|
|
161
|
+
confirmation_reference=confirmation_reference, confirmed_by=confirmed_by)
|
|
162
|
+
order = db.get_value("Purchase Order", purchase_order, ["docstatus", "discarded"])
|
|
163
|
+
if not order or order.get("docstatus") != 1 or order.get("discarded"):
|
|
164
|
+
raise ValidationError("A delivery date can only be confirmed on a submitted purchase order")
|
|
165
|
+
try:
|
|
166
|
+
date = getdate(str(confirmed_date)[:10]).isoformat()
|
|
167
|
+
except (TypeError, ValueError):
|
|
168
|
+
raise ValidationError("confirmed_date must be a date (YYYY-MM-DD)")
|
|
169
|
+
if db.dialect == "postgres":
|
|
170
|
+
db.sql('SELECT name FROM "Purchase Order" WHERE name = ? FOR UPDATE', [purchase_order])
|
|
171
|
+
rows = db.get_all("Purchase Order Item", filters={"parent": purchase_order}, fields=["*"], order_by="idx")
|
|
172
|
+
if lines:
|
|
173
|
+
wanted = {str(value) for value in lines}
|
|
174
|
+
chosen = [row for row in rows if row["name"] in wanted or str(row.get("idx")) in wanted]
|
|
175
|
+
if len(chosen) != len(wanted):
|
|
176
|
+
raise ValidationError(f"Purchase Order {purchase_order} has no line(s) {', '.join(sorted(wanted))}")
|
|
177
|
+
else:
|
|
178
|
+
chosen = [row for row in rows if flt(row.get("qty")) > flt(row.get("received_qty")) + EPSILON]
|
|
179
|
+
if not chosen:
|
|
180
|
+
raise ValidationError(f"Purchase Order {purchase_order} has no open lines to confirm")
|
|
181
|
+
if confirmed_qty is not None:
|
|
182
|
+
if len(chosen) != 1:
|
|
183
|
+
raise ValidationError("confirmed_qty applies to one line: name the line")
|
|
184
|
+
if not flt(confirmed_qty) > 0 or flt(confirmed_qty) > flt(chosen[0].get("qty")) + EPSILON:
|
|
185
|
+
raise ValidationError("confirmed_qty must be positive and at most the ordered qty")
|
|
186
|
+
stamp = now()
|
|
187
|
+
for row in chosen:
|
|
188
|
+
db.set_value("Purchase Order Item", row["name"], {
|
|
189
|
+
"confirmed_date": date,
|
|
190
|
+
"confirmed_qty": flt(confirmed_qty) if confirmed_qty is not None else None,
|
|
191
|
+
"confirmation_reference": (str(confirmation_reference).strip() or None) if confirmation_reference else None,
|
|
192
|
+
"confirmed_at": stamp, "confirmed_by": confirmed_by})
|
|
193
|
+
db.set_value("Purchase Order", purchase_order, "modified", stamp)
|
|
194
|
+
return {"purchase_order": purchase_order, "confirmed_date": date,
|
|
195
|
+
"lines": [{"purchase_order_item": row["name"], "idx": row.get("idx"), "item_code": row.get("item_code"),
|
|
196
|
+
"open_qty": flt(row.get("qty")) - flt(row.get("received_qty"))} for row in chosen]}
|
|
@@ -3366,6 +3366,23 @@ def _m055_price_decisions(db: "Database") -> None:
|
|
|
3366
3366
|
db.ensure_column("Pricing Rule", column, "TEXT")
|
|
3367
3367
|
|
|
3368
3368
|
|
|
3369
|
+
def _m056_order_progress(db: "Database") -> None:
|
|
3370
|
+
"""Returned quantities on order lines, billing of delivery notes, and
|
|
3371
|
+
supplier-confirmed dates on purchase order lines
|
|
3372
|
+
(see docs/order-progress-and-backlog.md). Existing lines get their
|
|
3373
|
+
returned / billed quantity the next time their order is touched; nothing
|
|
3374
|
+
is confirmed by the migration."""
|
|
3375
|
+
db.ensure_column("Sales Order Item", "returned_qty", "REAL DEFAULT 0")
|
|
3376
|
+
db.ensure_column("Purchase Order Item", "returned_qty", "REAL DEFAULT 0")
|
|
3377
|
+
db.ensure_column("Delivery Note Item", "billed_qty", "REAL DEFAULT 0")
|
|
3378
|
+
db.ensure_column("Sales Invoice Item", "delivery_note", "TEXT")
|
|
3379
|
+
db.ensure_column("Sales Invoice Item", "dn_detail", "TEXT")
|
|
3380
|
+
for column, definition in (("confirmed_date", "TEXT"), ("confirmed_qty", "REAL"),
|
|
3381
|
+
("confirmation_reference", "TEXT"), ("confirmed_at", "TEXT"),
|
|
3382
|
+
("confirmed_by", "TEXT")):
|
|
3383
|
+
db.ensure_column("Purchase Order Item", column, definition)
|
|
3384
|
+
|
|
3385
|
+
|
|
3369
3386
|
def _m052_access_profiles(db: "Database") -> None:
|
|
3370
3387
|
"""Access profiles narrow what a user's role allows (lambda_erp.permissions).
|
|
3371
3388
|
No profile is created and no user is assigned one: nothing changes for
|
|
@@ -3461,6 +3478,7 @@ Database.MIGRATIONS = [
|
|
|
3461
3478
|
(53, "storage_locations", _m053_storage_locations),
|
|
3462
3479
|
(54, "reservations_and_shelf_life", _m054_reservations_and_shelf_life),
|
|
3463
3480
|
(55, "price_decisions", _m055_price_decisions),
|
|
3481
|
+
(56, "order_progress", _m056_order_progress),
|
|
3464
3482
|
]
|
|
3465
3483
|
|
|
3466
3484
|
|
|
@@ -5,12 +5,16 @@ handlers for document lifecycle events without editing core files. Events are
|
|
|
5
5
|
named ``"<DocType>:<phase>"`` where phase is one of:
|
|
6
6
|
|
|
7
7
|
before_save / after_save
|
|
8
|
-
before_submit / after_submit
|
|
9
|
-
before_cancel / after_cancel
|
|
8
|
+
before_submit / on_submit / after_submit
|
|
9
|
+
before_cancel / on_cancel / after_cancel
|
|
10
10
|
|
|
11
11
|
Semantics (see docs/core-extension-architecture.md):
|
|
12
12
|
- ``before_*`` fire inside the document's transaction — a raising handler
|
|
13
13
|
aborts and rolls back the operation (use for extra validation / guards).
|
|
14
|
+
- ``on_submit`` / ``on_cancel`` fire inside the transaction too, after the
|
|
15
|
+
document has posted (or reversed) its ledgers and order progress has been
|
|
16
|
+
recalculated — the place for a follow-up step that must succeed or fail
|
|
17
|
+
together with the document. A raising handler rolls everything back.
|
|
14
18
|
- ``after_*`` fire after the change is committed and durable — use for
|
|
15
19
|
side-effects (notifications, external sync). A raising ``after_*`` handler
|
|
16
20
|
propagates but does NOT undo the committed voucher.
|
|
@@ -410,6 +410,9 @@ class Document:
|
|
|
410
410
|
from lambda_erp.workflow import refresh_order_progress
|
|
411
411
|
refresh_order_progress(self)
|
|
412
412
|
reservation.finish_guard(self, reserved)
|
|
413
|
+
# Posted, progress recalculated, still inside the transaction:
|
|
414
|
+
# a raising handler rolls the whole submit back.
|
|
415
|
+
run_hooks(f"{self.DOCTYPE}:on_submit", self)
|
|
413
416
|
except Exception:
|
|
414
417
|
self._data, self._children, self._persisted, self._loaded_modified = snapshot
|
|
415
418
|
raise
|
|
@@ -441,6 +444,7 @@ class Document:
|
|
|
441
444
|
self.on_cancel()
|
|
442
445
|
refresh_order_progress(self)
|
|
443
446
|
reservation.finish_guard(self, reserved, cancelling=True)
|
|
447
|
+
run_hooks(f"{self.DOCTYPE}:on_cancel", self)
|
|
444
448
|
except Exception:
|
|
445
449
|
self._data, self._children, self._persisted, self._loaded_modified = snapshot
|
|
446
450
|
raise
|
|
@@ -244,3 +244,61 @@ def make_delivery_return(dn_name):
|
|
|
244
244
|
))
|
|
245
245
|
|
|
246
246
|
return return_dn
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def make_sales_invoice_from_delivery_note(dn_name):
|
|
250
|
+
"""Bill what a delivery note delivered and has not been billed yet.
|
|
251
|
+
|
|
252
|
+
Deliver first, invoice afterwards: the invoice lines point back to the
|
|
253
|
+
delivery note lines (and to the order lines behind them), carry the
|
|
254
|
+
delivered price, and do not move stock again."""
|
|
255
|
+
from lambda_erp.accounting.sales_invoice import SalesInvoice
|
|
256
|
+
from lambda_erp.controllers.defaults import derived_line_pricing_fields
|
|
257
|
+
|
|
258
|
+
note = DeliveryNote.load(dn_name)
|
|
259
|
+
if note.docstatus != 1:
|
|
260
|
+
raise ValidationError("Delivery Note must be submitted before creating a Sales Invoice")
|
|
261
|
+
if note.is_return:
|
|
262
|
+
raise ValidationError("A return delivery is credited from the original invoice, not invoiced")
|
|
263
|
+
|
|
264
|
+
invoice = SalesInvoice(
|
|
265
|
+
customer=note.customer,
|
|
266
|
+
customer_name=note.customer_name,
|
|
267
|
+
company=note.company,
|
|
268
|
+
currency=note.currency,
|
|
269
|
+
conversion_rate=note.conversion_rate,
|
|
270
|
+
posting_date=nowdate(),
|
|
271
|
+
update_stock=0,
|
|
272
|
+
)
|
|
273
|
+
for item in note.get("items"):
|
|
274
|
+
unbilled = flt(item.get("qty")) - flt(item.get("billed_qty"))
|
|
275
|
+
if unbilled <= 0:
|
|
276
|
+
continue
|
|
277
|
+
invoice.append("items", _dict(
|
|
278
|
+
**derived_line_pricing_fields(item),
|
|
279
|
+
item_code=item.get("item_code"),
|
|
280
|
+
item_name=item.get("item_name"),
|
|
281
|
+
description=item.get("description"),
|
|
282
|
+
qty=unbilled,
|
|
283
|
+
uom=item.get("uom"),
|
|
284
|
+
rate=item.get("rate"),
|
|
285
|
+
price_list_rate=item.get("price_list_rate"),
|
|
286
|
+
discount_percentage=item.get("discount_percentage"),
|
|
287
|
+
discount_amount=item.get("discount_amount"),
|
|
288
|
+
warehouse=item.get("warehouse"),
|
|
289
|
+
sales_order=item.get("against_sales_order"),
|
|
290
|
+
sales_order_item=item.get("so_detail"),
|
|
291
|
+
delivery_note=note.name,
|
|
292
|
+
dn_detail=item.get("name"),
|
|
293
|
+
))
|
|
294
|
+
if not invoice.get("items"):
|
|
295
|
+
raise ValidationError(f"Delivery Note {note.name} is already billed in full")
|
|
296
|
+
for tax in note.get("taxes") or []:
|
|
297
|
+
invoice.append("taxes", _dict(
|
|
298
|
+
charge_type=tax.get("charge_type"),
|
|
299
|
+
account_head=tax.get("account_head"),
|
|
300
|
+
description=tax.get("description"),
|
|
301
|
+
rate=tax.get("rate"),
|
|
302
|
+
tax_amount=0,
|
|
303
|
+
))
|
|
304
|
+
return invoice
|
|
@@ -16,6 +16,14 @@ ORDER_REFERENCES = {
|
|
|
16
16
|
'Purchase Invoice': ('Purchase Order', 'purchase_order', 'purchase_order_item', 'supplier'),
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
def register_order_reference(doctype, order_type, parent_field, line_field, party_field):
|
|
20
|
+
"""Plugin seam: a document type whose lines fulfil or bill order lines.
|
|
21
|
+
Its lines name the order in `parent_field` and the order line in
|
|
22
|
+
`line_field`; quantities are then checked against the order line like
|
|
23
|
+
those of the built-in documents."""
|
|
24
|
+
ORDER_REFERENCES[doctype] = (order_type, parent_field, line_field, party_field)
|
|
25
|
+
|
|
26
|
+
|
|
19
27
|
CUSTOMER_BUSINESS_TYPES = {'Quotation', 'Proposal', 'Sales Order', 'Sales Invoice',
|
|
20
28
|
'Delivery Note', 'POS Invoice', 'Reservation', 'Subscription'}
|
|
21
29
|
|
|
@@ -83,8 +91,9 @@ def validate_document_requirements(doc):
|
|
|
83
91
|
if missing(doc.get(field)):
|
|
84
92
|
raise ValidationError(f"{doc.DOCTYPE}: {field.replace('_', ' ').title()} is required")
|
|
85
93
|
validate_order_references(doc)
|
|
86
|
-
from lambda_erp.workflow import validate_order_quantities
|
|
94
|
+
from lambda_erp.workflow import validate_order_quantities, validate_delivery_billing
|
|
87
95
|
validate_order_quantities(doc)
|
|
96
|
+
validate_delivery_billing(doc)
|
|
88
97
|
if doc.DOCTYPE not in TRANSACTION_TYPES:
|
|
89
98
|
return
|
|
90
99
|
if missing(doc.get('company')):
|
|
@@ -10,6 +10,12 @@ RETURN_TYPES = {'Delivery Note', 'Purchase Receipt', 'Sales Invoice', 'Purchase
|
|
|
10
10
|
EPSILON = 1e-9
|
|
11
11
|
|
|
12
12
|
|
|
13
|
+
def register_return_type(doctype):
|
|
14
|
+
"""Plugin seam: a document type that supports returns (is_return /
|
|
15
|
+
return_against with negative quantities), checked like the built-in ones."""
|
|
16
|
+
RETURN_TYPES.add(doctype)
|
|
17
|
+
|
|
18
|
+
|
|
13
19
|
def lock_workflow_references(doc):
|
|
14
20
|
"""Serialize checks against the same original/order, including cancel."""
|
|
15
21
|
db = get_db()
|
|
@@ -25,6 +31,9 @@ def lock_workflow_references(doc):
|
|
|
25
31
|
if rule:
|
|
26
32
|
table, parent, _, _ = rule
|
|
27
33
|
refs.update((table, row[parent]) for row in doc.get('items') if row.get(parent))
|
|
34
|
+
if doc.DOCTYPE == 'Sales Invoice':
|
|
35
|
+
# Invoices that bill a delivery note are checked against it.
|
|
36
|
+
refs.update(('Delivery Note', row['delivery_note']) for row in doc.get('items') if row.get('delivery_note'))
|
|
28
37
|
for table, name in sorted(refs):
|
|
29
38
|
if db.dialect == 'postgres':
|
|
30
39
|
db.sql(f'SELECT name FROM "{table}" WHERE name = ? FOR UPDATE', [name])
|
|
@@ -147,6 +156,81 @@ def validate_return(doc):
|
|
|
147
156
|
raise ValidationError(f'Return qty ({qty}) for {key[0]} exceeds remaining returnable qty ({remaining}; already returned {returned[key]})')
|
|
148
157
|
|
|
149
158
|
|
|
159
|
+
def _sum_returned(doctype, line_field, line, *, stock_only=False):
|
|
160
|
+
"""Quantity that came back on returns (positive number)."""
|
|
161
|
+
db = get_db()
|
|
162
|
+
return -flt(db.sql(
|
|
163
|
+
f'SELECT COALESCE(SUM(i.qty), 0) AS qty FROM "{doctype} Item" i '
|
|
164
|
+
f'JOIN "{doctype}" p ON p.name = i.parent WHERE i."{line_field}" = ? '
|
|
165
|
+
'AND p.docstatus = 1 AND COALESCE(p.is_return, 0) = 1 AND i.qty < 0'
|
|
166
|
+
+ (' AND p.update_stock = 1' if stock_only else '') + _goods_returns(doctype),
|
|
167
|
+
[line])[0]['qty'])
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def validate_delivery_billing(doc):
|
|
171
|
+
"""A Sales Invoice line that bills a delivery note line (delivery_note /
|
|
172
|
+
dn_detail): the delivery exists and matches, the invoice does not move
|
|
173
|
+
the goods a second time, and no more is billed than was delivered."""
|
|
174
|
+
if doc.DOCTYPE != 'Sales Invoice':
|
|
175
|
+
return
|
|
176
|
+
db = get_db()
|
|
177
|
+
if 'dn_detail' not in db._get_table_columns('Sales Invoice Item'):
|
|
178
|
+
return
|
|
179
|
+
requested = defaultdict(float)
|
|
180
|
+
for idx, row in enumerate(doc.get('items') or [], 1):
|
|
181
|
+
note, line = row.get('delivery_note'), row.get('dn_detail')
|
|
182
|
+
if not note and not line:
|
|
183
|
+
continue
|
|
184
|
+
if not note or not line:
|
|
185
|
+
raise ValidationError(f'Sales Invoice row {idx}: delivery_note and dn_detail must be supplied together')
|
|
186
|
+
if flt(doc.get('update_stock')):
|
|
187
|
+
raise ValidationError(
|
|
188
|
+
'A Sales Invoice that bills a delivery note cannot update stock: the delivery already moved the goods')
|
|
189
|
+
if flt(doc.get('is_return')):
|
|
190
|
+
continue # a credit note is checked against its original invoice
|
|
191
|
+
parent = db.get_value('Delivery Note', note, ['docstatus', 'customer', 'company', 'is_return'])
|
|
192
|
+
detail = db.get_value('Delivery Note Item', line, ['parent', 'item_code', 'qty'])
|
|
193
|
+
if not parent or parent.get('docstatus') != 1 or flt(parent.get('is_return')):
|
|
194
|
+
raise ValidationError(f'Sales Invoice row {idx}: Delivery Note {note} must be a submitted delivery')
|
|
195
|
+
if not detail or detail.get('parent') != note or detail.get('item_code') != row.get('item_code'):
|
|
196
|
+
raise ValidationError(f'Sales Invoice row {idx}: the delivery note line must belong to {note} and carry the same item')
|
|
197
|
+
if parent.get('customer') != doc.get('customer') or parent.get('company') != doc.get('company'):
|
|
198
|
+
raise ValidationError(f'Sales Invoice row {idx}: Customer and Company must match Delivery Note {note}')
|
|
199
|
+
requested[line] += flt(row.get('qty'))
|
|
200
|
+
for line, qty in requested.items():
|
|
201
|
+
delivered = flt(db.get_value('Delivery Note Item', line, 'qty'))
|
|
202
|
+
billed = _sum_line('Sales Invoice', 'dn_detail', line, exclude=doc.name)
|
|
203
|
+
if billed + qty > delivered + EPSILON:
|
|
204
|
+
raise ValidationError(
|
|
205
|
+
f'Sales Invoice: Qty exceeds what is left to bill of the delivery ({max(0, delivered - billed):g}); '
|
|
206
|
+
f'already billed {billed:g} of {delivered:g} delivered')
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def refresh_delivery_billing(doc):
|
|
210
|
+
"""billed_qty per delivery note line and the note's per_billed / status,
|
|
211
|
+
recalculated from the submitted invoices that bill it."""
|
|
212
|
+
if doc.DOCTYPE != 'Sales Invoice':
|
|
213
|
+
return
|
|
214
|
+
db = get_db()
|
|
215
|
+
if 'dn_detail' not in db._get_table_columns('Sales Invoice Item'):
|
|
216
|
+
return
|
|
217
|
+
for note in sorted({row['delivery_note'] for row in doc.get('items') or [] if row.get('delivery_note')}):
|
|
218
|
+
if db.dialect == 'postgres':
|
|
219
|
+
db.sql('SELECT name FROM "Delivery Note" WHERE name = ? FOR UPDATE', [note])
|
|
220
|
+
total = billed = 0
|
|
221
|
+
for line in db.get_all('Delivery Note Item', filters={'parent': note}, fields=['name', 'qty']):
|
|
222
|
+
done = _sum_line('Sales Invoice', 'dn_detail', line.name)
|
|
223
|
+
db.set_value('Delivery Note Item', line.name, 'billed_qty', done)
|
|
224
|
+
total += flt(line.qty)
|
|
225
|
+
billed += min(done, flt(line.qty))
|
|
226
|
+
per_billed = flt(billed / total * 100, 2) if total else 0
|
|
227
|
+
values = {'per_billed': per_billed}
|
|
228
|
+
if db.get_value('Delivery Note', note, 'docstatus') == 1:
|
|
229
|
+
# Submitted until an invoice bills it; then what is left to do.
|
|
230
|
+
values['status'] = 'Completed' if per_billed >= 100 else 'To Bill' if billed > EPSILON else 'Submitted'
|
|
231
|
+
db.set_value('Delivery Note', note, values)
|
|
232
|
+
|
|
233
|
+
|
|
150
234
|
def _sum_line(doctype, line_field, line, *, exclude=None, stock_only=False):
|
|
151
235
|
db = get_db()
|
|
152
236
|
return flt(db.sql(
|
|
@@ -265,6 +349,7 @@ def refresh_order_progress(doc):
|
|
|
265
349
|
if not db._in_transaction:
|
|
266
350
|
with db.atomic():
|
|
267
351
|
return refresh_order_progress(doc)
|
|
352
|
+
refresh_delivery_billing(doc)
|
|
268
353
|
if doc.DOCTYPE in {'Sales Order', 'Purchase Order'}:
|
|
269
354
|
orders = {(doc.DOCTYPE, doc.name)}
|
|
270
355
|
elif doc.DOCTYPE in ORDER_REFERENCES:
|
|
@@ -284,7 +369,12 @@ def refresh_order_progress(doc):
|
|
|
284
369
|
for row in lines:
|
|
285
370
|
delivered = _sum_line(movement, move_line, row.name) + _sum_line(invoice, invoice_line, row.name, stock_only=True)
|
|
286
371
|
invoiced = _sum_line(invoice, invoice_line, row.name)
|
|
287
|
-
|
|
372
|
+
values = {progress: delivered, 'billed_qty': invoiced}
|
|
373
|
+
if 'returned_qty' in row:
|
|
374
|
+
# Net of returns already; this says how much of it came back.
|
|
375
|
+
values['returned_qty'] = (_sum_returned(movement, move_line, row.name)
|
|
376
|
+
+ _sum_returned(invoice, invoice_line, row.name, stock_only=True))
|
|
377
|
+
db.set_value(kind + ' Item', row.name, values)
|
|
288
378
|
total += flt(row.qty)
|
|
289
379
|
moved += delivered
|
|
290
380
|
billed += invoiced
|
|
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
|