lambda-erp 1.4.3__tar.gz → 1.4.5__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.3 → lambda_erp-1.4.5}/PKG-INFO +1 -1
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/chat.py +26 -3
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/masters.py +40 -1
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/reports.py +93 -1
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/services.py +4 -1
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/frontend/src/api/client.ts +6 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/pos_invoice.py +1 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/purchase_invoice.py +17 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/sales_invoice.py +3 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/database.py +73 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/master_integrity.py +2 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/stock/delivery_note.py +1 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/stock/purchase_receipt.py +3 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/stock/stock_entry.py +33 -5
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/stock/stock_ledger.py +153 -3
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/validation.py +2 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/workflow.py +102 -9
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/pyproject.toml +1 -1
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/.gitignore +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/LICENSE +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/README.md +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/attachments.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/auth.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/bootstrap.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/chat_links.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/demo_limits.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/deps.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/erp_context.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/errors.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/list_values.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/llm_provider.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/main.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/mcp_oauth.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/mentions.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/menu_layout.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/oauth.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/pdf.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/pdf_contract.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/pdf_exports.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/pdf_fonts.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/pdf_pages.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/pdf_profiles.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/pdf_templates.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/providers.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/record_notes.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/remarks_md.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/accounting.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/actions.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/admin.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/analytics.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/availability.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/bank_statements.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/chat_api.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/documents.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/mcp.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/pdf_templates.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/proposals.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/routers/setup.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/templates/_proposal_totals.html +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/templates/_record_base.html +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/templates/delivery_note.html +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/templates/document.html +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/templates/proposal.html +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/templates/record.html +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/templates/reservation.html +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/time_filters.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/tool_permissions.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/api/write_context.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/docs/agents/README.md +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/frontend/LICENSE +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/frontend/README.md +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/bank_account.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/bank_reconciliation.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/bank_statement_import.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/bank_transaction.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/budget.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/camt.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/chart_of_accounts.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/general_ledger.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/journal_entry.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/payment_entry.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/revaluation.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/settlement.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/engine.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/pack.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/ch.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/de_common.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/de_skr03.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/de_skr04.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/packs/generic.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/profiles.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/setup/spine.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/accounting/subscription.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/assets/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/assets/asset.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/assets/lifecycle.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/assets/reservation.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/buying/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/buying/purchase_order.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/controllers/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/controllers/currency.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/controllers/defaults.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/controllers/item_price.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/controllers/item_prices.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/controllers/pricing_rule.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/controllers/taxes_and_totals.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/exceptions.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/hooks.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/model.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/selling/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/selling/proposal.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/selling/quotation.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/selling/sales_order.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/simulation.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/stock/__init__.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/timestamps.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/lambda_erp/utils.py +0 -0
- {lambda_erp-1.4.3 → lambda_erp-1.4.5}/terraform/README.md +0 -0
|
@@ -878,8 +878,8 @@ TOOLS = [
|
|
|
878
878
|
"parameters": {
|
|
879
879
|
"type": "object",
|
|
880
880
|
"properties": {
|
|
881
|
-
"report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
|
|
882
|
-
"filters": {"type": "object", "description": "Optional filters: company, account, from_date, to_date, item_code, warehouse. 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": {}},
|
|
881
|
+
"report_type": {"type": "string", "enum": ["trial-balance", "general-ledger", "stock-balance", "batch-stock", "batch-movements", "dashboard-summary", "profit-and-loss", "balance-sheet", "ar-aging", "ap-aging"]},
|
|
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; 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"],
|
|
885
885
|
},
|
|
@@ -1963,6 +1963,16 @@ def _handle_get_report(args):
|
|
|
1963
1963
|
elif report_type == "stock-balance":
|
|
1964
1964
|
from api.routers.reports import _stock_balance
|
|
1965
1965
|
return _stock_balance(db, filters.get("item_code"), filters.get("warehouse"))
|
|
1966
|
+
elif report_type == "batch-stock":
|
|
1967
|
+
from api.routers.reports import _batch_stock
|
|
1968
|
+
return _batch_stock(db, filters.get("item_code"), filters.get("warehouse"), filters.get("batch_no"),
|
|
1969
|
+
filters.get("item_prefix"), filters.get("expiring_before"),
|
|
1970
|
+
bool(filters.get("include_empty")))
|
|
1971
|
+
elif report_type == "batch-movements":
|
|
1972
|
+
from api.routers.reports import _batch_movements
|
|
1973
|
+
if not filters.get("batch_no"):
|
|
1974
|
+
return {"error": "batch-movements needs filters.batch_no"}
|
|
1975
|
+
return _batch_movements(db, filters.get("batch_no"), filters.get("item_code"), filters.get("warehouse"))
|
|
1966
1976
|
elif report_type == "dashboard-summary":
|
|
1967
1977
|
from api.routers.reports import _dashboard_summary
|
|
1968
1978
|
return _dashboard_summary(db, filters.get("company"))
|
|
@@ -2865,6 +2875,8 @@ Returns use the SAME document type with negative quantities and `is_return=1`. C
|
|
|
2865
2875
|
- **Delivery Note Return:** Convert a submitted Delivery Note. Stock comes back into the warehouse, reverses COGS entries.
|
|
2866
2876
|
- **Purchase Receipt Return:** Convert a submitted Purchase Receipt. Stock goes back out, reverses stock-in-hand entries.
|
|
2867
2877
|
|
|
2878
|
+
- **Price correction / goodwill credit (no goods come back):** convert the invoice to a return as above, then on the draft set `amount_only=1` and set each line's `rate` to the amount credited per unit (qty stays negative: the units the credit is for). An amount-only credit or debit note never moves stock (also when the original had update_stock=1) and leaves billed and returnable quantities alone, so the goods can still be returned later. Sales Invoice and Purchase Invoice only. Do NOT use a plain return for a price correction.
|
|
2879
|
+
|
|
2868
2880
|
To create a return: use convert_document with the SAME doctype as both source and target.
|
|
2869
2881
|
Example: convert_document(doctype="sales-invoice", name="SINV-0001", target_doctype="Sales Invoice")
|
|
2870
2882
|
|
|
@@ -2877,6 +2889,15 @@ For a complete sales return (financial + stock): create and submit both a Credit
|
|
|
2877
2889
|
- **Material Receipt:** Manual adjustment that adds stock (found stock, inventory count corrections). Posts Dr Stock In Hand / Cr Stock Adjustment. Not for purchased goods — use Purchase Receipt or Purchase Invoice with update_stock=1 for those. Not for opening balances — use Opening Stock.
|
|
2878
2890
|
- **Material Issue:** Removes stock for write-offs or internal consumption. Posts Dr Stock Adjustment / Cr Stock In Hand.
|
|
2879
2891
|
- **Material Transfer:** Moves stock between warehouses. No GL impact.
|
|
2892
|
+
- **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.
|
|
2893
|
+
|
|
2894
|
+
### Batches (lot numbers)
|
|
2895
|
+
- An item with `has_batch_no=1` is batch-tracked; `has_expiry_date=1` additionally requires an expiry date on each batch. Switch these on the Item master.
|
|
2896
|
+
- Every stock-moving line of a tracked item needs `batch_no` (Stock Entry, Delivery Note, Purchase Receipt, and invoices with update_stock=1). One batch per line: a quantity from two batches is two lines. Drafts may be saved without it; submit is refused until every such line has one.
|
|
2897
|
+
- Receiving lines (Purchase Receipt, Purchase Invoice with update_stock, Stock Entry receipt/opening) create a new batch automatically: give `batch_no` and, for items with expiry dates, `expiry_date`. Outgoing lines must name an existing batch with enough quantity in that warehouse — check with the batch-stock report first. Never invent a batch number or expiry date; ask.
|
|
2898
|
+
- Quantities are checked per batch: 10 in stock but only 2 in the named batch means a line for 3 is refused.
|
|
2899
|
+
- A return must name a batch that was on the original document, and at most the quantity of it that was delivered/received.
|
|
2900
|
+
- The `batch` master (search_masters master_type="batch") has one record per item + batch label.
|
|
2880
2901
|
|
|
2881
2902
|
### Assets & Reservations (equipment you OWN and hire out — not stock you sell)
|
|
2882
2903
|
Use these only for items flagged `is_asset_tracked` on the Item master. Neither posts GL or stock entries: an owned machine going out on hire is not a sale of inventory, so the books are untouched until you invoice the hire through the normal selling cycle.
|
|
@@ -2933,6 +2954,8 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
|
|
|
2933
2954
|
- **ar-aging** — Outstanding receivables bucketed by overdue days (Current, 1-30, 31-60, 61-90, 90+). Filters: company, as_of_date.
|
|
2934
2955
|
- **ap-aging** — Outstanding payables bucketed by overdue days. Filters: company, as_of_date.
|
|
2935
2956
|
- **stock-balance** — Inventory quantities and valuations. Filters: item_code, warehouse.
|
|
2957
|
+
- **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.
|
|
2958
|
+
- **batch-movements** — Every stock movement of a batch with document, line and customer/supplier: where it came from and who received it (recalls). Filters: batch_no (required), item_code, warehouse.
|
|
2936
2959
|
- **dashboard-summary** — KPI overview (revenue, receivables, payables, stock value).
|
|
2937
2960
|
- **Custom analytics drafts** — reserved for when the user **explicitly asks
|
|
2938
2961
|
for** a chart, graph, trend, pivot, breakdown, or saved report, or when the
|
|
@@ -2962,7 +2985,7 @@ Master records CAN be deleted — use the `delete_master` tool (ADMIN role only)
|
|
|
2962
2985
|
|
|
2963
2986
|
## Stock Entry specifics
|
|
2964
2987
|
When creating a stock-entry, the `data` object MUST include:
|
|
2965
|
-
- `stock_entry_type`: "Opening Stock", "Material Receipt", "Material Issue",
|
|
2988
|
+
- `stock_entry_type`: "Opening Stock", "Material Receipt", "Material Issue", "Material Transfer", or "Batch Assignment"
|
|
2966
2989
|
- `company`, `posting_date`
|
|
2967
2990
|
- `items` array where each item uses `basic_rate` (NOT `rate`) and warehouse fields:
|
|
2968
2991
|
- Opening Stock: items need `t_warehouse` (target). Set `to_warehouse` on the parent too.
|
|
@@ -4,7 +4,7 @@ import secrets
|
|
|
4
4
|
|
|
5
5
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
|
6
6
|
from lambda_erp.database import get_db
|
|
7
|
-
from lambda_erp.utils import _dict, now
|
|
7
|
+
from lambda_erp.utils import _dict, flt, now
|
|
8
8
|
# The per-type registries live in api.services so `register_master` can extend
|
|
9
9
|
# them; imported here (not moved) so existing `from api.routers.masters import
|
|
10
10
|
# MASTER_IDENTITY_ALIAS`-style imports keep working.
|
|
@@ -59,6 +59,10 @@ DELETE_REFERENCE_CHECKS = {
|
|
|
59
59
|
('SELECT 1 FROM "Subscription" WHERE company = ? LIMIT 1', "subscription"),
|
|
60
60
|
('SELECT 1 FROM "Bank Transaction" t JOIN "Bank Account" a ON a.name = t.bank_account WHERE a.company = ? LIMIT 1', "bank transaction"),
|
|
61
61
|
],
|
|
62
|
+
"batch": [
|
|
63
|
+
('SELECT 1 FROM "Stock Ledger Entry" s JOIN "Batch" b ON b.item_code = s.item_code '
|
|
64
|
+
'AND b.batch_no = s.batch_no WHERE b.name = ? LIMIT 1', "stock ledger entry"),
|
|
65
|
+
],
|
|
62
66
|
"customer": [
|
|
63
67
|
('SELECT 1 FROM "Quotation" WHERE customer = ? LIMIT 1', "quotation"),
|
|
64
68
|
('SELECT 1 FROM "Sales Order" WHERE customer = ? LIMIT 1', "sales order"),
|
|
@@ -211,6 +215,7 @@ MASTER_LINK_FIELDS = {
|
|
|
211
215
|
'warehouse': {'company': 'Company', 'account': 'Account', 'parent_warehouse': 'Warehouse'},
|
|
212
216
|
'account': {'company': 'Company', 'parent_account': 'Account'},
|
|
213
217
|
'cost-center': {'company': 'Company', 'parent_cost_center': 'Cost Center'},
|
|
218
|
+
'batch': {'item_code': 'Item'},
|
|
214
219
|
}
|
|
215
220
|
|
|
216
221
|
|
|
@@ -272,12 +277,46 @@ def _validate_master_input(master_type, doctype, data, name=None):
|
|
|
272
277
|
raise ValidationError(f'{doctype}: {field} must reference an existing {table}')
|
|
273
278
|
if master_type == 'item' and data.get('valuation_method') not in (None, '', 'Moving Average'):
|
|
274
279
|
raise ValidationError('Item: valuation_method must be Moving Average; it is the only valuation the stock ledger implements')
|
|
280
|
+
if master_type == 'item':
|
|
281
|
+
_validate_item_batch_flags(db, merged, name)
|
|
282
|
+
if master_type == 'batch':
|
|
283
|
+
_validate_batch(db, merged, name)
|
|
275
284
|
if master_type == 'company' and data.get('default_sales_tax_template'):
|
|
276
285
|
template = db.get_value('Tax Template', data['default_sales_tax_template'], ['company', 'tax_type'])
|
|
277
286
|
if not template or template['company'] != (name or data.get('name')) or template['tax_type'] != 'Sales':
|
|
278
287
|
raise ValidationError('Default sales tax template must be a Sales template belonging to this Company')
|
|
279
288
|
|
|
280
289
|
|
|
290
|
+
def _validate_item_batch_flags(db, merged, name):
|
|
291
|
+
"""Batch tracking can be switched on at any time (stock that is already
|
|
292
|
+
there stays without a batch until a Batch Assignment). It cannot be
|
|
293
|
+
switched off while the item has batches in the stock ledger."""
|
|
294
|
+
tracked = bool(flt(merged.get('has_batch_no')))
|
|
295
|
+
if flt(merged.get('has_expiry_date')) and not tracked:
|
|
296
|
+
raise ValidationError('Item: has_expiry_date needs has_batch_no; the expiry date belongs to the batch')
|
|
297
|
+
stock_item = merged.get('is_stock_item')
|
|
298
|
+
if tracked and stock_item is not None and not flt(stock_item):
|
|
299
|
+
raise ValidationError('Item: only a stock item can be batch-tracked')
|
|
300
|
+
if name and not tracked and db.sql(
|
|
301
|
+
'SELECT 1 FROM "Stock Ledger Entry" WHERE item_code = ? AND batch_no IS NOT NULL '
|
|
302
|
+
'AND batch_no <> \'\' LIMIT 1', [name]):
|
|
303
|
+
raise ValidationError(f'Item {name}: batch tracking cannot be switched off, the stock ledger has batches of it')
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _validate_batch(db, merged, name):
|
|
307
|
+
for field in ('item_code', 'batch_no'):
|
|
308
|
+
if missing(merged.get(field)):
|
|
309
|
+
raise ValidationError(f'Batch: {field} is required')
|
|
310
|
+
item = db.get_value('Item', merged['item_code'], ['has_batch_no', 'has_expiry_date'])
|
|
311
|
+
if not item or not flt(item.get('has_batch_no')):
|
|
312
|
+
raise ValidationError(f'Batch: item {merged["item_code"]} is not batch-tracked (set has_batch_no on the item first)')
|
|
313
|
+
if flt(item.get('has_expiry_date')) and missing(merged.get('expiry_date')):
|
|
314
|
+
raise ValidationError(f'Batch: expiry_date is required, item {merged["item_code"]} has expiry dates')
|
|
315
|
+
twin = db.get_value('Batch', {'item_code': merged['item_code'], 'batch_no': merged['batch_no']}, 'name')
|
|
316
|
+
if twin and twin != name:
|
|
317
|
+
raise ValidationError(f'Batch {merged["batch_no"]} already exists for item {merged["item_code"]} ({twin})')
|
|
318
|
+
|
|
319
|
+
|
|
281
320
|
@router.get('/company/{name}/sales-tax-templates')
|
|
282
321
|
def company_sales_tax_templates(name: str, _user: dict = _viewer):
|
|
283
322
|
"""Choices for the company default, using existing tax templates only."""
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from datetime import date
|
|
4
4
|
|
|
5
|
-
from fastapi import APIRouter, Depends, Query
|
|
5
|
+
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
6
6
|
from lambda_erp.database import get_db
|
|
7
7
|
from lambda_erp.utils import flt, nowdate
|
|
8
8
|
from lambda_erp.controllers.currency import get_exchange_rate
|
|
@@ -381,6 +381,98 @@ def stock_balance(
|
|
|
381
381
|
return _stock_balance(get_db(), item_code, warehouse)
|
|
382
382
|
|
|
383
383
|
|
|
384
|
+
def _batch_stock(db, item_code=None, warehouse=None, batch_no=None, item_prefix=None,
|
|
385
|
+
expiring_before=None, include_empty=False):
|
|
386
|
+
"""Stock per item x warehouse x batch with the batch's expiry date.
|
|
387
|
+
|
|
388
|
+
`batch_no` is the label as printed on the goods: the same label can exist
|
|
389
|
+
on several items, so it can return several rows. Stock of a tracked item
|
|
390
|
+
that has no batch yet appears with an empty batch_no."""
|
|
391
|
+
where, params = [], []
|
|
392
|
+
for column, value in (("d.item_code", item_code), ("d.warehouse", warehouse), ("d.batch_no", batch_no)):
|
|
393
|
+
if value:
|
|
394
|
+
where.append(f"{column} = ?")
|
|
395
|
+
params.append(value)
|
|
396
|
+
if item_prefix:
|
|
397
|
+
where.append("d.item_code LIKE ?")
|
|
398
|
+
params.append(item_prefix.replace("%", "") + "%")
|
|
399
|
+
if expiring_before:
|
|
400
|
+
where.append("b.expiry_date IS NOT NULL AND b.expiry_date <= ?")
|
|
401
|
+
params.append(expiring_before)
|
|
402
|
+
if not include_empty:
|
|
403
|
+
where.append("d.actual_qty <> 0")
|
|
404
|
+
if not batch_no:
|
|
405
|
+
# Untracked items have no batches to show; their stock is in stock-balance.
|
|
406
|
+
where.append("(d.batch_no <> '' OR COALESCE(i.has_batch_no, 0) = 1)")
|
|
407
|
+
rows = db.sql(
|
|
408
|
+
'SELECT d.item_code, i.item_name, d.warehouse, d.batch_no, b.name AS batch, b.expiry_date, '
|
|
409
|
+
'COALESCE(b.disabled, 0) AS batch_disabled, d.actual_qty '
|
|
410
|
+
'FROM "Stock Balance Detail" d '
|
|
411
|
+
'LEFT JOIN "Item" i ON i.name = d.item_code '
|
|
412
|
+
'LEFT JOIN "Batch" b ON b.item_code = d.item_code AND b.batch_no = d.batch_no '
|
|
413
|
+
+ (f"WHERE {' AND '.join(where)} " if where else "")
|
|
414
|
+
+ 'ORDER BY d.item_code, b.expiry_date, d.batch_no, d.warehouse', params)
|
|
415
|
+
return {"rows": [{**dict(row), "actual_qty": flt(row["actual_qty"])} for row in rows]}
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@router.get("/batch-stock")
|
|
419
|
+
def batch_stock(
|
|
420
|
+
item_code: str | None = None,
|
|
421
|
+
warehouse: str | None = None,
|
|
422
|
+
batch_no: str | None = None,
|
|
423
|
+
item_prefix: str | None = None,
|
|
424
|
+
expiring_before: str | None = None,
|
|
425
|
+
include_empty: bool = False,
|
|
426
|
+
):
|
|
427
|
+
return _batch_stock(get_db(), item_code, warehouse, batch_no, item_prefix, expiring_before, include_empty)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
_BATCH_PARTY = {
|
|
431
|
+
"Delivery Note": ("customer", "Customer"), "Sales Invoice": ("customer", "Customer"),
|
|
432
|
+
"POS Invoice": ("customer", "Customer"), "Purchase Receipt": ("supplier", "Supplier"),
|
|
433
|
+
"Purchase Invoice": ("supplier", "Supplier"),
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _batch_movements(db, batch_no=None, item_code=None, warehouse=None):
|
|
438
|
+
"""Every stock movement of a batch, oldest first, with its document, line
|
|
439
|
+
and the customer or supplier of that document: where a batch came from
|
|
440
|
+
and who received it. `batch_no` alone can match several items."""
|
|
441
|
+
if not batch_no:
|
|
442
|
+
raise HTTPException(status_code=422, detail="batch_no is required")
|
|
443
|
+
where, params = ["s.batch_no = ?"], [batch_no]
|
|
444
|
+
for column, value in (("s.item_code", item_code), ("s.warehouse", warehouse)):
|
|
445
|
+
if value:
|
|
446
|
+
where.append(f"{column} = ?")
|
|
447
|
+
params.append(value)
|
|
448
|
+
rows = db.sql(
|
|
449
|
+
'SELECT s.name, s.posting_date, s.item_code, s.warehouse, s.batch_no, s.actual_qty, '
|
|
450
|
+
's.voucher_type, s.voucher_no, s.voucher_detail_no '
|
|
451
|
+
f'FROM "Stock Ledger Entry" s WHERE {" AND ".join(where)} '
|
|
452
|
+
'ORDER BY s.posting_date, s.creation, s.name', params)
|
|
453
|
+
parties = {}
|
|
454
|
+
result = []
|
|
455
|
+
for row in rows:
|
|
456
|
+
entry = {**dict(row), "actual_qty": flt(row["actual_qty"]), "party_type": None, "party": None}
|
|
457
|
+
field = _BATCH_PARTY.get(row["voucher_type"])
|
|
458
|
+
if field:
|
|
459
|
+
key = (row["voucher_type"], row["voucher_no"])
|
|
460
|
+
if key not in parties:
|
|
461
|
+
parties[key] = db.get_value(row["voucher_type"], row["voucher_no"], field[0])
|
|
462
|
+
entry["party_type"], entry["party"] = field[1], parties[key]
|
|
463
|
+
result.append(entry)
|
|
464
|
+
return {"rows": result}
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
@router.get("/batch-movements")
|
|
468
|
+
def batch_movements(
|
|
469
|
+
batch_no: str,
|
|
470
|
+
item_code: str | None = None,
|
|
471
|
+
warehouse: str | None = None,
|
|
472
|
+
):
|
|
473
|
+
return _batch_movements(get_db(), batch_no, item_code, warehouse)
|
|
474
|
+
|
|
475
|
+
|
|
384
476
|
def _dashboard_summary(db, company=None):
|
|
385
477
|
"""Compute dashboard summary metrics."""
|
|
386
478
|
|
|
@@ -84,6 +84,8 @@ MASTER_TABLES = {
|
|
|
84
84
|
"account": ("Account", "account_name"),
|
|
85
85
|
"company": ("Company", "company_name"),
|
|
86
86
|
"cost-center": ("Cost Center", "cost_center_name"),
|
|
87
|
+
# One row per (item, batch label); the label alone is not unique.
|
|
88
|
+
"batch": ("Batch", "batch_no"),
|
|
87
89
|
}
|
|
88
90
|
|
|
89
91
|
# Auto-naming prefixes: masters created without an explicit `name` get a
|
|
@@ -94,11 +96,12 @@ MASTER_NAME_PREFIXES = {
|
|
|
94
96
|
"supplier": "SUPP",
|
|
95
97
|
"item": "ITEM",
|
|
96
98
|
"warehouse": "WH",
|
|
99
|
+
"batch": "BATCH",
|
|
97
100
|
}
|
|
98
101
|
|
|
99
102
|
# Minimum numeric suffix width for sequential plugin master ids. Core masters
|
|
100
103
|
# retain the historical three-digit form; plugins can opt into e.g. FIDX-0001.
|
|
101
|
-
MASTER_NAME_DIGITS: dict[str, int] = {}
|
|
104
|
+
MASTER_NAME_DIGITS: dict[str, int] = {"batch": 5}
|
|
102
105
|
|
|
103
106
|
# High-volume plugin masters can opt out of sequential ids. Sequential naming
|
|
104
107
|
# must inspect existing suffixes after a process restart; opaque random ids keep
|
|
@@ -555,6 +555,12 @@ export const api = {
|
|
|
555
555
|
stockBalance: (params?: Record<string, string>) =>
|
|
556
556
|
request<{ rows: any[] }>(`/reports/stock-balance${qs(params)}`),
|
|
557
557
|
|
|
558
|
+
batchStock: (params?: Record<string, string>) =>
|
|
559
|
+
request<{ rows: any[] }>(`/reports/batch-stock${qs(params)}`),
|
|
560
|
+
|
|
561
|
+
batchMovements: (params: Record<string, string>) =>
|
|
562
|
+
request<{ rows: any[] }>(`/reports/batch-movements${qs(params)}`),
|
|
563
|
+
|
|
558
564
|
// --- Rentals: availability + fleet calendar ---
|
|
559
565
|
availability: (params: { item_code: string; from: string; to: string; warehouse?: string; exclude?: string }) =>
|
|
560
566
|
request<AvailabilityResult>(`/availability${qs(params)}`),
|
|
@@ -72,6 +72,8 @@ class PurchaseInvoice(Document):
|
|
|
72
72
|
self.posting_date = nowdate()
|
|
73
73
|
|
|
74
74
|
apply_external_source_defaults(self)
|
|
75
|
+
from lambda_erp.workflow import apply_amount_only
|
|
76
|
+
apply_amount_only(self)
|
|
75
77
|
self._set_supplier_name()
|
|
76
78
|
self._set_missing_accounts()
|
|
77
79
|
set_default_currency(self, "Supplier", "supplier")
|
|
@@ -144,6 +146,20 @@ class PurchaseInvoice(Document):
|
|
|
144
146
|
if not item.get("cost_center"):
|
|
145
147
|
item["cost_center"] = default_cc
|
|
146
148
|
|
|
149
|
+
if flt(self.get("amount_only")):
|
|
150
|
+
# A price correction moves no goods, so it must not touch the
|
|
151
|
+
# stock accounts (Stock In Hand would drift from the stock ledger;
|
|
152
|
+
# SRBNB would keep a balance no receipt clears). The difference is
|
|
153
|
+
# a purchase price variance: stock adjustment, else expense.
|
|
154
|
+
variance = db.get_value("Company", self.company, "stock_adjustment_account") or default_expense
|
|
155
|
+
for item in self.get("items"):
|
|
156
|
+
account = item.get("expense_account")
|
|
157
|
+
if account and variance and (
|
|
158
|
+
account == stock_received_account
|
|
159
|
+
or db.get_value("Account", account, "account_type") == "Stock"
|
|
160
|
+
):
|
|
161
|
+
item["expense_account"] = variance
|
|
162
|
+
|
|
147
163
|
def _validate_stock_warehouses(self):
|
|
148
164
|
"""When update_stock=1, every stock-item line needs a warehouse so
|
|
149
165
|
the SLE has somewhere to put the received goods."""
|
|
@@ -458,6 +474,7 @@ def make_purchase_return(pinv_name):
|
|
|
458
474
|
expense_account=item.get("expense_account"),
|
|
459
475
|
cost_center=item.get("cost_center"),
|
|
460
476
|
warehouse=item.get("warehouse"),
|
|
477
|
+
batch_no=item.get("batch_no"),
|
|
461
478
|
purchase_order=item.get("purchase_order"),
|
|
462
479
|
purchase_order_item=item.get("purchase_order_item"),
|
|
463
480
|
))
|
|
@@ -89,6 +89,8 @@ class SalesInvoice(Document):
|
|
|
89
89
|
self.posting_date = nowdate()
|
|
90
90
|
|
|
91
91
|
apply_external_source_defaults(self)
|
|
92
|
+
from lambda_erp.workflow import apply_amount_only
|
|
93
|
+
apply_amount_only(self)
|
|
92
94
|
self._set_customer_name()
|
|
93
95
|
self._set_missing_accounts()
|
|
94
96
|
set_default_currency(self, "Customer", "customer")
|
|
@@ -456,6 +458,7 @@ def make_sales_return(sinv_name):
|
|
|
456
458
|
income_account=item.get("income_account"),
|
|
457
459
|
cost_center=item.get("cost_center"),
|
|
458
460
|
warehouse=item.get("warehouse"),
|
|
461
|
+
batch_no=item.get("batch_no"),
|
|
459
462
|
sales_order=item.get("sales_order"),
|
|
460
463
|
sales_order_item=item.get("sales_order_item"),
|
|
461
464
|
))
|
|
@@ -862,6 +862,7 @@ class Database:
|
|
|
862
862
|
is_return INTEGER DEFAULT 0,
|
|
863
863
|
return_against TEXT,
|
|
864
864
|
update_stock INTEGER DEFAULT 0,
|
|
865
|
+
amount_only INTEGER DEFAULT 0,
|
|
865
866
|
is_pos INTEGER DEFAULT 0,
|
|
866
867
|
paid_amount REAL DEFAULT 0,
|
|
867
868
|
against_income_account TEXT,
|
|
@@ -937,6 +938,7 @@ class Database:
|
|
|
937
938
|
is_return INTEGER DEFAULT 0,
|
|
938
939
|
return_against TEXT,
|
|
939
940
|
update_stock INTEGER DEFAULT 0,
|
|
941
|
+
amount_only INTEGER DEFAULT 0,
|
|
940
942
|
against_expense_account TEXT,
|
|
941
943
|
purchase_order TEXT,
|
|
942
944
|
status TEXT DEFAULT 'Draft',
|
|
@@ -3200,6 +3202,75 @@ def _m049_pricing_rule_currency(db: "Database") -> None:
|
|
|
3200
3202
|
[currencies[0]])
|
|
3201
3203
|
|
|
3202
3204
|
|
|
3205
|
+
def _m050_amount_only_returns(db: "Database") -> None:
|
|
3206
|
+
"""A credit / debit note that corrects money only (price correction): no
|
|
3207
|
+
quantity returned, no stock moved. See workflow.apply_amount_only."""
|
|
3208
|
+
for table in ("Sales Invoice", "Purchase Invoice"):
|
|
3209
|
+
db.ensure_column(table, "amount_only", "INTEGER DEFAULT 0")
|
|
3210
|
+
|
|
3211
|
+
|
|
3212
|
+
BATCH_LINE_TABLES = ("Stock Entry Detail", "Delivery Note Item", "Purchase Receipt Item",
|
|
3213
|
+
"Sales Invoice Item", "Purchase Invoice Item", "POS Invoice Item")
|
|
3214
|
+
BATCH_RECEIVING_TABLES = ("Stock Entry Detail", "Purchase Receipt Item", "Purchase Invoice Item")
|
|
3215
|
+
|
|
3216
|
+
|
|
3217
|
+
def _m051_batches(db: "Database") -> None:
|
|
3218
|
+
"""Batch-tracked stock (see docs/batches.md).
|
|
3219
|
+
|
|
3220
|
+
- Item.has_batch_no / has_expiry_date switch tracking on per item.
|
|
3221
|
+
- "Batch" is the master: one row per (item, batch label); a label alone is
|
|
3222
|
+
not unique, several items can carry the same one.
|
|
3223
|
+
- "Stock Balance Detail" is the quantity per item x warehouse x batch,
|
|
3224
|
+
maintained with every stock ledger entry. batch_no '' is stock without a
|
|
3225
|
+
batch (items that are not tracked, and stock that was there before an
|
|
3226
|
+
item was switched to tracking). Its rows always add up to "Bin".
|
|
3227
|
+
- Existing stock is backfilled into the '' rows: no batch is invented.
|
|
3228
|
+
"""
|
|
3229
|
+
db.conn.execute(db._ddl(
|
|
3230
|
+
"""CREATE TABLE IF NOT EXISTS "Batch" (
|
|
3231
|
+
name TEXT PRIMARY KEY,
|
|
3232
|
+
batch_no TEXT NOT NULL,
|
|
3233
|
+
item_code TEXT NOT NULL,
|
|
3234
|
+
expiry_date TEXT,
|
|
3235
|
+
manufacturing_date TEXT,
|
|
3236
|
+
description TEXT,
|
|
3237
|
+
disabled INTEGER DEFAULT 0,
|
|
3238
|
+
creation TEXT,
|
|
3239
|
+
modified TEXT
|
|
3240
|
+
)"""))
|
|
3241
|
+
db.conn.execute(db._ddl(
|
|
3242
|
+
'CREATE UNIQUE INDEX IF NOT EXISTS "ux_batch_item_batch_no" ON "Batch" (item_code, batch_no)'))
|
|
3243
|
+
db.conn.execute(db._ddl(
|
|
3244
|
+
"""CREATE TABLE IF NOT EXISTS "Stock Balance Detail" (
|
|
3245
|
+
name TEXT PRIMARY KEY,
|
|
3246
|
+
item_code TEXT NOT NULL,
|
|
3247
|
+
warehouse TEXT NOT NULL,
|
|
3248
|
+
batch_no TEXT NOT NULL DEFAULT '',
|
|
3249
|
+
actual_qty REAL DEFAULT 0
|
|
3250
|
+
)"""))
|
|
3251
|
+
db.conn.execute(db._ddl(
|
|
3252
|
+
'CREATE UNIQUE INDEX IF NOT EXISTS "ux_stock_balance_detail_key" '
|
|
3253
|
+
'ON "Stock Balance Detail" (item_code, warehouse, batch_no)'))
|
|
3254
|
+
db.conn.commit()
|
|
3255
|
+
for table in ("Batch", "Stock Balance Detail"):
|
|
3256
|
+
db._col_cache.pop(table, None)
|
|
3257
|
+
db._text_col_cache.pop(table, None)
|
|
3258
|
+
db.ensure_column("Item", "has_batch_no", "INTEGER DEFAULT 0")
|
|
3259
|
+
db.ensure_column("Item", "has_expiry_date", "INTEGER DEFAULT 0")
|
|
3260
|
+
for table in BATCH_LINE_TABLES:
|
|
3261
|
+
db.ensure_column(table, "batch_no", "TEXT")
|
|
3262
|
+
for table in BATCH_RECEIVING_TABLES:
|
|
3263
|
+
db.ensure_column(table, "expiry_date", "TEXT")
|
|
3264
|
+
import uuid
|
|
3265
|
+
for row in db.sql(
|
|
3266
|
+
'SELECT b.item_code, b.warehouse, b.actual_qty FROM "Bin" b WHERE NOT EXISTS ('
|
|
3267
|
+
'SELECT 1 FROM "Stock Balance Detail" d WHERE d.item_code = b.item_code AND d.warehouse = b.warehouse)'):
|
|
3268
|
+
db.sql('INSERT INTO "Stock Balance Detail" (name, item_code, warehouse, batch_no, actual_qty) '
|
|
3269
|
+
'VALUES (?, ?, ?, ?, ?)',
|
|
3270
|
+
[uuid.uuid4().hex, row["item_code"], row["warehouse"], "", row["actual_qty"] or 0])
|
|
3271
|
+
db.conn.commit()
|
|
3272
|
+
|
|
3273
|
+
|
|
3203
3274
|
def _m042_record_notes(db: "Database") -> None:
|
|
3204
3275
|
"""Internal team notes on any document or master (see api.record_notes)."""
|
|
3205
3276
|
db.conn.execute(
|
|
@@ -3269,6 +3340,8 @@ Database.MIGRATIONS = [
|
|
|
3269
3340
|
(47, "sales_order_status_left_to_do", _m047_sales_order_status_left_to_do),
|
|
3270
3341
|
(48, "item_valuation_moving_average", _m048_item_valuation_moving_average),
|
|
3271
3342
|
(49, "pricing_rule_currency", _m049_pricing_rule_currency),
|
|
3343
|
+
(50, "amount_only_returns", _m050_amount_only_returns),
|
|
3344
|
+
(51, "batches", _m051_batches),
|
|
3272
3345
|
]
|
|
3273
3346
|
|
|
3274
3347
|
|
|
@@ -6,6 +6,8 @@ STRUCTURAL_FIELDS = {
|
|
|
6
6
|
'item': ('is_asset_tracked', 'is_stock_item', 'stock_uom'),
|
|
7
7
|
'cost-center': ('company', 'parent_cost_center', 'is_group'),
|
|
8
8
|
'company': ('default_currency',),
|
|
9
|
+
# A batch is identified by its item and label once stock has moved on it.
|
|
10
|
+
'batch': ('item_code', 'batch_no'),
|
|
9
11
|
}
|
|
10
12
|
|
|
11
13
|
|
|
@@ -209,6 +209,7 @@ def make_delivery_return(dn_name):
|
|
|
209
209
|
uom=item.get("uom"),
|
|
210
210
|
rate=flt(item.get("rate")),
|
|
211
211
|
warehouse=item.get("warehouse"),
|
|
212
|
+
batch_no=item.get("batch_no"),
|
|
212
213
|
against_sales_order=item.get("against_sales_order"),
|
|
213
214
|
so_detail=item.get("so_detail"),
|
|
214
215
|
))
|
|
@@ -179,6 +179,8 @@ class PurchaseReceipt(Document):
|
|
|
179
179
|
voucher_type=self.DOCTYPE,
|
|
180
180
|
voucher_no=self.name,
|
|
181
181
|
voucher_detail_no=item.get("name"),
|
|
182
|
+
batch_no=item.get("batch_no"),
|
|
183
|
+
expiry_date=item.get("expiry_date"),
|
|
182
184
|
posting_date=self.posting_date,
|
|
183
185
|
company=self.company,
|
|
184
186
|
))
|
|
@@ -309,6 +311,7 @@ def make_purchase_receipt_return(prec_name):
|
|
|
309
311
|
uom=item.get("uom"),
|
|
310
312
|
rate=flt(item.get("rate")),
|
|
311
313
|
warehouse=item.get("warehouse"),
|
|
314
|
+
batch_no=item.get("batch_no"),
|
|
312
315
|
against_purchase_order=item.get("against_purchase_order"),
|
|
313
316
|
po_detail=item.get("po_detail"),
|
|
314
317
|
))
|
|
@@ -5,6 +5,7 @@ Stock Entry handles all material movements:
|
|
|
5
5
|
- Material Receipt: goods coming INTO a warehouse (no source)
|
|
6
6
|
- Material Issue: goods going OUT of a warehouse (no target)
|
|
7
7
|
- Material Transfer: goods moving between warehouses
|
|
8
|
+
- Batch Assignment: stock without a batch gets its batch, in place
|
|
8
9
|
|
|
9
10
|
Each type creates Stock Ledger Entries (SLEs) and optionally
|
|
10
11
|
GL entries for perpetual inventory.
|
|
@@ -29,8 +30,10 @@ class StockEntry(Document):
|
|
|
29
30
|
CHILD_REQUIREMENTS = {'items': {'required': ['item_code', 'qty']}}
|
|
30
31
|
CONDITIONAL_REQUIREMENTS = (
|
|
31
32
|
"Receipt/opening rows require an explicit finite basic_rate >= 0 in company currency (zero means intentionally unvalued). Issues and transfers use actual inventory cost, not a supplied selling rate. Financial postings derive from posted stock values.",
|
|
32
|
-
"stock_entry_type must be Opening Stock, Material Receipt, Material Issue or
|
|
33
|
+
"stock_entry_type must be Opening Stock, Material Receipt, Material Issue, Material Transfer or Batch Assignment.",
|
|
33
34
|
"Every items row requires an existing item_code and a positive finite qty. Receipt/opening need t_warehouse; issue needs s_warehouse; transfer needs two distinct warehouses. Warehouses must belong to company.",
|
|
35
|
+
"Rows of a batch-tracked item (Item.has_batch_no) require batch_no; a new batch on a receipt/opening row also needs expiry_date when the item has expiry dates. A transfer moves the batch as it is. Items that are not batch-tracked take no batch_no.",
|
|
36
|
+
"Batch Assignment gives stock that has no batch (from before the item was batch-tracked) its batch without moving it: each row needs the warehouse (s_warehouse or t_warehouse), batch_no and qty; it changes neither total quantity nor value and posts no GL.",
|
|
34
37
|
)
|
|
35
38
|
|
|
36
39
|
LINK_FIELDS = {
|
|
@@ -47,9 +50,11 @@ class StockEntry(Document):
|
|
|
47
50
|
}
|
|
48
51
|
|
|
49
52
|
def validate(self):
|
|
50
|
-
if self.stock_entry_type not in {"Opening Stock", "Material Receipt", "Material Issue", "Material Transfer"
|
|
53
|
+
if self.stock_entry_type not in {"Opening Stock", "Material Receipt", "Material Issue", "Material Transfer",
|
|
54
|
+
"Batch Assignment"}:
|
|
51
55
|
raise ValidationError(
|
|
52
|
-
"Stock Entry Type must be Opening Stock, Material Receipt, Material Issue
|
|
56
|
+
"Stock Entry Type must be Opening Stock, Material Receipt, Material Issue, "
|
|
57
|
+
"Material Transfer or Batch Assignment"
|
|
53
58
|
)
|
|
54
59
|
if not self.get("items"):
|
|
55
60
|
raise ValidationError("At least one item is required")
|
|
@@ -111,6 +116,20 @@ class StockEntry(Document):
|
|
|
111
116
|
raise ValidationError(
|
|
112
117
|
f"Source Warehouse is required for Material Issue (Item: {item.get('item_code')})"
|
|
113
118
|
)
|
|
119
|
+
elif self.stock_entry_type == "Batch Assignment":
|
|
120
|
+
# Same warehouse on both sides: the stock stays where it is.
|
|
121
|
+
warehouse = (item.get("t_warehouse") or item.get("s_warehouse")
|
|
122
|
+
or self.to_warehouse or self.from_warehouse)
|
|
123
|
+
if not warehouse:
|
|
124
|
+
raise ValidationError(
|
|
125
|
+
f"Warehouse is required for Batch Assignment (Item: {item.get('item_code')})")
|
|
126
|
+
if item.get("s_warehouse") and item.get("t_warehouse") and item["s_warehouse"] != item["t_warehouse"]:
|
|
127
|
+
raise ValidationError(
|
|
128
|
+
"Batch Assignment does not move stock: Source and Target Warehouse must be the same")
|
|
129
|
+
item["s_warehouse"] = item["t_warehouse"] = warehouse
|
|
130
|
+
if not str(item.get("batch_no") or "").strip():
|
|
131
|
+
raise ValidationError(
|
|
132
|
+
f"Batch is required for Batch Assignment (Item: {item.get('item_code')})")
|
|
114
133
|
elif self.stock_entry_type == "Material Transfer":
|
|
115
134
|
if not item.get("s_warehouse"):
|
|
116
135
|
item["s_warehouse"] = self.from_warehouse
|
|
@@ -164,14 +183,19 @@ class StockEntry(Document):
|
|
|
164
183
|
posting_date=self.posting_date, posting_time=self.posting_time or '00:00:00',
|
|
165
184
|
company=self.company)
|
|
166
185
|
rate = flt(item.get('basic_rate'))
|
|
186
|
+
batch = {'batch_no': item.get('batch_no')}
|
|
187
|
+
# Batch Assignment takes the quantity out of stock without a batch
|
|
188
|
+
# and puts it back, at the same value, under the batch.
|
|
189
|
+
source_batch = ({'batch_no': None, 'allow_unassigned_batch': True}
|
|
190
|
+
if self.stock_entry_type == 'Batch Assignment' else batch)
|
|
167
191
|
if item.get('s_warehouse'):
|
|
168
|
-
make_sl_entries([{**base, 'warehouse': item['s_warehouse'], 'actual_qty': -flt(item['qty']), 'outgoing_rate': 0}])
|
|
192
|
+
make_sl_entries([{**base, **source_batch, 'warehouse': item['s_warehouse'], 'actual_qty': -flt(item['qty']), 'outgoing_rate': 0}])
|
|
169
193
|
posted = db.get_value('Stock Ledger Entry', {'voucher_type': self.DOCTYPE, 'voucher_no': self.name, 'voucher_detail_no': item['name'], 'warehouse': item['s_warehouse']}, ['stock_value_difference'])
|
|
170
194
|
value = -flt(posted.stock_value_difference)
|
|
171
195
|
rate = value / flt(item['qty'])
|
|
172
196
|
outgoing += value
|
|
173
197
|
if item.get('t_warehouse'):
|
|
174
|
-
make_sl_entries([{**base, 'warehouse': item['t_warehouse'], 'actual_qty': flt(item['qty']), 'incoming_rate': rate, 'incoming_rate_is_explicit': True}])
|
|
198
|
+
make_sl_entries([{**base, **batch, 'expiry_date': item.get('expiry_date'), 'warehouse': item['t_warehouse'], 'actual_qty': flt(item['qty']), 'incoming_rate': rate, 'incoming_rate_is_explicit': True}])
|
|
175
199
|
incoming += flt(item['qty']) * rate
|
|
176
200
|
item['basic_rate'] = rate
|
|
177
201
|
item['basic_amount'] = item['amount'] = flt(flt(item['qty']) * rate, 2)
|
|
@@ -209,6 +233,10 @@ class StockEntry(Document):
|
|
|
209
233
|
if not account:
|
|
210
234
|
raise ValidationError('Stock account is required before posting a valued stock movement')
|
|
211
235
|
amounts[account] = amounts.get(account, 0) + value
|
|
236
|
+
if self.stock_entry_type == 'Batch Assignment':
|
|
237
|
+
if abs(sum(amounts.values())) > 0.01:
|
|
238
|
+
raise ValidationError('Batch Assignment must not change stock value')
|
|
239
|
+
return []
|
|
212
240
|
if self.stock_entry_type != 'Material Transfer':
|
|
213
241
|
total = sum(amounts.values())
|
|
214
242
|
if total:
|