Compare commits

..

20 Commits

Author SHA1 Message Date
Mihir Kandoi
653ef6eff2 fix: batch and serial nos set only once 2026-09-09 10:33:55 +05:30
Mihir Kandoi
acbefcd603 fix(stock): deduplicate scans after serial reselection 2026-09-09 10:01:46 +05:30
Mihir Kandoi
445a30ba60 fix(stock): show physical serial and batch numbers in errors 2026-09-09 09:56:45 +05:30
Mihir Kandoi
fca005c935 fix(stock): allow reselecting pending serial and batch entries 2026-09-09 09:45:19 +05:30
Mihir Kandoi
e51c01628d style(stock): declare the Data Import class extension with the others 2026-09-09 08:33:58 +05:30
Mihir Kandoi
766e51ae58 refactor(stock): drop the forked data import runner
The Data Import override copied the core background runner to swap one
line. Core now calls get_importer, so the subclass is used by the real
import and the copy can go. This also drops the enqueue_after_commit
that the copy had added on top of core.

Requires frappe#42648.
2026-09-09 08:33:23 +05:30
Mihir Kandoi
3acaa55db9 test(stock): verify merged print column escaping 2026-09-09 08:19:18 +05:30
Mihir Kandoi
dbfec6e9fb fix(stock): format serial numbers in builder prints 2026-09-09 08:13:04 +05:30
Mihir Kandoi
1426a098f1 refactor(stock): detect serial and batch input from field metadata 2026-09-09 07:42:46 +05:30
Mihir Kandoi
92b6d708d8 fix(stock): reuse transaction serial and batch fields 2026-09-09 07:11:49 +05:30
Mihir Kandoi
fa244a3615 perf(stock): batch serial and batch number resolution 2026-09-08 22:52:56 +05:30
Mihir Kandoi
cdb12ecf9d test(stock): close CSV fixture before importing 2026-09-08 22:29:28 +05:30
Mihir Kandoi
86489d6905 test(stock): verify FIFO normalization preserves references 2026-09-08 22:29:21 +05:30
Mihir Kandoi
d81fe03776 fix(stock): apply serial and batch identity review fixes 2026-09-08 22:20:12 +05:30
Mihir Kandoi
f80cac927d test: remove standalone serial and barcode tests 2026-09-08 12:54:32 +05:30
Mihir Kandoi
687c7d55ba chore: remove serial and batch documentation assets 2026-09-08 12:52:55 +05:30
Mihir Kandoi
6f2cf3bf91 fix(stock): preserve serial selection and use internal IDs in tests 2026-09-08 12:49:02 +05:30
Mihir Kandoi
48818c963a fix(stock): resolve number aliases and detect migration conflicts 2026-09-08 12:48:45 +05:30
Mihir Kandoi
c67a57d9bd fix(stock): enforce serial permissions and case-insensitive numbers 2026-09-08 12:20:58 +05:30
Mihir Kandoi
ca880f6be7 feat(stock)!: separate serial and batch numbers from document IDs 2026-09-08 12:00:06 +05:30
331 changed files with 4979 additions and 8374 deletions

View File

@@ -180,13 +180,6 @@ audit of these fixes found four recurring mistakes:
the arbitrary-pick preservation the wrap is usually justified as. Confirmed on CI; see #56241.
Note a local macOS PostgreSQL gives a **false all-clear** — its collation happens to agree with
MariaDB on case. Fix: take a representative row rather than sorting text.
**Picking that row is the hard part.** `Min(name)` is still a text sort: `autoname="hash"` is
not reliably lower case, because `_get_timestamp_prefix()` prepends `get_trace_id()[-1:]`
un-lowered and a client-supplied `X-Frappe-Request-Id` can put an upper case `A-F` there. A
non-text key (`Min(idx)`) works only where it is **unique within the group** and the join-back
carries the **full group key** — a date is usually neither, and joining on a duplicated value
turns one group into several rows (§3). Otherwise select the row in Python, sorting with
`key=str.casefold` so the order matches MariaDB's collation without depending on the database's.
- **Wrong bound** — where the value has a semantic, pick the bound deliberately:
`Min(schedule_date)` for a "required by", `Min(idx)` for first-line ordering, a qty-weighted
average for a rate. A blind `Max` can understate urgency or overstate a figure.

View File

@@ -55,18 +55,6 @@ class ERPNextAddress(Address):
@frappe.whitelist()
def get_shipping_address(company: str, address: str | None = None):
# `company` is caller supplied and this returns that company's own registered address with every
# field. `select` rather than `read` on Company: Delivery, Maintenance, Purchase Manager and
# Stock Manager all fill in transactions that ask for this while holding no Company `read` row.
frappe.has_permission("Company", ptype="select", throw=True)
# and scope it to the caller's own Company restrictions, which costs nobody who has none
from erpnext.stock.doctype.company_restriction.company_restriction import get_allowed_companies
allowed_companies = get_allowed_companies(frappe.session.user, "Address")
if allowed_companies and company not in allowed_companies:
frappe.throw(_("Not permitted for {0}").format(company), frappe.PermissionError)
filters = [
["Dynamic Link", "link_doctype", "=", "Company"],
["Dynamic Link", "link_name", "=", company],

View File

@@ -24,7 +24,7 @@ def get(
heatmap_year: str | None = None,
):
if chart_name:
chart = frappe.get_doc("Dashboard Chart", chart_name, check_permission="read")
chart = frappe.get_doc("Dashboard Chart", chart_name)
else:
chart = frappe._dict(frappe.parse_json(chart))
timespan = chart.timespan
@@ -46,9 +46,6 @@ def get(
if not account:
frappe.throw(_("Account filter not set!"))
# authorise the account itself, as get_balance_on() does; doc= brings User Permissions with it
frappe.has_permission("Account", doc=account, throw=True)
if not to_date:
to_date = nowdate()
if not from_date:

View File

@@ -503,21 +503,24 @@ class Account(NestedSet):
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_parent_account(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
return frappe.get_list(
"Account",
filters=[
["is_group", "=", 1],
["docstatus", "!=", 2],
["company", "=", filters["company"]],
[searchfield, "like", f"%{txt}%"],
],
fields=["name"],
order_by="name",
limit_start=start,
limit_page_length=page_len,
as_list=True,
Account = frappe.qb.DocType("Account")
search_field_obj = getattr(Account, searchfield)
query = (
frappe.qb.from_(Account)
.select(Account.name)
.where(Account.is_group == 1)
.where(Account.docstatus != 2)
.where(Account.company == filters["company"])
.where(search_field_obj.like(f"%{txt}%"))
.order_by(Account.name)
.limit(page_len)
.offset(start)
)
return query.run(as_list=1)
def get_account_currency(account):
"""Helper function to get account currency"""

View File

@@ -223,11 +223,8 @@ def delete_accounting_dimension(doc):
frappe.clear_cache(doctype=doctype)
@frappe.whitelist(methods=["POST"])
@frappe.whitelist()
def disable_dimension(doc: str):
# toggle_disabling rewrites a Custom Field site-wide, so demand the write that configures dimensions
frappe.has_permission("Accounting Dimension", "write", throw=True)
if frappe.in_test:
toggle_disabling(doc=doc)
else:

View File

@@ -222,13 +222,6 @@ class AccountsSettings(Document):
set_allow_on_submit_for_dimension_fields(doctypes)
@frappe.whitelist(methods=["POST"])
def get_posting_date_confirmation() -> int:
return cint(
frappe.db.get_single_value("Accounts Settings", "confirm_before_resetting_posting_date", cache=False)
)
def toggle_accounting_dimension_sections(hide):
accounting_dimension_doctypes = frappe.get_hooks("accounting_dimension_doctypes")
for doctype in accounting_dimension_doctypes:

View File

@@ -1,15 +1,9 @@
import frappe
from erpnext.accounts.doctype.accounts_settings.accounts_settings import get_posting_date_confirmation
from erpnext.tests.utils import ERPNextTestSuite
class TestAccountsSettings(ERPNextTestSuite):
def test_posting_date_confirmation_uses_current_setting(self):
for enabled in (0, 1, 0):
frappe.db.set_single_value("Accounts Settings", "confirm_before_resetting_posting_date", enabled)
self.assertEqual(get_posting_date_confirmation(), enabled)
def test_stale_days(self):
cur_settings = frappe.get_doc("Accounts Settings", "Accounts Settings")
cur_settings.allow_stale = 0

View File

@@ -60,9 +60,6 @@ def get_voucher_details(bank_guarantee_type: str, reference_name: str):
if not isinstance(reference_name, str):
raise TypeError("reference_name must be a string")
# the form is the boundary, not the referenced order: an order guard would break one of the two roles
frappe.has_permission("Bank Guarantee", throw=True)
fields_to_fetch = ["grand_total"]
if bank_guarantee_type == "Receiving":
@@ -73,14 +70,4 @@ def get_voucher_details(bank_guarantee_type: str, reference_name: str):
doctype = "Purchase Order"
fields_to_fetch.append("supplier")
# and scope the referenced order to the caller's own Company restrictions, which costs nobody
# who has none
from erpnext.stock.doctype.company_restriction.company_restriction import get_allowed_companies
allowed_companies = get_allowed_companies(frappe.session.user, "Bank Guarantee")
if allowed_companies:
company = frappe.db.get_value(doctype, reference_name, "company")
if company and company not in allowed_companies:
frappe.throw(_("Not permitted for {0}").format(company), frappe.PermissionError)
return frappe.db.get_value(doctype, reference_name, fields_to_fetch, as_dict=True)

View File

@@ -68,7 +68,6 @@ frappe.ui.form.on("Bank Reconciliation Tool", {
frappe.msgprint(__("Please select Bank Account"));
return;
}
frm.events.validate_dates(frm);
frappe.call({
method: "erpnext.accounts.doctype.bank_reconciliation_tool.bank_reconciliation_tool.auto_reconcile_vouchers",
args: {
@@ -83,7 +82,7 @@ frappe.ui.form.on("Bank Reconciliation Tool", {
});
frm.add_custom_button(__("Get Unreconciled Entries"), function () {
return frm.trigger("make_reconciliation_tool");
frm.trigger("make_reconciliation_tool");
});
frm.change_custom_button_type(__("Get Unreconciled Entries"), null, "primary");
@@ -107,24 +106,7 @@ frappe.ui.form.on("Bank Reconciliation Tool", {
frm.trigger("get_account_opening_balance");
},
validate_dates(frm) {
const from_date = frm.doc.filter_by_reference_date
? frm.doc.from_reference_date
: frm.doc.bank_statement_from_date;
const to_date = frm.doc.filter_by_reference_date
? frm.doc.to_reference_date
: frm.doc.bank_statement_to_date;
if (from_date && to_date && from_date > to_date) {
frappe.throw(
frm.doc.filter_by_reference_date
? __("From Reference Date cannot be greater than To Reference Date")
: __("From Date cannot be greater than To Date")
);
}
},
make_reconciliation_tool(frm) {
frm.events.validate_dates(frm);
frm.get_field("reconciliation_tool_cards").$wrapper.empty();
if (frm.doc.company && frm.doc.bank_account && frm.doc.bank_statement_to_date) {
frm.trigger("get_cleared_balance").then(() => {

View File

@@ -9,7 +9,7 @@ from frappe import _
from frappe.model.document import Document
from frappe.query_builder.custom import ConstantColumn
from frappe.query_builder.functions import Max, Sum
from frappe.utils import cint, create_batch, flt, getdate
from frappe.utils import cint, create_batch, flt
from erpnext import get_default_cost_center
from erpnext.accounts.doctype.bank_transaction.bank_transaction import get_total_allocated_amount
@@ -54,8 +54,6 @@ def get_bank_transactions(
all_transactions: bool = False,
):
# returns bank transactions for a bank account
validate_date_range(from_date, to_date)
filters = []
filters.append(["bank_account", "=", bank_account])
filters.append(["docstatus", "=", 1])
@@ -964,10 +962,9 @@ def auto_reconcile_vouchers(
from_date: str | date | None = None,
to_date: str | date | None = None,
filter_by_reference_date: bool | None = None,
from_reference_date: str | date | None = None,
to_reference_date: str | date | None = None,
from_reference_date: bool | None = None,
to_reference_date: str | None = None,
):
validate_date_range(from_date, to_date, filter_by_reference_date, from_reference_date, to_reference_date)
bank_transactions = get_bank_transactions(bank_account)
if len(bank_transactions) > 10:
@@ -1082,11 +1079,10 @@ def get_linked_payments(
from_date: str | date | None = None,
to_date: str | date | None = None,
filter_by_reference_date: bool | None = None,
from_reference_date: str | date | None = None,
to_reference_date: str | date | None = None,
from_reference_date: bool | None = None,
to_reference_date: str | None = None,
):
# get all matching payments for a bank transaction
validate_date_range(from_date, to_date, filter_by_reference_date, from_reference_date, to_reference_date)
transaction = frappe.get_doc("Bank Transaction", bank_transaction_name)
bank_account = frappe.db.get_values(
"Bank Account", transaction.bank_account, ["account", "company"], as_dict=True
@@ -1106,23 +1102,6 @@ def get_linked_payments(
return subtract_allocations(gl_account, matching)
def validate_date_range(
from_date,
to_date,
filter_by_reference_date=False,
from_reference_date=None,
to_reference_date=None,
):
if cint(filter_by_reference_date):
from_date, to_date = from_reference_date, to_reference_date
message = _("From Reference Date cannot be greater than To Reference Date")
else:
message = _("From Date cannot be greater than To Date")
if from_date and to_date and getdate(from_date) > getdate(to_date):
frappe.throw(message)
def subtract_allocations(gl_account, vouchers):
"Look up & subtract any existing Bank Transaction allocations"
copied = []
@@ -1159,7 +1138,6 @@ def check_matching(
from_reference_date=None,
to_reference_date=None,
):
document_types = document_types or []
exact_match = True if "exact_match" in document_types else False
common_filters = frappe._dict(

View File

@@ -131,37 +131,6 @@ class TestBankReconciliationTool(ERPNextTestSuite, AccountsTestMixin):
names = [t.name for t in get_bank_transactions(self.bank_account, to_date=add_days(today(), -1))]
self.assertEqual(names, [])
def test_get_linked_payments_without_document_types(self):
bank_transaction = self.make_bank_transaction(date=today())
self.assertEqual(get_linked_payments(bank_transaction.name), [])
def test_rejects_reversed_date_ranges(self):
from_date, to_date = today(), add_days(today(), -1)
with self.assertRaisesRegex(frappe.ValidationError, "From Date cannot be greater than To Date"):
get_bank_transactions(self.bank_account, from_date, to_date)
with self.assertRaisesRegex(
frappe.ValidationError, "From Reference Date cannot be greater than To Reference Date"
):
auto_reconcile_vouchers(
self.bank_account,
filter_by_reference_date=True,
from_reference_date=from_date,
to_reference_date=to_date,
)
transaction = self.make_bank_transaction(date=today())
with self.assertRaisesRegex(
frappe.ValidationError, "From Reference Date cannot be greater than To Reference Date"
):
get_linked_payments(
transaction.name,
["payment_entry"],
filter_by_reference_date=True,
from_reference_date=from_date,
to_reference_date=to_date,
)
def test_deposit_matches_amount_received_in_bank_account(self):
# money leaves another bank account and lands here minus a charge, so the two sides differ
payment = frappe.get_doc(

View File

@@ -437,11 +437,6 @@ def get_import_logs(docname: str):
@frappe.whitelist()
def upload_bank_statement(**args):
# The only caller is the Bank Reconciliation Tool's "Upload Bank Statement" button, whose
# callback routes straight into a new Bank Statement Import form — so `create` is exactly the
# right to require, and both doctypes are System Manager only, which makes it loser-free.
frappe.has_permission("Bank Statement Import", "create", throw=True)
args = frappe._dict(args)
bsi = frappe.new_doc("Bank Statement Import")

View File

@@ -11,11 +11,6 @@ from frappe.utils.dateutils import parse_date
@frappe.whitelist()
def upload_bank_statement():
# Parsing a statement is the first step of creating Bank Transactions from it, so that is the
# right to require. Both functions in this file are reached only over HTTP — nothing in the tree
# calls either — so there is no caller to break.
frappe.has_permission("Bank Transaction", "create", throw=True)
if getattr(frappe, "uploaded_file", None):
with open(frappe.uploaded_file, "rb") as upfile:
fcontent = upfile.read()
@@ -41,12 +36,6 @@ def upload_bank_statement():
@frappe.whitelist(methods=["POST"])
def create_bank_entries(columns: str, data: str | list, bank_account: str):
# insert()/submit() below already enforce this per document, but only after the per-row loop has
# read the Bank Account and its Bank mapping and written an Error Log for every rejected row —
# so check once up front rather than failing row by row.
frappe.has_permission("Bank Transaction", "create", throw=True)
frappe.has_permission("Bank Account", doc=bank_account, throw=True)
header_map = get_header_mapping(columns, bank_account)
success = 0

View File

@@ -8,7 +8,6 @@ from functools import reduce
import frappe
from frappe import _
from frappe.core.doctype.file.utils import find_file_by_url
from frappe.desk.form.linked_with import get_linked_fields
from frappe.model.document import Document
from frappe.utils import cint, cstr
@@ -59,8 +58,6 @@ def validate_columns(data):
@frappe.whitelist()
def validate_company(company: str):
frappe.has_permission("Chart of Accounts Importer", throw=True)
parent_company, allow_account_creation_against_child_company = frappe.get_cached_value(
"Company", company, ["parent_company", "allow_account_creation_against_child_company"]
)
@@ -113,10 +110,7 @@ def import_coa(file_name: str, company: str):
def get_file(file_name):
file_doc = find_file_by_url(file_name)
if not file_doc:
raise frappe.PermissionError
file_doc = frappe.get_doc("File", {"file_url": file_name})
parts = file_doc.get_extension()
extension = parts[1]
extension = extension.lstrip(".")
@@ -185,8 +179,6 @@ def get_coa(
):
"""called by tree view (to fetch node's children)"""
frappe.has_permission("Chart of Accounts Importer", throw=True)
file_doc, extension = get_file(file_name)
parent = None if parent == _("All Accounts") else parent
@@ -334,8 +326,6 @@ def build_response_as_excel(writer):
@frappe.whitelist()
def download_template(file_type: str, template_type: str, company: str):
frappe.has_permission("Chart of Accounts Importer", throw=True)
writer = get_template(template_type, company)
if file_type == "CSV":
@@ -388,6 +378,7 @@ def get_sample_template(writer, company):
return writer
@frappe.whitelist()
def validate_accounts(file_doc: Document, extension: str):
if extension == "csv":
accounts = generate_data_from_csv(file_doc, as_dict=True)

View File

@@ -17,8 +17,7 @@ import json
import frappe
from frappe import _
from frappe.contacts.doctype.address.address import get_address_display
from frappe.query_builder.functions import Sum
from frappe.utils import flt, getdate
from frappe.utils import getdate
from erpnext.controllers.accounts_controller import AccountsController
@@ -148,31 +147,6 @@ class Dunning(AccountsController):
)
row.dunning_level = len(past_dunnings) + 1
def get_unpaid_base_dunning_amount(self):
"""Interest and dunning fee that is still to be collected, in company currency."""
if not self.base_dunning_amount:
return 0.0
return flt(
flt(self.base_dunning_amount) - get_paid_dunning_amount(self.name),
self.precision("base_dunning_amount"),
)
def get_unpaid_dunning_amount(self):
"""Interest and dunning fee that is still to be collected, in the dunning currency."""
return flt(
self.get_unpaid_base_dunning_amount() / (flt(self.conversion_rate) or 1),
self.precision("dunning_amount"),
)
def get_unpaid_overdue_payments(self):
"""Overdue payments with their outstanding as of now, not as of dunning creation."""
return [
(row, outstanding)
for row in self.overdue_payments
if (outstanding := get_current_outstanding(row)) > 0
]
def on_cancel(self):
super().on_cancel()
self.ignore_linked_doctypes = [
@@ -187,7 +161,6 @@ class Dunning(AccountsController):
"Unreconcile Payment Entries",
"Payment Ledger Entry",
"Serial and Batch Bundle",
"Payment Entry",
]
@frappe.whitelist()
@@ -286,73 +259,11 @@ def update_linked_dunnings(doc, previous_outstanding_amount):
if has_outstanding:
break
set_dunning_status(dunning, has_outstanding, respect_manual_resolution=True)
new_status = "Resolved" if not has_outstanding else "Unresolved"
def update_dunnings_linked_to_payment(payment_entry):
"""Refresh dunnings whose interest and fee are settled by this payment."""
dunnings = {row.dunning for row in payment_entry.get("deductions") if row.dunning}
for name in dunnings:
dunning = frappe.get_doc("Dunning", name)
if dunning.docstatus != 1:
continue
set_dunning_status(dunning, bool(dunning.get_unpaid_overdue_payments()))
def set_dunning_status(dunning, has_outstanding_payments: bool, respect_manual_resolution: bool = False):
"""A dunning is only resolved once the invoiced sum *and* its interest and fee are paid."""
has_unpaid_dunning_amount = dunning.get_unpaid_dunning_amount() > 0
new_status = "Unresolved" if has_outstanding_payments or has_unpaid_dunning_amount else "Resolved"
# resolving by hand waives the interest, only an invoice that is owed again reopens it
if respect_manual_resolution and dunning.status == "Resolved" and not has_outstanding_payments:
return
if dunning.status != new_status:
dunning.db_set("status", new_status, notify=True)
def get_paid_dunning_amount(dunning: str) -> float:
"""Interest and fee collected for this dunning, in company currency."""
deduction = frappe.qb.DocType("Payment Entry Deduction")
payment_entry = frappe.qb.DocType("Payment Entry")
paid = (
frappe.qb.from_(deduction)
.join(payment_entry)
.on(payment_entry.name == deduction.parent)
.select(Sum(deduction.amount))
.where((deduction.dunning == dunning) & (payment_entry.docstatus == 1))
).run()
# the dunning amount is booked as a negative deduction, against the income account
return -flt(paid[0][0]) if paid else 0.0
def get_current_outstanding(overdue_payment) -> float:
"""Outstanding of an overdue payment as of now, in the invoice's transaction currency."""
invoice = frappe.db.get_value(
"Sales Invoice",
overdue_payment.sales_invoice,
["outstanding_amount", "currency", "party_account_currency"],
as_dict=True,
)
schedule_outstanding = (
flt(frappe.db.get_value("Payment Schedule", overdue_payment.payment_schedule, "outstanding"))
if overdue_payment.payment_schedule
else flt(overdue_payment.outstanding)
)
if flt(invoice.outstanding_amount) <= 0 or schedule_outstanding <= 0:
return 0.0
outstanding = min(schedule_outstanding, flt(overdue_payment.outstanding))
if invoice.currency == invoice.party_account_currency:
outstanding = min(outstanding, flt(invoice.outstanding_amount))
return outstanding
if dunning.status != new_status:
dunning.status = new_status
dunning.save()
def get_linked_dunnings_as_per_state(sales_invoice, state):

View File

@@ -55,125 +55,6 @@ class TestDunning(ERPNextTestSuite):
dunning.reload()
self.assertEqual(dunning.status, "Resolved")
def test_dunning_not_resolved_by_payment_of_invoiced_sum_only(self):
"""
Regression for #58220: paying the invoice without the interest and fee must not
resolve the dunning, the interest is still owed and has to stay claimable.
"""
dunning = create_dunning(overdue_days=15, dunning_type_name="Second Notice - _TC")
dunning.submit()
sales_invoice = dunning.overdue_payments[0].sales_invoice
pe = get_payment_entry("Sales Invoice", sales_invoice)
pe.reference_no, pe.reference_date = "4", nowdate()
pe.insert()
pe.submit()
self.assertEqual(frappe.get_value("Sales Invoice", sales_invoice, "outstanding_amount"), 0)
dunning.reload()
self.assertEqual(dunning.status, "Unresolved")
self.assertEqual(round(dunning.get_unpaid_dunning_amount(), 2), 10.41)
# the interest and fee can still be collected on their own
pe = get_payment_entry("Dunning", dunning.name)
pe.reference_no, pe.reference_date = "5", nowdate()
self.assertEqual(pe.references, [])
self.assertEqual(round(pe.paid_amount, 2), 10.41)
pe.insert()
pe.submit()
dunning.reload()
self.assertEqual(dunning.status, "Resolved")
self.assertEqual(dunning.get_unpaid_dunning_amount(), 0)
# cancelling the interest payment makes the dunning claimable again
pe.cancel()
dunning.reload()
self.assertEqual(dunning.status, "Unresolved")
self.assertEqual(round(dunning.get_unpaid_dunning_amount(), 2), 10.41)
def test_dunning_can_be_cancelled_after_its_interest_was_paid(self):
"""
The payment collecting the interest links back to the dunning, which must not stand in
the way of cancelling it.
"""
dunning = create_dunning(overdue_days=15, dunning_type_name="Second Notice - _TC")
dunning.submit()
pe = get_payment_entry("Dunning", dunning.name)
pe.reference_no, pe.reference_date = "6", nowdate()
pe.insert()
pe.submit()
dunning.reload()
self.assertEqual(dunning.status, "Resolved")
dunning.cancel()
self.assertEqual(dunning.docstatus, 2)
def test_waived_interest_keeps_a_manually_resolved_dunning_resolved(self):
"""
Resolving a dunning by hand waives its interest, so a later payment of the invoice
must not reopen it.
"""
dunning = create_dunning(overdue_days=15, dunning_type_name="Second Notice - _TC")
dunning.submit()
sales_invoice = dunning.overdue_payments[0].sales_invoice
# what the "Resolve" button does
dunning.reload()
dunning.status = "Resolved"
dunning.save()
pe = get_payment_entry("Sales Invoice", sales_invoice)
pe.reference_no, pe.reference_date = "7", nowdate()
pe.insert()
pe.submit()
dunning.reload()
self.assertEqual(dunning.status, "Resolved")
self.assertEqual(round(dunning.get_unpaid_dunning_amount(), 2), 10.41)
@ERPNextTestSuite.change_settings(
"Accounts Settings", {"allow_multi_currency_invoices_against_single_party_account": 1}
)
def test_unpaid_dunning_amount_is_tracked_in_company_currency(self):
"""
The interest and fee are collected as a Payment Entry deduction, a company currency
field, so what is left to collect has to be measured in the same currency.
"""
si = create_sales_invoice(
posting_date=add_days(today(), -15),
currency="USD",
conversion_rate=50,
rate=100,
debit_to="Debtors - _TC",
)
dunning = create_dunning_from_sales_invoice(si.name)
dunning_type = frappe.get_doc("Dunning Type", "Second Notice - _TC")
dunning.dunning_type = dunning_type.name
dunning.rate_of_interest = dunning_type.rate_of_interest
dunning.dunning_fee = dunning_type.dunning_fee
dunning.income_account = dunning_type.income_account
dunning.cost_center = dunning_type.cost_center
dunning.save()
self.assertEqual(dunning.currency, "USD")
self.assertEqual(dunning.conversion_rate, 50)
self.assertEqual(round(dunning.dunning_amount, 2), 10.41)
self.assertEqual(round(dunning.base_dunning_amount, 2), 520.55)
# nothing collected yet, in either currency
self.assertEqual(round(dunning.get_unpaid_base_dunning_amount(), 2), 520.55)
self.assertEqual(round(dunning.get_unpaid_dunning_amount(), 2), 10.41)
# the deduction booking the interest is in company currency
dunning.submit()
pe = get_payment_entry("Dunning", dunning.name)
self.assertEqual(round(pe.deductions[0].amount, 2), -520.55)
def test_fetch_overdue_payments(self):
"""
Create SI with overdue payment. Check if overdue payment is fetched in Dunning.

View File

@@ -3,6 +3,7 @@
import ast
import json
import math
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from functools import cache, reduce
@@ -28,7 +29,6 @@ from erpnext.accounts.doctype.financial_report_template.financial_report_templat
FinancialReportTemplate,
)
from erpnext.accounts.doctype.financial_report_template.financial_report_validation import (
FORMULA_FUNCTIONS,
AccountFilterValidator,
CalculationFormulaValidator,
DependencyValidator,
@@ -1328,14 +1328,26 @@ class FormulaCalculator:
self.precision = get_currency_precision()
self.validator = CalculationFormulaValidator(set(row_data.keys()))
self.math_functions = {
"abs": abs,
"round": round,
"min": min,
"max": max,
"sum": sum,
"sqrt": math.sqrt,
"pow": math.pow,
"ceil": math.ceil,
"floor": math.floor,
}
def evaluate_formula(self, report_row: dict[str, Any]) -> list[float]:
validation_result = self.validator.validate(report_row)
formula = (report_row.calculation_formula or "").strip()
formula = report_row.calculation_formula
negation_factor = -1 if report_row.reverse_sign else 1
if validation_result.issues:
# TODO: Throw?
messages = "<br><br>".join(str(issue) for issue in validation_result.issues)
messages = "<br><br>".join(issue.message for issue in validation_result.issues)
frappe.log_error(f"Formula validation errors found:\n{messages}")
return [0.0] * len(self.period_list)
@@ -1350,7 +1362,7 @@ class FormulaCalculator:
# TODO: consistent error handling
try:
context = self._build_context(period_index)
result = frappe.safe_eval(formula, eval_globals=None, eval_locals=context)
result = frappe.safe_eval(formula, context)
return flt(result * negation_factor, self.precision)
except ZeroDivisionError:
@@ -1371,7 +1383,7 @@ class FormulaCalculator:
context[code] = 0.0
# math functions
context.update(FORMULA_FUNCTIONS)
context.update(self.math_functions)
return context

View File

@@ -34,13 +34,6 @@ class FinancialReportTemplate(Document):
def before_validate(self):
self.clear_hidden_fields()
for row in self.rows:
if row.reference_code:
row.reference_code = row.reference_code.strip()
if row.calculation_formula:
row.calculation_formula = row.calculation_formula.strip()
def clear_hidden_fields(self):
style_data_sources = {"Blank Line", "Column Break", "Section Break"}

View File

@@ -2,8 +2,6 @@
# For license information, please see license.txt
import json
import keyword
import math
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
@@ -12,19 +10,6 @@ from typing import Any
import frappe
from frappe import _, is_whitelisted
from frappe.database.operator_map import OPERATOR_MAP
from frappe.utils import escape_html
FORMULA_FUNCTIONS = {
"abs": abs,
"round": round,
"min": min,
"max": max,
"sum": sum,
"sqrt": math.sqrt,
"pow": math.pow,
"ceil": math.ceil,
"floor": math.floor,
}
def get_valid_api_method(api_path: str):
@@ -104,9 +89,8 @@ class ValidationResult:
self.warnings.append(issue)
def notify_user(self) -> None:
# messages quote user input back, and both are rendered as HTML
warnings = "<br><br>".join(escape_html(str(w)) for w in self.warnings if w)
errors = "<br><br>".join(escape_html(str(e)) for e in self.issues if e)
warnings = "<br><br>".join(str(w) for w in self.warnings if w)
errors = "<br><br>".join(str(e) for e in self.issues if e)
if warnings:
frappe.msgprint(warnings, title=_("Warnings"), indicator="orange")
@@ -163,27 +147,18 @@ class TemplateStructureValidator(Validator):
if not row.reference_code:
continue
ref_code = row.reference_code
ref_code = row.reference_code.strip()
# a line reference is used as a name in formulas, so it must be a usable one
if not re.match(r"^[A-Za-z][A-Za-z0-9_]*$", ref_code):
# Check format
if not re.match(r"^[A-Za-z][A-Za-z0-9_-]*$", ref_code):
result.add_error(
ValidationIssue(
message=_(
"Invalid line reference format: '{0}'. Must start with a letter and contain only letters, numbers and underscores"
"Invalid line reference format: '{0}'. Must start with letter and contain only letters, numbers, underscores, and hyphens"
).format(ref_code),
row_idx=row.idx,
)
)
elif keyword.iskeyword(ref_code) or ref_code in FORMULA_FUNCTIONS:
result.add_error(
ValidationIssue(
message=_("'{0}' is a reserved name and cannot be used as a line reference").format(
ref_code
),
row_idx=row.idx,
)
)
# Check uniqueness
if ref_code in used_codes:
@@ -233,7 +208,12 @@ class DependencyValidator(Validator):
self.dependencies = self._build_dependency_graph()
def validate(self, context=None) -> ValidationResult:
return self._validate_circular_dependencies()
result = ValidationResult()
result.merge(self._validate_circular_dependencies())
result.merge(self._validate_missing_dependencies())
return result
def _build_dependency_graph(self) -> dict[str, list[str]]:
graph = {}
@@ -300,6 +280,31 @@ class DependencyValidator(Validator):
return result
def _validate_missing_dependencies(self) -> ValidationResult:
available = {row.reference_code for row in self.template.rows if row.reference_code}
result = ValidationResult()
for ref_code, deps in self.dependencies.items():
undefined = [d for d in deps if d not in available]
if undefined:
row_idx = self._get_row_idx(ref_code)
result.add_error(
ValidationIssue(
message=_("Line references undefined in {0}: {1}").format(
get_formula_field_label("Calculated Amount"), ", ".join(undefined)
),
row_idx=row_idx,
)
)
return result
def _get_row_idx(self, reference_code: str) -> int | None:
for row in self.template.rows:
if row.reference_code == reference_code:
return row.idx
return None
class CalculationFormulaValidator(Validator):
"""Validates calculation formulas used in Calculated Amount rows"""
@@ -315,6 +320,7 @@ class CalculationFormulaValidator(Validator):
return result
formula = self._preprocess_formula(row.calculation_formula)
row.calculation_formula = formula
# Check parentheses
if not self._are_parentheses_balanced(formula):
@@ -362,15 +368,25 @@ class CalculationFormulaValidator(Validator):
def _test_formula_evaluation(self, formula: str, available_codes: list[str]) -> str | None:
try:
context = {code: 1.0 for code in available_codes}
context.update(FORMULA_FUNCTIONS)
context.update(
{
"abs": abs,
"round": round,
"min": min,
"max": max,
"sum": sum,
"sqrt": lambda x: x**0.5,
"pow": pow,
"ceil": lambda x: int(x) + (1 if x % 1 else 0),
"floor": int,
}
)
result = frappe.safe_eval(formula, eval_globals=None, eval_locals=context)
if not isinstance(result, (int | float)):
if not isinstance(result, (int, float)): # noqa: UP038
return _("Formula must return a numeric value, got {0}").format(type(result).__name__)
return None
except ZeroDivisionError:
return None
except Exception as e:
return str(e)
@@ -446,14 +462,13 @@ class AccountFilterValidator(Validator):
return _("Field and operator must be strings")
if field not in account_fields:
return _("Field '{0}' is not a valid Account field").format(field)
# escape: `field` is caller-supplied and this message renders as HTML
return _("Field '{0}' is not a valid Account field").format(frappe.utils.escape_html(field))
normalized_operator = operator.casefold()
if normalized_operator not in OPERATOR_MAP:
if operator.casefold() not in OPERATOR_MAP:
return _("Invalid operator '{0}'").format(operator)
if normalized_operator in ["in", "not in"] and not isinstance(value, list):
if operator in ["in", "not in"] and not isinstance(value, list):
return _("Operator '{0}' requires a list value").format(operator)
# logical condition: {"and": [condition1, condition2]}

View File

@@ -5,11 +5,8 @@ import frappe
from frappe.tests.utils import whitelist_for_tests
from erpnext.accounts.doctype.financial_report_template.financial_report_validation import (
FORMULA_FUNCTIONS,
AccountFilterValidator,
CalculationFormulaValidator,
FormulaValidator,
TemplateStructureValidator,
get_valid_api_method,
)
from erpnext.tests.utils import ERPNextTestSuite
@@ -192,13 +189,8 @@ class TestAccountFilter(FinancialReportTemplateTestCase):
def test_error_message_labels_and_escapes_field(self):
validator = AccountFilterValidator()
result = validator.validate_filter(self._row('["<script>", "=", "x"]'))
self.assertIn("[Account Filter]", str(result.issues[0]))
# escaping happens where the message is rendered, not where it is built
frappe.clear_messages()
with self.assertRaises(frappe.ValidationError):
result.notify_user()
message = frappe.get_message_log()[-1]["message"]
message = str(result.issues[0])
self.assertIn("[Account Filter]", message)
self.assertIn("&lt;script&gt;", message)
self.assertNotIn("<script>", message)
@@ -256,149 +248,3 @@ class TestAccountFilter(FinancialReportTemplateTestCase):
pluck="name",
)
self.assertEqual(sorted(get_filtered_accounts(company, "[]")), sorted(expected))
class TestFormulaEnvironment(FinancialReportTemplateTestCase):
"""Validator and engine must evaluate a formula in the same environment."""
@staticmethod
def _calc(row_data):
from erpnext.accounts.doctype.financial_report_template.financial_report_engine import (
FormulaCalculator,
)
return FormulaCalculator(row_data, [{"key": "p1"}])
@staticmethod
def _row(formula):
return frappe._dict(
calculation_formula=formula,
idx=1,
reverse_sign=0,
data_source="Calculated Amount",
reference_code="X",
)
def test_engine_keeps_reference_codes_named_like_builtins(self):
# "int" and "long" are whitelisted safe_eval globals; the row values must win
calc = self._calc({"int": [500.0], "long": [2000.0]})
self.assertEqual(calc.evaluate_formula(self._row("int + long"))[0], 2500.0)
def test_validator_keeps_reference_codes_named_like_builtins(self):
validator = CalculationFormulaValidator({"int", "long"})
self.assertTrue(validator.validate(self._row("int + long")).is_valid)
def test_engine_uses_the_shared_function_list(self):
context = self._calc({"A": [1.0]})._build_context(0)
for name, function in FORMULA_FUNCTIONS.items():
self.assertIs(context[name], function)
def test_rounding_matches_math_module(self):
calc = self._calc({"A": [1.0]})
self.assertEqual(calc.evaluate_formula(self._row("floor(-2.5)"))[0], -3.0)
self.assertEqual(calc.evaluate_formula(self._row("ceil(-2.5)"))[0], -2.0)
class TestCalculationFormula(FinancialReportTemplateTestCase):
"""Formulas are test-evaluated with dummy values before a template can be saved."""
@staticmethod
def _validate(formula, codes=("A", "B", "C")):
row = frappe._dict(
calculation_formula=formula, idx=1, data_source="Calculated Amount", reference_code="X"
)
return CalculationFormulaValidator(set(codes)).validate(row)
def test_division_by_zero_is_not_a_validation_error(self):
# the dummy values are all 1.0, so a denominator can only be zero by accident;
# the engine tolerates real division by zero at run time
self.assertTrue(self._validate("A / (B - C)").is_valid)
self.assertTrue(self._validate("(A - B) / (A - C)").is_valid)
self.assertTrue(self._validate("ROM / (CAS + FDE - ROM)", ("ROM", "CAS", "FDE")).is_valid)
self.assertTrue(self._validate("A / 0").is_valid)
def test_broken_formulas_are_rejected(self):
self.assertFalse(self._validate("A +").is_valid)
self.assertFalse(self._validate("NOPE * 2").is_valid)
self.assertFalse(self._validate("'text'").is_valid)
class TestFilterOperatorCase(FinancialReportTemplateTestCase):
"""Operators are matched case-insensitively, so their value checks must be too."""
@staticmethod
def _row(formula):
return frappe._dict(calculation_formula=formula, idx=1)
def test_uppercase_in_requires_a_list_value(self):
validator = AccountFilterValidator()
self.assertFalse(validator.validate_filter(self._row('["root_type", "IN", "Income"]')).is_valid)
self.assertFalse(validator.validate_filter(self._row('["root_type", "NOT IN", "Income"]')).is_valid)
def test_uppercase_in_accepts_a_list_value(self):
validator = AccountFilterValidator()
self.assertTrue(validator.validate_filter(self._row('["root_type", "IN", ["Income"]]')).is_valid)
class TestLineReferenceNames(FinancialReportTemplateTestCase):
"""A line reference becomes a name in formulas, so it must be usable as one."""
@staticmethod
def _validate(code):
template = frappe._dict(rows=[frappe._dict(reference_code=code, idx=1, data_source="Blank Line")])
return TemplateStructureValidator()._validate_reference_codes(template)
def test_plain_codes_are_accepted(self):
for code in ("REV", "CA100", "cash_flow_2"):
self.assertTrue(self._validate(code).is_valid, code)
def test_hyphen_is_rejected(self):
# "-" reads as subtraction in a formula and is not a valid Python name
self.assertFalse(self._validate("REV-COGS").is_valid)
def test_python_keyword_is_rejected(self):
for code in ("if", "None", "class"):
self.assertFalse(self._validate(code).is_valid, code)
def test_formula_function_name_is_rejected(self):
# these would be overwritten by the function of the same name
for code in ("sum", "round", "abs"):
self.assertFalse(self._validate(code).is_valid, code)
def test_surrounding_spaces_are_normalised_before_validation(self):
template = frappe.new_doc("Financial Report Template")
template.template_name = "Spaces"
template.append("rows", {"reference_code": " REV ", "data_source": "Blank Line"})
template.append(
"rows",
{
"reference_code": "X",
"data_source": "Calculated Amount",
"calculation_formula": " REV * 2 ",
},
)
template.before_validate()
self.assertEqual(template.rows[0].reference_code, "REV")
self.assertEqual(template.rows[1].calculation_formula, "REV * 2")
def test_validation_does_not_modify_the_row(self):
row = frappe._dict(
calculation_formula=" REV * 2 ",
idx=1,
data_source="Calculated Amount",
reference_code="X",
)
CalculationFormulaValidator({"REV", "X"}).validate(row)
self.assertEqual(row.calculation_formula, " REV * 2 ")
def test_invalid_reference_code_is_escaped(self):
# this message fires when the code fails the format check, so it can hold anything
template = frappe._dict(rows=[frappe._dict(reference_code="<img src=x onerror=alert(1)>", idx=1)])
result = TemplateStructureValidator()._validate_reference_codes(template)
frappe.clear_messages()
with self.assertRaises(frappe.ValidationError):
result.notify_user()
message = frappe.get_message_log()[-1]["message"]
self.assertIn("&lt;img", message)
self.assertNotIn("<img", message)

View File

@@ -136,7 +136,6 @@ frappe.ui.form.on("Invoice Discounting", {
],
primary_action: function () {
var data = d.get_values();
data.company = frm.doc.company;
frappe.call({
method: "erpnext.accounts.doctype.invoice_discounting.invoice_discounting.get_invoices",

View File

@@ -1,6 +1,5 @@
{
"actions": [],
"allow_bulk_edit": 1,
"allow_import": 1,
"autoname": "ACC-INV-DISC-.YYYY.-.#####",
"creation": "2019-03-07 12:01:56.296952",
@@ -171,7 +170,7 @@
],
"is_submittable": 1,
"links": [],
"modified": "2026-09-09 17:04:59.512294",
"modified": "2024-03-27 13:09:52.746196",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Invoice Discounting",
@@ -188,15 +187,14 @@
"print": 1,
"read": 1,
"report": 1,
"role": "Accounts Manager",
"role": "System Manager",
"share": 1,
"submit": 1,
"write": 1
}
],
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"track_changes": 1
}
}

View File

@@ -319,13 +319,6 @@ class InvoiceDiscounting(AccountsController):
@frappe.whitelist()
def get_invoices(filters: str | dict):
filters = frappe._dict(frappe.parse_json(filters))
if not filters.get("company"):
frappe.throw(_("Please set company on the Document before requesting for invoices."))
frappe.has_permission("Company", doc=filters.get("company"), throw=True)
frappe.has_permission("Invoice Discounting", throw=True)
si = frappe.qb.DocType("Sales Invoice")
di = frappe.qb.DocType("Discounted Invoice")

View File

@@ -624,8 +624,8 @@ Object.assign(erpnext.journal_entry, {
total_credit += flt(row.credit, precision("credit", row));
});
frm.doc.total_debit = flt(total_debit, precision("total_debit"));
frm.doc.total_credit = flt(total_credit, precision("total_credit"));
frm.doc.total_debit = total_debit;
frm.doc.total_credit = total_credit;
frm.doc.difference = flt(total_debit - total_credit, precision("difference"));
["total_debit", "total_credit", "difference"].forEach((field) => frm.refresh_field(field));
},

View File

@@ -674,14 +674,12 @@ class JournalEntry(AccountsController):
if d.debit and d.credit:
frappe.throw(_("You cannot credit and debit same account at the same time"))
self.total_debit = flt(
self.total_debit + flt(d.debit, d.precision("debit")), self.precision("total_debit")
)
self.total_credit = flt(
self.total_credit + flt(d.credit, d.precision("credit")), self.precision("total_credit")
)
self.total_debit = flt(self.total_debit) + flt(d.debit, d.precision("debit"))
self.total_credit = flt(self.total_credit) + flt(d.credit, d.precision("credit"))
self.difference = flt(self.total_debit - self.total_credit, self.precision("difference"))
self.difference = flt(self.total_debit, self.precision("total_debit")) - flt(
self.total_credit, self.precision("total_credit")
)
def validate_multi_currency(self):
alternate_currency = []
@@ -1023,11 +1021,6 @@ def get_default_bank_cash_account(
) -> dict:
from erpnext.accounts.doctype.sales_invoice.sales_invoice import get_bank_cash_account
# the company is the scope being authorised, and doc= brings User Permissions to bear. `select`,
# not `read`: this also runs server-side from get_payment_entry, and Auditor/HR User/Desk User
# hold only the select row on Company
frappe.has_permission("Company", ptype="select", doc=company, throw=True)
if mode_of_payment:
account = get_bank_cash_account(mode_of_payment, company).get("account")
@@ -1056,11 +1049,6 @@ def get_default_bank_cash_account(
account = account_list[0].name
if account:
# `account` may be named by the caller outright, so authorise the account actually being
# described. get_balance_on() checks this too, but only on the branch that reads a balance,
# and `fetch_balance` is a caller-supplied argument.
frappe.has_permission("Account", doc=account, throw=True)
account_details = frappe.get_cached_value(
"Account", account, ["account_currency", "account_type"], as_dict=1
)
@@ -1090,40 +1078,30 @@ def get_against_jv(
if not frappe.db.has_column("Journal Entry", searchfield):
return []
account = filters.get("account")
JournalEntry = frappe.qb.DocType("Journal Entry")
JournalEntryAccount = frappe.qb.DocType("Journal Entry Account")
query = (
frappe.qb.from_(JournalEntry)
.join(JournalEntryAccount)
.on(JournalEntryAccount.parent == JournalEntry.name)
.select(JournalEntry.name, JournalEntry.posting_date, JournalEntry.remark)
.where(JournalEntryAccount.account == filters.get("account"))
.where(JournalEntryAccount.reference_type.isnull() | (JournalEntryAccount.reference_type == ""))
.where(JournalEntry.docstatus == 1)
.where(JournalEntry[searchfield].like(f"%{txt}%"))
.orderby(JournalEntry.name, order=frappe.qb.desc)
.limit(page_len)
.offset(start)
)
party = filters.get("party")
if party:
query = query.where(JournalEntryAccount.party == party)
else:
query = query.where(JournalEntryAccount.party.isnull() | (JournalEntryAccount.party == ""))
# each names one value. A list would be read as a filter operator below and widen the search
# past what the caller named.
for value in (account, party):
if value and not isinstance(value, str):
frappe.throw(_("Invalid filter"), frappe.PermissionError)
# get_list applies the permission query conditions; the child-table filter resolves the check to `read`
je_filters = [
["docstatus", "=", 1],
[searchfield, "like", f"%{txt}%"],
["Journal Entry Account", "account", "=", account],
["Journal Entry Account", "reference_type", "is", "not set"],
]
je_filters.append(
["Journal Entry Account", "party", "=", party]
if party
else ["Journal Entry Account", "party", "is", "not set"]
)
return frappe.get_list(
"Journal Entry",
filters=je_filters,
fields=["name", "posting_date", "remark"],
order_by="name desc",
limit_start=start,
limit_page_length=page_len,
as_list=True,
# one row per entry, not per matching account row. group_by rather than distinct: frappe
# drops ORDER BY from a distinct query on postgres, which would lose the ordering above.
group_by="name",
)
return query.run()
@frappe.whitelist()

View File

@@ -461,59 +461,6 @@ class TestJournalEntry(ERPNextTestSuite):
self.check_gl_entries()
def make_jv_with_fractional_totals(self):
"""0.10 + 0.20 sums to 0.30000000000000004, the residue this guards against."""
jv = frappe.new_doc("Journal Entry")
jv.posting_date = nowdate()
jv.company = "_Test Company"
jv.voucher_type = "Journal Entry"
jv.remark = "test"
for amount in (0.10, 0.20):
jv.append(
"accounts",
{
"account": "_Test Cash - _TC",
"cost_center": "_Test Cost Center - _TC",
"debit_in_account_currency": amount,
},
)
jv.append(
"accounts",
{
"account": "_Test Bank - _TC",
"cost_center": "_Test Cost Center - _TC",
"credit_in_account_currency": 0.30,
},
)
jv.insert()
return jv
def test_totals_are_rounded_to_precision(self):
jv = self.make_jv_with_fractional_totals()
jv.submit()
stored = frappe.db.get_value(
"Journal Entry", jv.name, ["total_debit", "total_credit", "difference"], as_dict=True
)
self.assertEqual(jv.total_debit, flt(jv.total_debit, jv.precision("total_debit")))
self.assertEqual(jv.total_credit, flt(jv.total_credit, jv.precision("total_credit")))
self.assertEqual(jv.total_debit, stored.total_debit)
self.assertEqual(jv.total_credit, stored.total_credit)
self.assertEqual(jv.difference, stored.difference)
def test_update_after_submit_with_fractional_totals(self):
"""An unrounded total is stored rounded, so updating a submitted entry used to throw."""
jv = self.make_jv_with_fractional_totals()
jv.submit()
jv.pay_to_recd_from = "_Test Supplier"
jv.save()
self.assertEqual(jv.docstatus, 1)
self.assertEqual(
jv.pay_to_recd_from, frappe.db.get_value("Journal Entry", jv.name, "pay_to_recd_from")
)
def test_jv_account_and_party_balance_with_cost_centre(self):
from erpnext.accounts.doctype.cost_center.test_cost_center import create_cost_center
from erpnext.accounts.utils import get_balance_on

View File

@@ -129,11 +129,6 @@ def get_loyalty_program_details(
silent: bool = False,
include_expired_entry: bool = False,
):
# Same guard as get_loyalty_program_details_with_points above: the customer is what the caller
# is entitled to, not the programme. A check on Loyalty Program itself would be read-only to
# System Manager and would deny every role that actually fills in the two calling forms.
frappe.has_permission("Customer", doc=customer, throw=True)
lp_details = frappe._dict()
if not loyalty_program:
@@ -155,13 +150,6 @@ def get_loyalty_program_details(
@frappe.whitelist()
def get_redeemption_factor(loyalty_program: str | None = None, customer: str | None = None):
# both call sites send only `loyalty_program`, so the calling form is the boundary; the customer branch stays guarded
if not (frappe.has_permission("Sales Invoice") or frappe.has_permission("POS Invoice")):
frappe.throw(_("Not permitted"), frappe.PermissionError)
if customer:
frappe.has_permission("Customer", doc=customer, throw=True)
customer_loyalty_program = None
if not loyalty_program:
customer_loyalty_program = frappe.db.get_value("Customer", customer, "loyalty_program")

View File

@@ -46,27 +46,23 @@ frappe.ui.form.on("Payment Entry", {
},
setup: function (frm) {
frm.set_query("paid_from", function (doc) {
frm.set_query("paid_from", function () {
frm.events.validate_company(frm);
var account_types = ["Pay", "Internal Transfer"].includes(frm.doc.payment_type)
? ["Bank", "Cash"]
: [frappe.boot.party_account_types[frm.doc.party_type]];
let filters = {
account_type: ["in", account_types],
is_group: 0,
company: doc.company,
};
if (frm.doc.party_type == "Shareholder") {
account_types.push("Equity");
}
if (doc.payment_type == "Internal Transfer" && doc.paid_to) {
filters.name = ["!=", doc.paid_to];
}
return {
filters,
filters: {
account_type: ["in", account_types],
is_group: 0,
company: frm.doc.company,
},
};
});
@@ -110,25 +106,21 @@ frappe.ui.form.on("Payment Entry", {
}
});
frm.set_query("paid_to", function (doc) {
frm.set_query("paid_to", function () {
frm.events.validate_company(frm);
var account_types = ["Receive", "Internal Transfer"].includes(frm.doc.payment_type)
? ["Bank", "Cash"]
: [frappe.boot.party_account_types[frm.doc.party_type]];
let filters = {
account_type: ["in", account_types],
is_group: 0,
company: doc.company,
};
if (frm.doc.party_type == "Shareholder") {
account_types.push("Equity");
}
if (doc.payment_type == "Internal Transfer" && doc.paid_from) {
filters.name = ["!=", doc.paid_from];
}
return {
filters,
filters: {
account_type: ["in", account_types],
is_group: 0,
company: frm.doc.company,
},
};
});

View File

@@ -176,7 +176,6 @@ class PaymentEntry(AccountsController):
self.set_liability_account()
self.set_missing_ref_details(force=True)
self.validate_payment_type()
self.validate_internal_transfer_accounts()
self.validate_party_details()
self.set_exchange_rate()
self.validate_mandatory()
@@ -209,15 +208,9 @@ class PaymentEntry(AccountsController):
self.update_payment_schedule()
self.make_gl_entries()
self.update_outstanding_amounts()
self.update_linked_dunnings()
self.set_status()
self.trigger_invoice_update_for_subscriptions()
def update_linked_dunnings(self):
from erpnext.accounts.doctype.dunning.dunning import update_dunnings_linked_to_payment
update_dunnings_linked_to_payment(self)
def validate_for_repost(self):
validate_docs_for_voucher_types(["Payment Entry"])
validate_docs_for_deferred_accounting([self.name], [])
@@ -322,7 +315,6 @@ class PaymentEntry(AccountsController):
self.update_payment_schedule(cancel=1)
self.make_gl_entries(cancel=1)
self.update_outstanding_amounts()
self.update_linked_dunnings()
self.delink_advance_entry_references()
self.set_status()
self.trigger_invoice_update_for_subscriptions()
@@ -635,10 +627,6 @@ class PaymentEntry(AccountsController):
if self.payment_type not in ("Receive", "Pay", "Internal Transfer"):
frappe.throw(_("Payment Type must be one of Receive, Pay, or Internal Transfer"))
def validate_internal_transfer_accounts(self):
if self.payment_type == "Internal Transfer" and self.paid_from and self.paid_from == self.paid_to:
frappe.throw(_("Paid From and Paid To accounts must be different for an Internal Transfer."))
def validate_party_details(self):
if self.party and not frappe.db.exists(self.party_type, self.party):
frappe.throw(_("{0} {1} does not exist").format(_(self.party_type), self.party))
@@ -2737,7 +2725,7 @@ def get_payment_entry(
pe.append("references", reference)
else:
if dt == "Dunning":
for overdue_payment, outstanding in doc.get_unpaid_overdue_payments():
for overdue_payment in doc.overdue_payments:
pe.append(
"references",
{
@@ -2745,23 +2733,21 @@ def get_payment_entry(
"reference_name": overdue_payment.sales_invoice,
"payment_term": overdue_payment.payment_term,
"due_date": overdue_payment.due_date,
"total_amount": outstanding,
"outstanding_amount": outstanding,
"allocated_amount": outstanding,
"total_amount": overdue_payment.outstanding,
"outstanding_amount": overdue_payment.outstanding,
"allocated_amount": overdue_payment.outstanding,
},
)
if (unpaid_dunning_amount := doc.get_unpaid_base_dunning_amount()) > 0:
pe.append(
"deductions",
{
"account": doc.income_account,
"cost_center": doc.cost_center,
"amount": -1 * unpaid_dunning_amount,
"description": _("Interest and/or dunning fee"),
"dunning": doc.name,
},
)
pe.append(
"deductions",
{
"account": doc.income_account,
"cost_center": doc.cost_center,
"amount": -1 * doc.dunning_amount,
"description": _("Interest and/or dunning fee"),
},
)
else:
pe.append(
"references",
@@ -3054,10 +3040,8 @@ def set_grand_total_and_outstanding_amount(party_amount, dt, party_account_curre
grand_total = doc.rounded_total or doc.grand_total
outstanding_amount = doc.outstanding_amount
elif dt == "Dunning":
# only what is left to collect, the totals on the dunning are the ones it was raised with
grand_total = sum(outstanding for _row, outstanding in doc.get_unpaid_overdue_payments())
grand_total += doc.get_unpaid_dunning_amount()
outstanding_amount = grand_total
grand_total = doc.grand_total
outstanding_amount = doc.grand_total
else:
if party_account_currency == doc.company_currency:
grand_total = flt(doc.get("base_rounded_total") or doc.get("base_grand_total"))

View File

@@ -782,23 +782,6 @@ class TestPaymentEntry(ERPNextTestSuite):
self.validate_gl_entries(pe.name, expected_gle)
def test_internal_transfer_rejects_same_account(self):
pe = frappe.new_doc("Payment Entry")
pe.payment_type = "Internal Transfer"
pe.company = "_Test Company"
pe.paid_from = "_Test Bank - _TC"
pe.paid_to = "_Test Bank - _TC"
pe.paid_amount = 100
pe.received_amount = 100
pe.reference_no = "same-account-transfer"
pe.reference_date = nowdate()
self.assertRaisesRegex(
frappe.ValidationError,
"Paid From and Paid To accounts must be different",
pe.insert,
)
def test_bank_charges_deduction(self):
bank_charges_account = create_account(
parent_account="Indirect Expenses - _TC",

View File

@@ -10,8 +10,7 @@
"amount",
"column_break_2",
"is_exchange_gain_loss",
"description",
"dunning"
"description"
],
"fields": [
{
@@ -56,21 +55,12 @@
"fieldtype": "Check",
"label": "System Generated",
"read_only": 1
},
{
"fieldname": "dunning",
"fieldtype": "Link",
"label": "Dunning",
"no_copy": 1,
"options": "Dunning",
"print_hide": 1,
"read_only": 1
}
],
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
"modified": "2026-08-17 11:20:35.482913",
"modified": "2026-03-11 14:26:11.312950",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Payment Entry Deduction",

View File

@@ -18,7 +18,6 @@ class PaymentEntryDeduction(Document):
amount: DF.Currency
cost_center: DF.Link
description: DF.SmallText | None
dunning: DF.Link | None
is_exchange_gain_loss: DF.Check
parent: DF.Data
parentfield: DF.Data

View File

@@ -57,27 +57,9 @@ class PaymentOrder(Document):
frappe.db.set_value(self.payment_order_type, d.get(ref_doc_field), ref_field, status)
def _readable_payment_order(filters: dict) -> str | None:
"""Authorise the parent before reading its rows.
A child table carries no permissions of its own, so a read of it has to be authorised on the
Payment Order the rows belong to.
"""
parent = filters.get("parent")
if not parent or not frappe.db.exists("Payment Order", parent):
return None
ptype = "select" if frappe.only_has_select_perm("Payment Order") else "read"
frappe.has_permission("Payment Order", ptype, doc=parent, throw=True)
return parent
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_mop_query(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
if not _readable_payment_order(filters):
return []
return frappe.get_all(
"Payment Order Reference",
filters={"parent": filters.get("parent"), "mode_of_payment": ["like", f"%{txt}%"]},
@@ -92,9 +74,6 @@ def get_mop_query(doctype: str, txt: str, searchfield: str, start: int, page_len
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_supplier_query(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
if not _readable_payment_order(filters):
return []
return frappe.get_all(
"Payment Order Reference",
filters={

View File

@@ -1041,6 +1041,40 @@ class TestPaymentRequestV2Gateway(ERPNextTestSuite):
mock_payments.utils = mock_utils
return {"payments": mock_payments, "payments.utils": mock_utils}, mock_utils
def test_is_v2_gateway_returns_false_for_none(self):
"""_is_v2_gateway returns False for None input."""
from erpnext.accounts.doctype.payment_request.payment_request import _is_v2_gateway
# Mock returns True, but is_v2_gateway(None) in payments.utils returns False
modules, mock_utils = self._mock_payments_modules(False)
with patch.dict(sys.modules, modules):
result = _is_v2_gateway(None)
self.assertFalse(result)
mock_utils.is_v2_gateway.assert_called_once_with(None)
def test_is_v2_gateway_returns_false_for_empty_string(self):
"""_is_v2_gateway returns False for empty string input."""
from erpnext.accounts.doctype.payment_request.payment_request import _is_v2_gateway
modules, mock_utils = self._mock_payments_modules(False)
with patch.dict(sys.modules, modules):
result = _is_v2_gateway("")
self.assertFalse(result)
mock_utils.is_v2_gateway.assert_called_once_with("")
def test_is_v2_gateway_returns_false_for_nonexistent_gateway(self):
"""_is_v2_gateway returns False for nonexistent gateway."""
from erpnext.accounts.doctype.payment_request.payment_request import _is_v2_gateway
modules, mock_utils = self._mock_payments_modules(False)
with patch.dict(sys.modules, modules):
result = _is_v2_gateway("NonExistentGateway12345")
self.assertFalse(result)
mock_utils.is_v2_gateway.assert_called_once_with("NonExistentGateway12345")
def test_is_v2_gateway_delegates_to_payments_util(self):
"""_is_v2_gateway delegates to payments.utils.is_v2_gateway."""
from erpnext.accounts.doctype.payment_request.payment_request import _is_v2_gateway

View File

@@ -5,7 +5,7 @@ frappe.ui.form.on("Period Closing Voucher", {
onload: function (frm) {
if (!frm.doc.transaction_date) frm.doc.transaction_date = frappe.datetime.obj_to_str(new Date());
frm.ignore_doctypes_on_cancel_all = ["Process Period Closing Voucher", "MapReduce Job"];
frm.ignore_doctypes_on_cancel_all = ["Process Period Closing Voucher"];
},
setup: function (frm) {

View File

@@ -5,20 +5,9 @@
import copy
import frappe
from frappe import _, qb
from frappe.query_builder.custom import ConstantColumn
from frappe.query_builder.functions import Count, Max, Min, Sum
from frappe.utils import (
add_days,
ceil,
cint,
flt,
fmt_money,
formatdate,
get_datetime,
get_link_to_form,
getdate,
)
from frappe import _
from frappe.query_builder.functions import Max, Sum
from frappe.utils import add_days, flt, fmt_money, formatdate, get_link_to_form, getdate
from erpnext import is_perpetual_inventory_enabled
from erpnext.accounts.doctype.account_closing_balance.account_closing_balance import (
@@ -276,17 +265,8 @@ class PeriodClosingVoucher(AccountsController):
if frappe.get_single_value("Accounts Settings", "use_legacy_controller_for_pcv"):
self.make_gl_entries()
else:
from frappe.utils.background_jobs import mapreduce
data = self.get_data_for_mapreduce()
mapreduce(
"erpnext.accounts.doctype.period_closing_voucher.period_closing_voucher.mapper",
"erpnext.accounts.doctype.period_closing_voucher.period_closing_voucher.reducer",
"erpnext.accounts.doctype.period_closing_voucher.period_closing_voucher.summarize_and_post_ledger",
data,
self.doctype,
self.name,
)
ppcv = frappe.get_doc({"doctype": "Process Period Closing Voucher", "parent_pcv": self.name})
ppcv.save().submit()
def on_cancel(self):
self.ignore_linked_doctypes = (
@@ -295,16 +275,11 @@ class PeriodClosingVoucher(AccountsController):
"Payment Ledger Entry",
"Account Closing Balance",
"Process Period Closing Voucher",
"MapReduce Job",
)
self.block_if_future_closing_voucher_exists()
self.validate_accounts_not_frozen(for_cancellation=True)
if not frappe.get_single_value("Accounts Settings", "use_legacy_controller_for_pcv"):
from frappe.utils.background_jobs import cancel_mapreduce_job
cancel_mapreduce_job(self.doctype, self.name)
self.cancel_process_pcv_docs()
self.db_set("gle_processing_status", "In Progress")
@@ -317,11 +292,6 @@ class PeriodClosingVoucher(AccountsController):
def on_trash(self):
super().on_trash()
if not frappe.get_single_value("Accounts Settings", "use_legacy_controller_for_pcv"):
from frappe.utils.background_jobs import remove_mapreduce_job
remove_mapreduce_job(self.doctype, self.name)
ppcvs = frappe.db.get_all(
"Process Period Closing Voucher", {"parent_pcv": self.name, "docstatus": ["in", [1, 2]]}
)
@@ -624,135 +594,6 @@ class PeriodClosingVoucher(AccountsController):
{"voucher_type": "Period Closing Voucher", "voucher_no": self.name, "is_cancelled": 0},
)
def get_data_for_mapreduce(self):
return self.generate_tasks_for_normal_balance() + self.generate_tasks_for_opening_balance()
def get_period_range_for_tasks(self, start_date, end_date, step_size, report_type, balance_type):
start_date = getdate(start_date)
end_date = getdate(end_date)
# split period into date ranges
curr_date = getdate(start_date)
date_splits = []
while True:
next_date = getdate(add_days(curr_date, step_size))
if next_date < end_date:
date_splits.append(
{
"from_date": str(curr_date),
"to_date": str(next_date),
"pcv": self.name,
"report_type": report_type,
"balance_type": balance_type,
}
)
curr_date = getdate(add_days(next_date, 1))
else:
date_splits.append(
{
"from_date": str(curr_date),
"to_date": str(end_date),
"pcv": self.name,
"report_type": report_type,
"balance_type": balance_type,
}
)
break
return date_splits
def generate_tasks_for_normal_balance(self):
# estimation can be wrong by a factor of 2
gl = qb.DocType("GL Entry")
raw_query = (
qb.from_(gl)
.select(Count(gl.star))
.where(
gl.is_cancelled.eq(0) & gl.posting_date.between(self.period_start_date, self.period_end_date)
)
.get_sql()
)
# estimation can be wrong by a factor of 2
correction_factor = 2
if frappe.db.db_type == "postgres":
analyzer = frappe.json.loads(
(
frappe.db.sql(
f"explain (format json) {raw_query}",
)
)[0][0]
)
estimated_count = analyzer[0].get("Plan").get("Plans")[0].get("Plan Rows") * correction_factor
else:
estimated_count = (
cint(
frappe.db.sql(
f"explain {raw_query}",
as_dict=True,
)[0].rows
)
* correction_factor
)
job_count = (
1 if estimated_count / 2000000 < 1 else ceil(estimated_count / 2000000)
) # conservative chunk size
days = (getdate(self.period_end_date) - getdate(self.period_start_date)).days
step_size = 1 if days / job_count < 1 else ceil(days / job_count)
return self.get_period_range_for_tasks(
self.period_start_date, self.period_end_date, step_size, "Balance Sheet", "Normal Balance"
) + self.get_period_range_for_tasks(
self.period_start_date, self.period_end_date, step_size, "Profit and Loss", "Normal Balance"
)
def generate_tasks_for_opening_balance(self):
tasks = []
if self.is_first_period_closing_voucher():
gl = qb.DocType("GL Entry")
min = qb.from_(gl).select(Min(gl.posting_date)).run()[0][0]
max = qb.from_(gl).select(Max(gl.posting_date)).run()[0][0]
raw_query = (
qb.from_(gl)
.select(Count(gl.star))
.where(gl.is_cancelled.eq(0) & gl.is_opening.eq("Yes") & gl.posting_date.between(min, max))
.get_sql()
)
# estimation can be wrong by a factor of 2
correction_factor = 2
if frappe.db.db_type == "postgres":
analyzer = frappe.json.loads(
(
frappe.db.sql(
f"explain (format json) {raw_query}",
)
)[0][0]
)
estimated_count = analyzer[0].get("Plan").get("Plans")[0].get("Plan Rows") * correction_factor
else:
estimated_count = (
cint(
frappe.db.sql(
f"explain {raw_query};",
as_dict=True,
)[0].rows
)
* correction_factor
)
job_count = (
1 if estimated_count / 2000000 < 1 else ceil(estimated_count / 2000000)
) # conservative chunk size
days = (getdate(self.period_end_date) - getdate(self.period_start_date)).days
step_size = 1 if days / job_count < 1 else ceil(days / job_count)
tasks = self.get_period_range_for_tasks(min, max, step_size, "Balance Sheet", "Opening Balance")
return tasks
def process_gl_and_closing_entries(doc):
from erpnext.accounts.general_ledger import make_gl_entries
@@ -832,119 +673,3 @@ def get_previous_closed_period_in_current_year(fiscal_year, company):
order_by="period_end_date desc",
)
return prev_closed_period_end_date
def mapper(val):
start_date = val.from_date
end_date = val.to_date
pcv = val.pcv
report_type = val.report_type
balance_type = val.balance_type
company = frappe.db.get_value("Period Closing Voucher", pcv, "company")
dimensions = get_dimensions()
accounts = frappe.db.get_all(
"Account", filters={"company": company, "report_type": report_type}, pluck="name"
)
gle = qb.DocType("GL Entry")
query = qb.from_(gle).select(gle.account)
for dim in dimensions:
query = query.select(gle[dim])
query = query.select(
Sum(gle.debit).as_("debit"),
Sum(gle.credit).as_("credit"),
Sum(gle.debit_in_account_currency).as_("debit_in_account_currency"),
Sum(gle.credit_in_account_currency).as_("credit_in_account_currency"),
# account_currency is constant per grouped account -> Max() keeps the GROUP BY postgres-valid
Max(gle.account_currency).as_("account_currency"),
ConstantColumn(balance_type).as_("balance_type"),
ConstantColumn(report_type).as_("report_type"),
).where(
(gle.company.eq(company))
& (gle.is_cancelled.eq(0))
& (gle.posting_date.between(start_date, end_date))
& (gle.account.isin(accounts))
)
if balance_type == "Opening Balance":
query = query.where(gle.is_opening.eq("Yes"))
else:
# Keep balances aligned with legacy PCV logic (non-opening transactions only)
query = query.where(gle.is_opening.eq("No"))
query = query.groupby(gle.account)
for dim in dimensions:
query = query.groupby(gle[dim])
res = query.run(as_dict=True)
return res
def reducer(final, partial_res):
if final is None:
final = []
if partial_res:
final.extend([frappe._dict(x) for x in partial_res])
return final
def get_dimensions():
from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
get_accounting_dimensions,
)
default_dimensions = ["cost_center", "finance_book", "project"]
dimensions = default_dimensions + get_accounting_dimensions()
return dimensions
def summarize_and_post_ledger(result, ref_dt, ref_dn):
pcv = frappe.get_doc(ref_dt, ref_dn)
from erpnext.accounts.doctype.process_period_closing_voucher.process_period_closing_voucher import (
build_dimension_wise_balance_dict,
get_bs_closing_entries,
get_closing_account_closing_entry,
get_gle_for_closing_account,
get_gle_for_pl_account,
get_p_l_closing_entries,
)
result = [frappe._dict(x) for x in result]
# generate and post closing entries for P&L accounts
pl_entries = [x for x in result if x.report_type == "Profit and Loss"]
pl_dimension_wise_acc_balance = build_dimension_wise_balance_dict(pl_entries)
# build gl map
pl_accounts_reverse_gle = []
closing_account_gle = []
for dimensions, account_balances in pl_dimension_wise_acc_balance.items():
for acc, balances in account_balances.items():
balance_in_company_currency = flt(balances.debit) - flt(balances.credit)
if balance_in_company_currency:
pl_accounts_reverse_gle.append(get_gle_for_pl_account(pcv, acc, balances, dimensions))
closing_account_gle.append(get_gle_for_closing_account(pcv, account_balances["balances"], dimensions))
gl_entries = pl_accounts_reverse_gle + closing_account_gle
if gl_entries:
from erpnext.accounts.general_ledger import make_gl_entries
make_gl_entries(gl_entries, merge_entries=False)
# generate and post account closing balance for balance sheet accounts
bs_entries = [x for x in result if x.report_type == "Balance Sheet"]
bs_dimension_wise_acc_balance = build_dimension_wise_balance_dict(bs_entries)
pl_closing_entries = get_p_l_closing_entries(pl_accounts_reverse_gle, pcv)
bs_closing_entries = get_bs_closing_entries(bs_dimension_wise_acc_balance, pcv)
closing_entries_for_closing_account = get_closing_account_closing_entry(closing_account_gle, pcv)
closing_entries = pl_closing_entries + bs_closing_entries + closing_entries_for_closing_account
make_closing_entries(closing_entries, pcv.name, pcv.company, pcv.period_end_date)
frappe.db.set_value("Period Closing Voucher", pcv.name, "gle_processing_status", "Completed")

View File

@@ -1,8 +0,0 @@
from frappe import _
def get_data():
return {
"non_standard_fieldnames": {"MapReduce Job": "document_name"},
"transactions": [{"label": _("Job"), "items": ["MapReduce Job"]}],
}

View File

@@ -256,13 +256,6 @@ class POSClosingEntry(StatusUpdater):
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_cashiers(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
pos_profile = filters.get("parent")
if not pos_profile or not frappe.db.exists("POS Profile", pos_profile):
return []
ptype = "select" if frappe.only_has_select_perm("POS Profile") else "read"
frappe.has_permission("POS Profile", ptype, doc=pos_profile, throw=True)
cashiers_list = frappe.get_all("POS Profile User", filters=filters, fields=["user"], as_list=1)
return [c for c in cashiers_list]

View File

@@ -909,30 +909,6 @@ class POSInvoice(SalesInvoice):
@frappe.whitelist()
def get_stock_availability(item_code: str | None, warehouse: str):
# The POS Profile is what entitles a caller to POS stock figures, and it is the only boundary
# that fits: `Item` read and `Bin` read both exclude Accounts Manager, `Item` select is granted
# to every desk user by `Desk User`, and `POS Invoice` read is granted to `All`.
frappe.has_permission("POS Profile", throw=True)
# and keep a company-restricted caller inside their own companies, which costs nobody who has
# no Company User Permission
from erpnext.stock.doctype.company_restriction.company_restriction import get_allowed_companies
allowed_companies = get_allowed_companies(frappe.session.user, "POS Profile")
if allowed_companies:
company = frappe.db.get_value("Warehouse", warehouse, "company")
if company and company not in allowed_companies:
frappe.throw(_("Not permitted for {0}").format(company), frappe.PermissionError)
# the caller picks the warehouse when allow_warehouse_change is set, and the company check above
# does not narrow within a company; costs nobody who has no Warehouse User Permission
from frappe.permissions import get_allowed_docs_for_doctype, get_user_permissions
if warehouse_permissions := get_user_permissions(frappe.session.user).get("Warehouse"):
allowed_warehouses = get_allowed_docs_for_doctype(warehouse_permissions, "POS Invoice")
if allowed_warehouses and warehouse not in allowed_warehouses:
frappe.throw(_("Not permitted for {0}").format(warehouse), frappe.PermissionError)
if frappe.db.get_value("Item", item_code, "is_stock_item"):
is_stock_item = True
bin_qty = get_bin_qty(item_code, warehouse)

View File

@@ -818,7 +818,7 @@ class TestPOSInvoice(POSInvoiceTestMixin):
)
from erpnext.stock.serial_batch_bundle import SerialBatchCreation
create_batch_item_with_batch("_BATCH ITEM", "TestBatch 01")
batch_no = create_batch_item_with_batch("_BATCH ITEM", "TestBatch 01")
item = frappe.get_doc("Item", "_BATCH ITEM")
se = make_stock_entry(
@@ -826,12 +826,10 @@ class TestPOSInvoice(POSInvoiceTestMixin):
item_code="_BATCH ITEM",
qty=2,
basic_rate=100,
batch_no="TestBatch 01",
batch_no=batch_no,
)
pos_inv1 = create_pos_invoice(
item=item.name, rate=300, qty=1, do_not_submit=1, batch_no="TestBatch 01"
)
pos_inv1 = create_pos_invoice(item=item.name, rate=300, qty=1, do_not_submit=1, batch_no=batch_no)
pos_inv1.append(
"payments",
{"mode_of_payment": "Cash", "amount": 300},
@@ -849,7 +847,7 @@ class TestPOSInvoice(POSInvoiceTestMixin):
"voucher_no": pos_inv2.name,
"qty": 2,
"avg_rate": 300,
"batches": frappe._dict({"TestBatch 01": 2}),
"batches": frappe._dict({batch_no: 2}),
"type_of_transaction": "Outward",
"company": pos_inv2.company,
}
@@ -925,6 +923,7 @@ class TestPOSInvoice(POSInvoiceTestMixin):
self.assertRaises(frappe.ValidationError, pos_inv.submit)
@ERPNextTestSuite.change_settings("Stock Settings", {"allow_negative_stock": 0})
def test_bundle_stock_availability_validation(self):
from erpnext.accounts.doctype.pos_invoice.pos_invoice import ProductBundleStockValidationError
from erpnext.selling.doctype.product_bundle.test_product_bundle import make_product_bundle

View File

@@ -108,7 +108,7 @@ frappe.ui.form.on("Pricing Rule", {
</td></tr>
</table>`;
frm.get_field("pricing_rule_help").html(help_content);
frm.set_df_property("pricing_rule_help", "options", help_content);
frm.events.set_options_for_applicable_for(frm);
frm.trigger("toggle_reqd_apply_on");
},

View File

@@ -12,29 +12,6 @@ from frappe import _, throw
from frappe.model.document import Document
from frappe.utils import cint, flt
# the transactions the pricing engine is called for, from transaction.js and the POS
PRICING_TRANSACTION_DOCTYPES = frozenset(
{
"Quotation",
"Sales Order",
"Delivery Note",
"Sales Invoice",
"POS Invoice",
"Supplier Quotation",
"Purchase Order",
"Purchase Receipt",
"Purchase Invoice",
"Material Request",
# these three also extend a controller that calls the pricing engine: BOM and BOM Creator
# through TransactionController, Request for Quotation through BuyingController
"BOM",
"BOM Creator",
"Request for Quotation",
# no client sends this one, but set_transaction_type below still branches on it
"Opportunity",
}
)
apply_on_dict = {"Item Code": "items", "Item Group": "item_groups", "Brand": "brands"}
other_fields = ["other_item_code", "other_item_group", "other_brand"]
@@ -389,30 +366,6 @@ def apply_pricing_rule(args: str | dict, doc: str | dict | Document | None = Non
args = frappe._dict(args)
# `args` is caller supplied, and what comes back is pricing: matched Pricing Rules, discounts
# and rates. The transaction being priced is what decides who may price it, so authorise that
# — and the document itself where the caller named an existing one, so User Permissions apply.
# an allow-list, not just a type check: `doctype` is caller-chosen, and any doctype the caller can
# read would otherwise satisfy has_permission below while the pricing engine still ran
transaction_doctype = args.get("doctype")
if transaction_doctype not in PRICING_TRANSACTION_DOCTYPES:
frappe.throw(_("Invalid doctype"), frappe.PermissionError)
transaction_name = args.get("name")
if not isinstance(transaction_name, str) or not frappe.db.exists(transaction_doctype, transaction_name):
transaction_name = None
frappe.has_permission(transaction_doctype, doc=transaction_name, throw=True)
# scope by the caller's own Company restrictions, not a Company read: several roles that fill these forms hold none
company = args.get("company")
if company:
from erpnext.stock.doctype.company_restriction.company_restriction import get_allowed_companies
allowed_companies = get_allowed_companies(frappe.session.user, transaction_doctype)
if allowed_companies and company not in allowed_companies:
frappe.throw(_("Not permitted for {0}").format(company), frappe.PermissionError)
set_transaction_type(args)
# list of dictionaries
@@ -772,18 +725,14 @@ def set_transaction_type(pricing_ctx: frappe._dict) -> None:
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_item_uoms(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
if filters.get("apply_on") == "Item Code":
item_filters = [["name", "=", filters.get("value")]]
else:
item_filters = [[frappe.scrub(filters.get("apply_on")), "=", filters.get("value")]]
items = frappe.get_list("Item", filters=item_filters, pluck="name")
if not items:
return []
items = [filters.get("value")]
if filters.get("apply_on") != "Item Code":
field = frappe.scrub(filters.get("apply_on"))
items = [d.name for d in frappe.db.get_all("Item", filters={field: filters.get("value")})]
return frappe.get_all(
"UOM Conversion Detail",
filters={"parent": ("in", items), "parenttype": "Item", "uom": ("like", f"{txt}%")},
filters={"parent": ("in", items), "uom": ("like", f"{txt}%")},
fields=["uom"],
as_list=1,
distinct=True,

View File

@@ -133,17 +133,14 @@ def initialize_parallel_threads(docname: str):
frappe.db.set_value("Process Period Closing Voucher", docname, "status", "Completed")
@frappe.whitelist(methods=["POST"])
@frappe.whitelist()
def start_pcv_processing(docname: str):
# checked before the status is read, not inside the branch: otherwise an unentitled caller
# learns the document's status from whether this returns or throws
frappe.has_permission("Process Period Closing Voucher", "write", doc=docname, throw=True)
if frappe.db.get_value("Process Period Closing Voucher", docname, "status") in ["Queued", "Running"]:
frappe.has_permission("Process Period Closing Voucher", "write", doc=docname, throw=True)
initialize_parallel_threads(docname)
@frappe.whitelist(methods=["POST"])
@frappe.whitelist()
def pause_pcv_processing(docname: str):
frappe.has_permission("Process Period Closing Voucher", ptype="write", doc=docname, throw=True)
@@ -160,7 +157,7 @@ def pause_pcv_processing(docname: str):
qb.update(ppcvd).set(ppcvd.status, "Paused").where(ppcvd.name.isin(queued_dates)).run()
@frappe.whitelist(methods=["POST"])
@frappe.whitelist()
def cancel_pcv_processing(docname: str):
frappe.has_permission("Process Period Closing Voucher", ptype="cancel", doc=docname, throw=True)
@@ -176,7 +173,7 @@ def cancel_pcv_processing(docname: str):
qb.update(ppcvd).set(ppcvd.status, "Cancelled").where(ppcvd.name.isin(queued_dates)).run()
@frappe.whitelist(methods=["POST"])
@frappe.whitelist()
def resume_pcv_processing(docname: str):
frappe.has_permission("Process Period Closing Voucher", ptype="write", doc=docname, throw=True)
@@ -261,11 +258,8 @@ def get_gle_for_closing_account(pcv, dimension_balance, dimensions):
return gl_entry
@frappe.whitelist(methods=["POST"])
@frappe.whitelist()
def schedule_next_date(docname: str):
# marks a row Running and enqueues a long job, so it needs the same write check as the sibling controls
frappe.has_permission("Process Period Closing Voucher", ptype="write", doc=docname, throw=True)
timeout = frappe.db.get_single_value("Accounts Settings", "pcv_job_timeout") or 3600
ppcvd = qb.DocType("Process Period Closing Voucher Detail")

View File

@@ -320,13 +320,6 @@ def get_html(doc, filters, entry, col, res, ageing):
from frappe.www.printview import get_letter_head
letter_head = get_letter_head(doc, 0)
# render letter head content as a template so its Jinja resolves against the doc
if letter_head.get("content"):
# nosemgrep: frappe-semgrep-rules.rules.security.frappe-ssti
letter_head["content"] = frappe.render_template(letter_head["content"], {"doc": doc})
if letter_head.get("footer"):
# nosemgrep: frappe-semgrep-rules.rules.security.frappe-ssti
letter_head["footer"] = frappe.render_template(letter_head["footer"], {"doc": doc})
html = frappe.render_template(
template_path,
{

View File

@@ -78,7 +78,7 @@ erpnext.accounts.PurchaseInvoice = class PurchaseInvoice extends erpnext.buying.
const me = this;
super.refresh();
hide_fields(this.frm);
hide_fields(this.frm.doc);
// Show / Hide button
this.show_general_ledger();
erpnext.accounts.ledger_preview.show_accounting_ledger_preview(this.frm);
@@ -418,7 +418,7 @@ erpnext.accounts.PurchaseInvoice = class PurchaseInvoice extends erpnext.buying.
}
is_paid() {
hide_fields(this.frm);
hide_fields(this.frm.doc);
if (cint(this.frm.doc.is_paid)) {
this.frm.set_value("allocate_advances_automatically", 0);
this.frm.set_value("payment_terms_template", "");
@@ -482,26 +482,28 @@ cur_frm.script_manager.make(erpnext.accounts.PurchaseInvoice);
// Hide Fields
// ------------
function hide_fields(frm) {
const doc = frm.doc;
const parent_fields = ["due_date", "is_opening", "advances_section", "from_date", "to_date"];
function hide_fields(doc) {
var parent_fields = ["due_date", "is_opening", "advances_section", "from_date", "to_date"];
if (cint(doc.is_paid) == 1) {
frm.toggle_display(parent_fields, false);
hide_field(parent_fields);
} else {
for (const fieldname of parent_fields) {
const docfield = frappe.meta.docfield_map[doc.doctype][fieldname];
if (!docfield.hidden) frm.toggle_display(fieldname, true);
for (var i in parent_fields) {
var docfield = frappe.meta.docfield_map[doc.doctype][parent_fields[i]];
if (!docfield.hidden) unhide_field(parent_fields[i]);
}
}
const item_fields_stock = ["warehouse_section", "received_qty", "rejected_qty"];
var item_fields_stock = ["warehouse_section", "received_qty", "rejected_qty"];
if (frm.fields_dict["items"]) {
frm.fields_dict["items"].grid.set_column_disp(item_fields_stock, cint(doc.update_stock) == 1);
if (cur_frm.fields_dict["items"]) {
cur_frm.fields_dict["items"].grid.set_column_disp(
item_fields_stock,
cint(doc.update_stock) == 1 || cint(doc.is_return) == 1 ? true : false
);
}
frm.refresh_fields();
cur_frm.refresh_fields();
}
cur_frm.fields_dict.cash_bank_account.get_query = function (doc) {
@@ -710,7 +712,7 @@ frappe.ui.form.on("Purchase Invoice", {
},
update_stock: function (frm) {
hide_fields(frm);
hide_fields(frm.doc);
frm.fields_dict.items.grid.toggle_reqd("item_code", frm.doc.update_stock ? true : false);
},

View File

@@ -36,6 +36,7 @@ from erpnext.stock.doctype.serial_and_batch_bundle.test_serial_and_batch_bundle
make_serial_batch_bundle,
)
from erpnext.stock.doctype.stock_entry.test_stock_entry import get_qty_after_transaction
from erpnext.stock.serial_batch_identity import SerialBatchIdentity
from erpnext.stock.tests.test_utils import StockTestMixin
from erpnext.tests.utils import ERPNextTestSuite
@@ -2643,25 +2644,8 @@ class TestPurchaseInvoice(ERPNextTestSuite, StockTestMixin):
batch_no = "BATCH-PI-BNU-TPRBI-0001"
serial_nos = ["SNU-PI-TPRSI-0001", "SNU-PI-TPRSI-0002", "SNU-PI-TPRSI-0003"]
if not frappe.db.exists("Batch", batch_no):
frappe.get_doc(
{
"doctype": "Batch",
"batch_id": batch_no,
"item": batch_item,
}
).insert()
for serial_no in serial_nos:
if not frappe.db.exists("Serial No", serial_no):
frappe.get_doc(
{
"doctype": "Serial No",
"item_code": serial_item,
"serial_no": serial_no,
"company": "_Test Company",
}
).insert()
batch_no = SerialBatchIdentity("Batch").resolve(batch_item, [batch_no], create=True)[0]
serial_nos = SerialBatchIdentity("Serial No").resolve(serial_item, serial_nos, create=True)
pi = make_purchase_invoice(
item_code=batch_item,
@@ -3061,23 +3045,6 @@ class TestPurchaseInvoice(ERPNextTestSuite, StockTestMixin):
self.assertRaises(StockOverReturnError, return_doc.save)
def test_partial_returns_ignore_received_qty_without_update_stock(self):
from erpnext.controllers.sales_and_purchase_return import make_return_doc
invoice = make_purchase_invoice(qty=10, received_qty=10)
first_return = make_return_doc(invoice.doctype, invoice.name)
first_return.items[0].qty = -4
first_return.save().submit()
self.assertEqual(first_return.items[0].received_qty, -10)
second_return = make_return_doc(invoice.doctype, invoice.name)
second_return.items[0].qty = -6
second_return.save().submit()
self.assertEqual(second_return.docstatus, 1)
def test_apply_discount_on_grand_total(self):
"""
To test if after applying discount on grand total,

View File

@@ -2,10 +2,10 @@
# License: GNU General Public License v3. See license.txt
from frappe.model.document import Document
from erpnext.stock.serial_batch_display import SerialBatchReference
class PurchaseInvoiceItem(Document):
class PurchaseInvoiceItem(SerialBatchReference):
# begin: auto-generated types
# This code is auto-generated. Do not modify anything in this block.

View File

@@ -514,11 +514,6 @@ def validate_docs_for_voucher_types(doc_voucher_types):
def get_repost_allowed_types(
doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict
):
# Reached only from this doctype's own form (repost_accounting_ledger.js:8), and Repost
# Accounting Ledger is System-Manager-only, so the form is the boundary. `filters` is passed
# straight to db.get_all, which is why reaching it needs to be gated rather than merely typed.
frappe.has_permission("Repost Accounting Ledger", throw=True)
if txt:
filters.update({"document_type": ("like", f"%{txt}%")})

View File

@@ -123,8 +123,6 @@ class RepostPaymentLedger(Document):
def execute_repost_payment_ledger(docname: str):
"""Repost Payment Ledger Entries by background job."""
frappe.has_permission("Repost Payment Ledger", ptype="submit", doc=docname, throw=True)
job_name = "payment_ledger_repost_" + docname
frappe.enqueue(

View File

@@ -376,26 +376,9 @@ def _apply_sales_party_details(target_doc, source_doc, details):
@frappe.whitelist()
def get_received_items(reference_name: str, doctype: str, reference_fieldname: str):
# The only two targets this resolves a reference field for. Stating them rejects a caller
# supplied doctype that would otherwise be filtered on a column it does not have.
reference_fields = {
"Purchase Invoice": ("inter_company_invoice_reference", "Sales Invoice"),
"Purchase Order": ("inter_company_order_reference", "Sales Order"),
}
if doctype not in reference_fields:
frappe.throw(_("Invalid doctype {0}").format(doctype), frappe.PermissionError)
reference_field, source_doctype = reference_fields[doctype]
# `reference_name` is the caller's own document. The targets belong to the counterpart company
# and the caller legitimately may not be able to read them, so the source is what decides
# access here rather than the doctype being counted. doc= brings User Permissions in.
frappe.has_permission(source_doctype, doc=reference_name, throw=True)
# `reference_fieldname` is selected as a column below and its value becomes the result key,
# so an unchecked one returns any field of the item table to the caller.
if not frappe.get_meta(doctype + " Item").has_field(reference_fieldname):
frappe.throw(_("Invalid field {0}").format(reference_fieldname), frappe.PermissionError)
reference_field = "inter_company_invoice_reference"
if doctype == "Purchase Order":
reference_field = "inter_company_order_reference"
filters = {
reference_field: reference_name,

View File

@@ -52,7 +52,7 @@ from erpnext.stock.doctype.stock_reconciliation.test_stock_reconciliation import
create_stock_reconciliation,
)
from erpnext.stock.get_item_details import get_item_tax_map
from erpnext.stock.utils import _get_incoming_rate, get_stock_balance
from erpnext.stock.utils import get_incoming_rate, get_stock_balance
from erpnext.tests.utils import ERPNextTestSuite
@@ -3356,7 +3356,7 @@ class TestSalesInvoice(ERPNextTestSuite):
rate = 0.0
for d in si.get("items"):
rate = _get_incoming_rate(
rate = get_incoming_rate(
{
"item_code": d.item_code,
"warehouse": d.warehouse,

View File

@@ -4,12 +4,12 @@
import frappe
from frappe import _
from frappe.model.document import Document
from erpnext.assets.doctype.asset.depreciation import get_disposal_account_and_cost_center
from erpnext.stock.serial_batch_display import SerialBatchReference
class SalesInvoiceItem(Document):
class SalesInvoiceItem(SerialBatchReference):
# begin: auto-generated types
# This code is auto-generated. Do not modify anything in this block.

View File

@@ -9,15 +9,10 @@ frappe.ui.form.on("Shipping Rule", {
},
company: function (frm) {
if (frm.previous_company !== frm.doc.company) {
frm.previous_company = frm.doc.company;
frm.set_value("account", "");
}
erpnext.accounts.dimensions.update_dimension(frm, frm.doctype);
},
refresh: function (frm) {
frm.previous_company = frm.doc.company;
frm.set_query("account", function () {
return {
filters: {

View File

@@ -52,23 +52,10 @@ class ShippingRule(Document):
# end: auto-generated types
def validate(self):
self.validate_account_company()
self.validate_from_to_values()
self.sort_shipping_rule_conditions()
self.validate_overlapping_shipping_rule_conditions()
def validate_account_company(self):
if not self.company or not self.account:
return
if frappe.get_cached_value("Account", self.account, "company") != self.company:
throw(
_("Shipping Account {0} does not belong to Company {1}").format(
frappe.bold(self.account), frappe.bold(self.company)
),
title=_("Invalid Shipping Account"),
)
def validate_from_to_values(self):
if self.calculate_based_on == "Fixed":
if self.conditions:

View File

@@ -15,37 +15,6 @@ class TestShippingRule(ERPNextTestSuite):
def setUp(self):
self.load_test_records("Shipping Rule")
def test_account_company_on_insert(self):
for rule_type in ("Selling", "Buying"):
with self.subTest(shipping_rule_type=rule_type):
shipping_rule = frappe.copy_doc(self.globalTestRecords["Shipping Rule"][0])
shipping_rule.label = f"{rule_type} Delivery"
shipping_rule.shipping_rule_type = rule_type
shipping_rule.company = "_Test Company 1"
shipping_rule.cost_center = None
with self.assertRaisesRegex(frappe.ValidationError, "does not belong to Company"):
shipping_rule.insert()
def test_account_company_on_update(self):
shipping_rule = create_shipping_rule("Selling", "Standard Delivery")
shipping_rule.company = "_Test Company 1"
shipping_rule.cost_center = None
with self.assertRaisesRegex(frappe.ValidationError, "does not belong to Company"):
shipping_rule.save()
shipping_rule.reload()
shipping_rule.company = "_Test Company 1"
shipping_rule.account = "_Test Account Shipping Charges - _TC1"
shipping_rule.cost_center = None
shipping_rule.save()
shipping_rule.reload()
self.assertEqual(shipping_rule.company, "_Test Company 1")
self.assertEqual(shipping_rule.account, "_Test Account Shipping Charges - _TC1")
shipping_rule.account = "_Test Account Shipping Charges - _TC"
with self.assertRaisesRegex(frappe.ValidationError, "does not belong to Company"):
shipping_rule.save()
def test_from_greater_than_to(self):
shipping_rule = frappe.copy_doc(self.globalTestRecords["Shipping Rule"][0])
shipping_rule.name = self.globalTestRecords["Shipping Rule"][0].get("name")

View File

@@ -145,12 +145,6 @@ def get_party_details(party: str | None, party_type: str, args: dict | None = No
out = {}
billing_address, shipping_address = None, None
if args:
# each of these names a single Address. A dict is read as a filter instead, and `get_doc`
# would resolve it to whichever Address happens to match, so only a plain name is accepted
for fieldname in ("billing_address", "shipping_address"):
if args.get(fieldname) and not isinstance(args.get(fieldname), str):
frappe.throw(_("Invalid address"), frappe.PermissionError)
if args.get("billing_address"):
billing_address = frappe.get_doc("Address", args.get("billing_address"))
if args.get("shipping_address"):

View File

@@ -26,7 +26,6 @@ import erpnext
from erpnext import get_company_currency
from erpnext.accounts.utils import get_fiscal_year
from erpnext.exceptions import InvalidAccountCurrency, PartyDisabled, PartyFrozen
from erpnext.stock.doctype.price_list.price_list import is_price_list_enabled
from erpnext.utilities.regional import temporary_flag
try:
@@ -395,17 +394,12 @@ def set_other_values(party_details, party, party_type):
def get_default_price_list(party):
"""Return the first enabled default price list for party (Document object)"""
price_list = party.get("default_price_list")
if is_price_list_enabled(price_list):
return price_list
"""Return default price list for party (Document object)"""
if party.get("default_price_list"):
return party.default_price_list
if party.doctype != "Customer":
return
price_list = frappe.get_cached_value("Customer Group", party.customer_group, "default_price_list")
if is_price_list_enabled(price_list):
return price_list
if party.doctype == "Customer":
return frappe.get_cached_value("Customer Group", party.customer_group, "default_price_list")
def set_price_list(party_details, party, party_type, given_price_list, pos=None):
@@ -418,7 +412,7 @@ def set_price_list(party_details, party, party_type, given_price_list, pos=None)
elif pos and party_type == "Customer":
customer_price_list = frappe.get_value("Customer", party.name, "default_price_list")
if is_price_list_enabled(customer_price_list):
if customer_price_list:
price_list = customer_price_list
else:
pos_price_list = frappe.get_value("POS Profile", pos, "selling_price_list")
@@ -426,9 +420,6 @@ def set_price_list(party_details, party, party_type, given_price_list, pos=None)
else:
price_list = get_default_price_list(party) or given_price_list
if price_list and not is_price_list_enabled(price_list):
price_list = None
if price_list:
party_details.price_list_currency = frappe.db.get_value(
"Price List", price_list, "currency", cache=True

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -171,7 +171,6 @@ class ReceivablePayableReport:
party_account=ple.account,
posting_date=ple.posting_date,
account_currency=ple.account_currency,
cost_center=ple.cost_center,
remarks=ple.remarks,
invoiced=0.0,
paid=0.0,

View File

@@ -1337,28 +1337,6 @@ class TestAccountsReceivable(ERPNextTestSuite, AccountsTestMixin):
row = report[1][0]
self.assertEqual(expected_data_after_payment, [row.voucher_no, row.cost_center, row.outstanding])
def test_cost_center_on_payment_before_invoice(self):
filters = {
"company": self.company,
"party_type": "Customer",
"party": [self.customer],
"report_date": today(),
"range": "30, 60, 90, 120",
}
si = self.create_sales_invoice(no_payment_schedule=True, do_not_submit=True)
si.posting_date = add_days(today(), 1)
si.due_date = si.posting_date
si.payment_schedule[0].due_date = si.posting_date
si.save().submit()
pe = self.create_payment_entry(si.name, do_not_submit=True)
pe.cost_center = self.cost_center
pe.save().submit()
row = next(row for row in execute(filters)[1] if row.voucher_no == pe.name)
self.assertEqual(row.cost_center, pe.cost_center)
def test_payment_terms_template_filters(self):
from erpnext.controllers.accounts_controller import get_payment_terms

View File

@@ -28,16 +28,16 @@
<br>{%= __("Clearance Date") %}: {%= frappe.datetime.str_to_user(data[i]["clearance_date"]) %}
{% } %}
</td>
<td style="text-align: right">{%= format_currency(data[i]["debit"], data[i]["account_currency"]) %}</td>
<td style="text-align: right">{%= format_currency(data[i]["credit"], data[i]["account_currency"]) %}</td>
<td style="text-align: right">{%= format_currency(data[i]["debit"]) %}</td>
<td style="text-align: right">{%= format_currency(data[i]["credit"]) %}</td>
</tr>
{% } else { %}
<tr>
<td></td>
<td></td>
<td>{%= data[i]["payment_entry"] %}</td>
<td style="text-align: right">{%= format_currency(data[i]["debit"], data[i]["account_currency"]) %}</td>
<td style="text-align: right">{%= format_currency(data[i]["credit"], data[i]["account_currency"]) %}</td>
<td style="text-align: right">{%= format_currency(data[i]["debit"]) %}</td>
<td style="text-align: right">{%= format_currency(data[i]["credit"]) %}</td>
</tr>
{% } %}
{% } %}

View File

@@ -114,7 +114,6 @@ def execute(filters=None):
filters={
"account_type": row["account_type"],
"is_group": 0,
"company": filters.company,
},
pluck="name",
)

View File

@@ -16,7 +16,7 @@ from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
)
from erpnext.accounts.report.financial_statements import get_cost_centers_with_children
from erpnext.stock.report.stock_ledger.stock_ledger import get_item_group_condition
from erpnext.stock.utils import _get_incoming_rate
from erpnext.stock.utils import get_incoming_rate
def execute(filters=None):
@@ -180,15 +180,13 @@ def get_data_when_grouped_by_invoice(columns, gross_profit_data, filters, group_
columns[0]["fieldname"] = "sales_invoice"
columns[0]["options"] = "Item"
columns[0]["width"] = 300
# removing the duplicate Item Code column and moving Item Name before Customer
# removing Item Code and Item Name columns
supplier_master_name = frappe.db.get_single_value("Buying Settings", "supp_master_name")
customer_master_name = frappe.db.get_single_value("Selling Settings", "cust_master_name")
if supplier_master_name == "Supplier Name" and customer_master_name == "Customer Name":
del columns[4]
columns.insert(1, columns.pop(4))
del columns[4:6]
else:
del columns[5]
columns.insert(1, columns.pop(5))
del columns[5:7]
total_base_amount = 0
total_buying_amount = 0
@@ -969,7 +967,7 @@ class GrossProfitGenerator:
if row.serial_and_batch_bundle:
args.update({"serial_and_batch_bundle": row.serial_and_batch_bundle})
average_buying_rate = _get_incoming_rate(args)
average_buying_rate = get_incoming_rate(args)
self.average_buying_rate[key] = flt(average_buying_rate)
return self.average_buying_rate[key]

View File

@@ -3,7 +3,7 @@
import frappe
from frappe import _
from frappe.query_builder.functions import Coalesce, Min, Sum
from frappe.query_builder.functions import Coalesce, Max, Min, Sum
from frappe.utils import cstr
@@ -47,23 +47,19 @@ def get_columns(filters):
def get_pos_sales_payment_data(filters):
sales_invoice_data = get_pos_invoice_data(filters)
labels = get_pos_row_labels(filters)
data = []
for row in sales_invoice_data:
label = labels.get(get_pos_row_key(row)) or frappe._dict()
data.append(
[
row["posting_date"],
row["owner"],
label.mode_of_payment,
row["net_total"],
row["total_taxes"],
row["paid_amount"],
row["warehouse"],
label.cost_center,
]
)
data = [
[
row["posting_date"],
row["owner"],
row["mode_of_payment"],
row["net_total"],
row["total_taxes"],
row["paid_amount"],
row["warehouse"],
row["cost_center"],
]
for row in sales_invoice_data
]
return data
@@ -127,17 +123,25 @@ def apply_conditions(query, a, filters):
return query
def get_invoice_item_totals():
"""One row per invoice: summed item base_total, plus warehouse and cost_center off its first line."""
def get_pos_invoice_data(filters):
sii = frappe.qb.DocType("Sales Invoice Item")
sip = frappe.qb.DocType("Sales Invoice Payment")
si = frappe.qb.DocType("Sales Invoice")
# t1: one row per invoice with the summed item base_total. warehouse and cost_center describe an
# item line, not the invoice, and an invoice may carry several. warehouse then becomes an outer
# grouping key below, so which line wins decides how rows are partitioned and what each row totals
# -- not merely which label is shown. Max() over text is a sort, and MariaDB (case-folding) and
# PostgreSQL (byte order) resolve it differently, so take both off one real line instead.
# The representative is the first line the user entered: Min(idx) is an integer, so the pick is
# free of collation and is meaningful, rather than turning on an unrelated hash-named row.
grouped_items = (
frappe.qb.from_(sii)
.select(sii.parent, Sum(sii.amount).as_("base_total"), Min(sii.idx).as_("representative_idx"))
.groupby(sii.parent)
).as_("grouped_items")
representative_item = frappe.qb.DocType("Sales Invoice Item").as_("representative_item")
return (
t1 = (
frappe.qb.from_(grouped_items)
.inner_join(representative_item)
.on(
@@ -152,45 +156,12 @@ def get_invoice_item_totals():
)
)
def get_invoice_totals():
"""Invoice-level aggregates, grouped by the primary key so every plain column is dependent."""
si = frappe.qb.DocType("Sales Invoice")
return (
frappe.qb.from_(si)
.select(
si.docstatus,
si.company,
si.customer,
si.is_pos,
si.name,
si.posting_date,
si.owner,
si.creation,
Sum(si.base_total).as_("base_total"),
Sum(si.net_total).as_("net_total"),
Sum(si.total_taxes_and_charges).as_("total_taxes"),
Sum(si.base_paid_amount).as_("paid_amount"),
Sum(si.outstanding_amount).as_("outstanding_amount"),
)
.groupby(si.name)
)
def get_pos_row_key(row):
return (row.owner, row.posting_date, row.warehouse)
def get_representative_payments():
"""One payment line per invoice: the first the user entered."""
sip = frappe.qb.DocType("Sales Invoice Payment")
# t3: mode_of_payment per invoice, from one real payment line for the same reason
grouped_payments = (
frappe.qb.from_(sip).select(sip.parent, Min(sip.idx).as_("representative_idx")).groupby(sip.parent)
).as_("grouped_payments")
representative_payment = frappe.qb.DocType("Sales Invoice Payment").as_("representative_payment")
return (
t3 = (
frappe.qb.from_(grouped_payments)
.inner_join(representative_payment)
.on(
@@ -200,15 +171,26 @@ def get_representative_payments():
.select(grouped_payments.parent, representative_payment.mode_of_payment.as_("mode_of_payment"))
)
def get_pos_row_labels(filters):
"""cost_center and mode_of_payment off the earliest invoice in each row.
Ordered in Python rather than SQL, so no database collation applies to the tie-break.
"""
t1 = get_invoice_item_totals()
t3 = get_representative_payments()
a = get_invoice_totals()
# a: invoice-level aggregates. Grouped by the primary key (si.name), so the other plain si columns
# (incl. customer, needed by the customer filter) are functionally dependent and valid on Postgres.
a = (
frappe.qb.from_(si)
.select(
si.docstatus,
si.company,
si.customer,
si.is_pos,
si.name,
si.posting_date,
si.owner,
Sum(si.base_total).as_("base_total"),
Sum(si.net_total).as_("net_total"),
Sum(si.total_taxes_and_charges).as_("total_taxes"),
Sum(si.base_paid_amount).as_("paid_amount"),
Sum(si.outstanding_amount).as_("outstanding_amount"),
)
.groupby(si.name)
)
query = (
frappe.qb.from_(t1)
@@ -216,37 +198,6 @@ def get_pos_row_labels(filters):
.on(t3.parent == t1.parent)
.join(a)
.on((t1.parent == a.name) & (t1.base_total == a.base_total))
.select(
a.owner,
a.posting_date,
a.creation,
a.name,
t1.warehouse,
t1.cost_center,
t3.mode_of_payment,
)
.where(a.docstatus == 1)
)
query = apply_conditions(query, a, filters)
labels = {}
for row in query.run(as_dict=True):
key = get_pos_row_key(row)
current = labels.get(key)
if current is None or (row.creation, row.name) < (current.creation, current.name):
labels[key] = row
return labels
def get_pos_invoice_data(filters):
t1 = get_invoice_item_totals()
a = get_invoice_totals()
query = (
frappe.qb.from_(t1)
.join(a)
.on((t1.parent == a.name) & (t1.base_total == a.base_total))
.select(
a.posting_date,
a.owner,
@@ -254,7 +205,10 @@ def get_pos_invoice_data(filters):
Sum(a.total_taxes).as_("total_taxes"),
Sum(a.paid_amount).as_("paid_amount"),
Sum(a.outstanding_amount).as_("outstanding_amount"),
# mode_of_payment/cost_center are not in the outer GROUP BY -> Max() (deterministic, both engines)
Max(t3.mode_of_payment).as_("mode_of_payment"),
t1.warehouse,
Max(t1.cost_center).as_("cost_center"),
)
.where(a.docstatus == 1)
.groupby(a.owner, a.posting_date, t1.warehouse)

View File

@@ -9,8 +9,6 @@ from erpnext.accounts.report.sales_payment_summary.sales_payment_summary import
get_mode_of_payment_details,
get_mode_of_payments,
get_pos_invoice_data,
get_pos_row_key,
get_pos_row_labels,
)
from erpnext.tests.utils import ERPNextTestSuite
@@ -96,43 +94,12 @@ class TestSalesPaymentSummary(ERPNextTestSuite):
posted = {(row.warehouse, row.cost_center) for row in si.items}
self.assertGreater(len(posted), 1, "fixture must post more than one distinct pair")
labels = get_pos_row_labels(get_filters())
rows = get_pos_invoice_data(get_filters())
reported = [r for r in rows if r.get("warehouse") in {w for w, _ in posted}]
self.assertTrue(reported)
for row in reported:
label = labels[get_pos_row_key(row)]
self.assertIn((row["warehouse"], label.cost_center), posted)
def test_pos_row_labels_come_from_the_earliest_invoice(self):
"""The reported cost centre and payment mode must be one invoice's, and the same one's.
A row covers every invoice sharing an owner, date and warehouse, so neither column describes
it. Aggregating each independently sorts text -- which the two engines resolve differently --
and can pair one invoice's cost centre with another's payment mode.
"""
from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
warehouse = create_warehouse("_Test POS Row Labels")
card = create_mode_of_payment("_Test POS Card", "_Test Bank - _TC")
# cross the two picks: the earlier invoice holds the lower cost centre and the higher mode
posted = [("Main - _TC", card, "_Test Bank - _TC"), ("Sub - _TC", "Cash", "_Test Cash - _TC")]
for cost_center, mode_of_payment, account in posted:
si = create_sales_invoice_record()
si.is_pos = 1
si.items[0].warehouse = warehouse
si.items[0].cost_center = cost_center
si.append("payments", {"mode_of_payment": mode_of_payment, "account": account, "amount": 10000})
si.insert()
si.submit()
rows = [row for row in get_pos_invoice_data(get_filters()) if row.get("warehouse") == warehouse]
self.assertEqual(len(rows), 1, "the reported row count must not change")
label = get_pos_row_labels(get_filters())[get_pos_row_key(rows[0])]
self.assertEqual((label.cost_center, label.mode_of_payment), ("Main - _TC", card))
self.assertIn((row["warehouse"], row["cost_center"]), posted)
def test_get_mode_of_payments_details(self):
filters = get_filters()
@@ -215,21 +182,6 @@ def get_filters():
return {"from_date": "1900-01-01", "to_date": today(), "company": "_Test Company"}
def create_mode_of_payment(name, account, company="_Test Company"):
"""A POS payment row needs its mode to carry a default account for the company."""
if not frappe.db.exists("Mode of Payment", name):
frappe.get_doc(
{
"doctype": "Mode of Payment",
"mode_of_payment": name,
"type": "Bank",
"accounts": [{"company": company, "default_account": account}],
}
).insert()
return name
def create_sales_invoice_record(qty=1):
# return sales invoice doc object
return frappe.get_doc(

View File

@@ -181,27 +181,6 @@ class TaxService:
return amount, base_amount
# the only doctypes a `taxes_and_charges` Link points at; `master_doctype` is caller-supplied and reaches get_doc()
TAX_MASTER_DOCTYPES = ("Sales Taxes and Charges Template", "Purchase Taxes and Charges Template")
def validate_tax_master(master_doctype: str, master_name: str | None = None) -> None:
if master_doctype not in TAX_MASTER_DOCTYPES:
frappe.throw(_("Invalid tax master doctype"), frappe.PermissionError)
if not master_name:
return
# keep a company-restricted caller inside their own companies; this does NOT authorise the template itself
from erpnext.stock.doctype.company_restriction.company_restriction import get_allowed_companies
allowed_companies = get_allowed_companies(frappe.session.user, master_doctype)
if allowed_companies:
company = frappe.db.get_value(master_doctype, master_name, "company")
if company and company not in allowed_companies:
frappe.throw(_("Not permitted for {0}").format(company), frappe.PermissionError)
@frappe.whitelist()
def get_tax_rate(account_head: str) -> dict:
return frappe.get_cached_value("Account", account_head, ["tax_rate", "account_name"], as_dict=True)
@@ -214,8 +193,6 @@ def get_default_taxes_and_charges(
if not company:
return {}
validate_tax_master(master_doctype, tax_template)
if tax_template and company:
tax_template_company = frappe.get_cached_value(master_doctype, tax_template, "company")
if tax_template_company == company:
@@ -233,9 +210,6 @@ def get_default_taxes_and_charges(
def get_taxes_and_charges(master_doctype: str, master_name: str | None = None) -> list | None:
if not master_name:
return
validate_tax_master(master_doctype, master_name)
from frappe.model import child_table_fields, default_fields
tax_master = frappe.get_doc(master_doctype, master_name)

View File

@@ -1,6 +1,6 @@
import frappe
from erpnext.accounts.party import get_default_price_list, set_price_list
from erpnext.accounts.party import get_default_price_list
from erpnext.tests.utils import ERPNextTestSuite
@@ -16,46 +16,3 @@ class PartyTestCase(ERPNextTestSuite):
customer.save()
price_list = get_default_price_list(customer)
assert price_list is None
def test_disabled_party_default_should_fall_back_to_given_price_list(self):
customer = self.create_customer(default_price_list=self.create_price_list(enabled=0))
given_price_list = self.create_price_list(enabled=1)
party_details = frappe._dict()
set_price_list(party_details, customer, "Customer", given_price_list)
self.assertEqual(party_details.selling_price_list, given_price_list)
def test_disabled_given_price_list_should_not_be_set(self):
customer = self.create_customer()
party_details = frappe._dict()
set_price_list(party_details, customer, "Customer", self.create_price_list(enabled=0))
self.assertIsNone(party_details.selling_price_list)
def create_price_list(self, enabled):
price_list = frappe.get_doc(
{
"doctype": "Price List",
"price_list_name": frappe.generate_hash(length=10),
"currency": "INR",
"selling": 1,
"enabled": enabled,
}
).insert(ignore_permissions=True)
return price_list.name
def create_customer(self, **values):
customer = frappe.get_doc(
{
"doctype": "Customer",
"customer_name": frappe.generate_hash(length=10),
**values,
}
).insert(ignore_permissions=True, ignore_mandatory=True)
customer.customer_group = None
customer.save()
return customer

View File

@@ -2415,8 +2415,8 @@ class QueryPaymentLedger:
.groupby(ple.account, ple.voucher_type, ple.voucher_no, ple.party_type, ple.party)
).as_("grouped")
# KNOWN DIVERGENCE: Min(name) is a text sort. Hash names are not reliably lower case -- the
# trace-id prefix is not lowered -- so the engines can pick different rows here.
# Payment Ledger Entry has no autoname rule, so frappe names it by hash -- lower-case, which
# keeps Min(name) free of the collation divergence that picking Max() over free text has.
representative_ple = qb.DocType("Payment Ledger Entry").as_("representative_ple")
query_voucher_amount = (
qb.from_(grouped_voucher_amount)

View File

@@ -546,22 +546,15 @@ frappe.ui.form.on("Asset", {
},
set_finance_book: function (frm) {
let item_code = frm.doc.item_code;
let net_purchase_amount = frm.doc.net_purchase_amount;
frappe.call({
method: "erpnext.assets.doctype.asset.asset.get_item_details",
args: {
item_code: item_code,
item_code: frm.doc.item_code,
asset_category: frm.doc.asset_category,
net_purchase_amount: net_purchase_amount,
net_purchase_amount: frm.doc.net_purchase_amount,
},
callback: function (r, rt) {
if (
r.message &&
frm.doc.item_code === item_code &&
frm.doc.net_purchase_amount === net_purchase_amount
) {
if (r.message) {
frm.set_value("finance_books", r.message);
}
},
@@ -759,12 +752,10 @@ frappe.ui.form.on("Asset", {
},
net_purchase_amount: function (frm) {
if (frm.doc.finance_books && frm.doc.finance_books.length) {
if (frm.doc.finance_books) {
frm.doc.finance_books.forEach((d) => {
frm.events.set_depreciation_rate(frm, d);
});
} else if (frm.doc.item_code && frm.doc.calculate_depreciation && frm.doc.net_purchase_amount) {
frm.trigger("set_finance_book");
}
},

View File

@@ -1171,36 +1171,15 @@ def get_asset_value_after_depreciation(
asset_name: str,
finance_book: str | None = None,
):
# one of the three calling forms is the boundary; Asset itself excludes the roles holding Asset Value Adjustment write
if not any(
frappe.has_permission(dt, "write")
for dt in ("Asset Value Adjustment", "Asset Capitalization", "Asset Repair")
):
frappe.throw(_("Not permitted"), frappe.PermissionError)
asset = frappe.get_doc("Asset", asset_name)
_check_asset_company(asset.company)
if not asset.calculate_depreciation:
return flt(asset.value_after_depreciation)
return asset.get_value_after_depreciation(finance_book)
def _check_asset_company(company: str | None) -> None:
"""Keep a company-restricted caller inside their own companies; a no-op for everyone else."""
from erpnext.stock.doctype.company_restriction.company_restriction import get_allowed_companies
allowed_companies = get_allowed_companies(frappe.session.user, "Asset")
if allowed_companies and company and company not in allowed_companies:
frappe.throw(_("Not permitted for {0}").format(company), frappe.PermissionError)
@frappe.whitelist()
def has_active_capitalization(asset: str):
frappe.has_permission("Asset", doc=asset, throw=True)
active_capitalizations = frappe.db.count(
"Asset Capitalization", filters={"target_asset": asset, "docstatus": 1}
)
@@ -1213,21 +1192,7 @@ def get_values_from_purchase_doc(
item_code: str,
doctype: str,
):
# `doctype` is caller-supplied and reaches frappe.get_doc() as the doctype itself, so without
# this list any document with an `items` table could be read for its valuation rates. The two
# values below are the only ones this function handles — see the branches further down.
if doctype not in ("Purchase Receipt", "Purchase Invoice"):
frappe.throw(_("Invalid document type"), frappe.PermissionError)
# The caller is filling in an Asset (asset.js:794), and the Asset form is the boundary: Quality
# Manager writes Assets but holds read on neither Purchase Receipt nor Purchase Invoice, so the
# purchase document cannot be it.
frappe.has_permission("Asset", "write", throw=True)
purchase_doc = frappe.get_doc(doctype, purchase_doc_name)
_check_asset_company(purchase_doc.company)
matching_items = [item for item in purchase_doc.items if item.item_code == item_code]
if not matching_items:

View File

@@ -29,7 +29,7 @@ from erpnext.stock.get_item_details import (
get_item_warehouse_,
)
from erpnext.stock.stock_ledger import get_previous_sle
from erpnext.stock.utils import _get_incoming_rate, check_warehouse_company
from erpnext.stock.utils import get_incoming_rate
force_fields = [
"target_item_name",
@@ -191,7 +191,7 @@ class AssetCapitalization(StockController):
cumulative_qty += flt(d.stock_qty)
args = self.get_args_for_incoming_rate(d)
args["qty"] = -1 * cumulative_qty
cumulative_rate = flt(_get_incoming_rate(args, raise_error_if_no_rate=False))
cumulative_rate = flt(get_incoming_rate(args, raise_error_if_no_rate=False))
cumulative_value = cumulative_rate * cumulative_qty
row_value = cumulative_value - prev_cumulative_value
@@ -326,8 +326,6 @@ class AssetCapitalization(StockController):
@frappe.whitelist()
def set_warehouse_details(self):
self.check_permission("write")
for d in self.get("stock_items"):
if d.item_code and d.warehouse:
args = self.get_args_for_incoming_rate(d)
@@ -338,8 +336,6 @@ class AssetCapitalization(StockController):
@frappe.whitelist()
def set_asset_values(self):
self.check_permission("write")
for d in self.get("asset_items"):
if d.asset:
finance_book = d.get("finance_book") or self.get("finance_book")
@@ -515,24 +511,8 @@ class AssetCapitalization(StockController):
)
def check_capitalization_access(company: str | None = None) -> None:
"""Every lookup in this file feeds the Asset Capitalization form, so that form is the boundary."""
frappe.has_permission("Asset Capitalization", throw=True)
if not isinstance(company, str) or not company:
return
from erpnext.stock.doctype.company_restriction.company_restriction import get_allowed_companies
allowed_companies = get_allowed_companies(frappe.session.user, "Asset Capitalization")
if allowed_companies and company not in allowed_companies:
frappe.throw(_("Not permitted for {0}").format(company), frappe.PermissionError)
@frappe.whitelist()
def get_target_item_details(item_code: str | None = None, company: str | None = None):
check_capitalization_access(company)
out = frappe._dict()
# Get Item Details
@@ -559,8 +539,6 @@ def get_target_item_details(item_code: str | None = None, company: str | None =
@frappe.whitelist()
def get_target_asset_details(asset: str | None = None, company: str | None = None):
check_capitalization_access(company)
out = frappe._dict()
# Get Asset Details
@@ -646,12 +624,10 @@ def get_warehouse_details(ctx: ItemDetailsCtx) -> frappe._dict:
frappe.has_permission("Item", doc=ctx.item_code, throw=True)
frappe.has_permission("Warehouse", doc=ctx.warehouse, throw=True)
frappe.has_permission("Stock Ledger Entry", throw=True)
# inherited from get_incoming_rate before the split; _get_incoming_rate does not scope
check_warehouse_company(ctx.warehouse)
out = frappe._dict(
{
"actual_qty": get_previous_sle(ctx).get("qty_after_transaction") or 0,
"valuation_rate": _get_incoming_rate(ctx, raise_error_if_no_rate=False),
"valuation_rate": get_incoming_rate(ctx, raise_error_if_no_rate=False),
}
)
return out
@@ -660,8 +636,6 @@ def get_warehouse_details(ctx: ItemDetailsCtx) -> frappe._dict:
@frappe.whitelist()
@erpnext.normalize_ctx_input(ItemDetailsCtx)
def get_consumed_asset_details(ctx: ItemDetailsCtx) -> frappe._dict:
check_capitalization_access(ctx.get("company"))
out = frappe._dict()
asset_details = frappe._dict()
@@ -708,8 +682,6 @@ def get_consumed_asset_details(ctx: ItemDetailsCtx) -> frappe._dict:
@frappe.whitelist()
@erpnext.normalize_ctx_input(ItemDetailsCtx)
def get_service_item_details(ctx: ItemDetailsCtx) -> frappe._dict:
check_capitalization_access(ctx.get("company"))
out = frappe._dict()
item = frappe._dict()
@@ -734,8 +706,6 @@ def get_service_item_details(ctx: ItemDetailsCtx) -> frappe._dict:
def get_items_tagged_to_wip_composite_asset(params: dict | str):
params = frappe.parse_json(params)
check_capitalization_access(params.get("company") if isinstance(params, dict | frappe._dict) else None)
fields = [
"item_code",
"item_name",

View File

@@ -2,10 +2,10 @@
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
from erpnext.stock.serial_batch_display import SerialBatchReference
class AssetCapitalizationStockItem(Document):
class AssetCapitalizationStockItem(SerialBatchReference):
# begin: auto-generated types
# This code is auto-generated. Do not modify anything in this block.

View File

@@ -351,20 +351,6 @@ class AssetRepair(AccountsController):
add_asset_activity(self.asset, subject)
def check_asset_repair_access(company: str | None = None) -> None:
"""Both pickers below sit on the Asset Repair form, so that form is the boundary, not Purchase Invoice."""
frappe.has_permission("Asset Repair", throw=True)
if not isinstance(company, str) or not company:
return
from erpnext.stock.doctype.company_restriction.company_restriction import get_allowed_companies
allowed_companies = get_allowed_companies(frappe.session.user, "Asset Repair")
if allowed_companies and company not in allowed_companies:
frappe.throw(_("Not permitted for {0}").format(company), frappe.PermissionError)
@frappe.whitelist()
def get_downtime(failure_date: DateTimeLikeObject, completion_date: DateTimeLikeObject):
downtime = time_diff_in_hours(completion_date, failure_date)
@@ -385,8 +371,6 @@ def get_purchase_invoice(
Get Purchase Invoices that have expense accounts for non-stock items.
Only returns invoices with at least one non-stock, non-fixed-asset item with an expense account.
"""
check_asset_repair_access(filters.get("company") if isinstance(filters, dict) else None)
pi = DocType("Purchase Invoice")
pi_item = DocType("Purchase Invoice Item")
item = DocType("Item")
@@ -429,8 +413,6 @@ def get_expense_accounts(
Get expense accounts for non-stock (service) items from the purchase invoice.
Used as a query function for link fields.
"""
check_asset_repair_access()
purchase_invoice = filters.get("purchase_invoice")
if not purchase_invoice:
return []

View File

@@ -2,10 +2,10 @@
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
from erpnext.stock.serial_batch_display import SerialBatchReference
class AssetRepairConsumedItem(Document):
class AssetRepairConsumedItem(SerialBatchReference):
# begin: auto-generated types
# This code is auto-generated. Do not modify anything in this block.

View File

@@ -581,7 +581,7 @@ erpnext.buying.PurchaseOrderController = class PurchaseOrderController extends (
var item_length = me.frm.doc.items.length;
while (i < item_length) {
var qty = me.frm.doc.items[i].qty;
(r.message || []).forEach(function (d) {
(r.message[0] || []).forEach(function (d) {
if (
d.qty > 0 &&
qty > 0 &&

View File

@@ -226,7 +226,6 @@ class PurchaseOrder(BuyingController):
self.doctype, self.supplier, self.company, self.inter_company_order_reference
)
self.reset_default_field_value("set_warehouse", "items", "warehouse")
self.set_missing_terms()
def set_has_unit_price_items(self):
"""
@@ -611,19 +610,14 @@ def item_last_purchase_rate(name, conversion_rate, item_code, conversion_factor=
return item_last_purchase_rate
@frappe.whitelist(methods=["POST"])
@frappe.whitelist()
def close_or_unclose_purchase_orders(names: str | list, status: str):
frappe.has_permission("Purchase Order", "write", throw=True)
if not frappe.has_permission("Purchase Order", "write"):
frappe.throw(_("Not permitted"), frappe.PermissionError)
names = frappe.parse_json(names)
for name in names:
if not isinstance(name, str):
frappe.throw(_("Invalid name"), frappe.PermissionError)
# the check above is doctype level and never consults User Permissions, so on its own it
# lets a caller restricted to one company close another company's orders. Checking each
# document is what scopes it, and matches what update_status() below already does.
po = frappe.get_lazy_doc("Purchase Order", name, check_permission="submit")
po = frappe.get_lazy_doc("Purchase Order", name)
if po.docstatus == 1:
if status == "Closed":
if po.status not in ("Cancelled", "Closed") and (
@@ -654,7 +648,7 @@ def get_list_context(context=None):
return list_context
@frappe.whitelist(methods=["POST"])
@frappe.whitelist()
def update_status(status: str, name: str):
po = frappe.get_lazy_doc("Purchase Order", name, check_permission="submit")
po.update_status(status)

View File

@@ -2,10 +2,10 @@
# License: GNU General Public License v3. See license.txt
from frappe.model.document import Document
from erpnext.stock.serial_batch_display import SerialBatchReference
class PurchaseReceiptItemSupplied(Document):
class PurchaseReceiptItemSupplied(SerialBatchReference):
# begin: auto-generated types
# This code is auto-generated. Do not modify anything in this block.

View File

@@ -8,6 +8,7 @@ from frappe.contacts.doctype.contact.contact import get_full_name
from frappe.core.doctype.communication.email import make
from frappe.desk.form.load import get_attachments
from frappe.model.document import Document
from frappe.query_builder import Order
from frappe.utils import get_url
from frappe.utils.print_format import download_pdf
from frappe.utils.user import get_user_fullname
@@ -480,34 +481,32 @@ def get_supplier_tag():
def get_rfq_containing_supplier(
doctype: str | None, txt: str, searchfield: str | None, start: int, page_len: int, filters: dict
):
rfq_filters = [
["docstatus", "=", 1],
["company", "=", filters.get("company")],
]
rfq = frappe.qb.DocType("Request for Quotation")
rfq_supplier = frappe.qb.DocType("Request for Quotation Supplier")
if frappe.has_permission("Request for Quotation", "read"):
rfq_filters.append(["Request for Quotation Supplier", "supplier", "=", filters.get("supplier")])
else:
parents = frappe.get_all(
"Request for Quotation Supplier",
filters={"supplier": filters.get("supplier"), "parenttype": "Request for Quotation"},
pluck="parent",
distinct=True,
query = (
frappe.qb.from_(rfq)
.from_(rfq_supplier)
.select(rfq.name)
.distinct()
.select(rfq.transaction_date, rfq.company)
.where(
(rfq.name == rfq_supplier.parent)
& (rfq_supplier.supplier == filters.get("supplier"))
& (rfq.docstatus == 1)
& (rfq.company == filters.get("company"))
)
rfq_filters.append(["name", "in", parents or [""]])
.orderby(rfq.transaction_date, order=Order.asc)
.limit(page_len)
.offset(start)
)
if txt:
rfq_filters.append(["name", "like", f"%{txt}%"])
query = query.where(rfq.name.like(f"%%{txt}%%"))
if filters.get("transaction_date"):
rfq_filters.append(["transaction_date", "=", filters.get("transaction_date")])
query = query.where(rfq.transaction_date == filters.get("transaction_date"))
return frappe.get_list(
"Request for Quotation",
filters=rfq_filters,
fields=["name", "transaction_date", "company"],
group_by="name",
order_by="transaction_date asc",
limit_start=start,
limit_page_length=page_len,
)
rfq_data = query.run(as_dict=1)
return rfq_data

View File

@@ -242,16 +242,6 @@ def get_supplier_primary(
):
supplier = filters.get("supplier")
type = filters.get("type")
# `type` is caller-supplied and was interpolated straight into qb.DocType(), so any doctype on
# the site could be joined to Dynamic Link and read. The two pickers that call this
# (supplier.js:51,61) send only these two values.
if type not in ("Contact", "Address"):
frappe.throw(_("Invalid type"), frappe.PermissionError)
# authorise the party, not Contact/Address: the `if_owner` row on Address would empty the picker rather than error
frappe.has_permission("Supplier", doc=supplier, throw=True)
type_doctype = frappe.qb.DocType(type)
dynamic_link = frappe.qb.DocType("Dynamic Link")

View File

@@ -146,7 +146,11 @@ class SupplierScorecard(Document):
frappe.db.set_value("Supplier", self.supplier, fieldname, self.get(fieldname))
def get_timeline_data(doctype: str, name: str) -> dict[float, float]:
@frappe.whitelist()
def get_timeline_data(doctype: str, name: str):
# Get a list of all the associated scorecards
out = {}
timeline_data = {}
scorecards = frappe.get_all(
@@ -160,7 +164,8 @@ def get_timeline_data(doctype: str, name: str) -> dict[float, float]:
for single_date in daterange(sc.start_date, sc.end_date):
timeline_data[time.mktime(single_date.timetuple())] = sc.total_score
return timeline_data
out["timeline_data"] = timeline_data
return out
def daterange(start_date, end_date):

View File

@@ -6,5 +6,6 @@ def get_data():
"heatmap": True,
"heatmap_message": _("This covers all scorecards tied to this Setup"),
"fieldname": "supplier",
"method": "erpnext.buying.doctype.supplier_scorecard.supplier_scorecard.get_timeline_data",
"transactions": [{"label": _("Scorecards"), "items": ["Supplier Scorecard Period"]}],
}

View File

@@ -9,7 +9,6 @@ from erpnext.buying.doctype.supplier_scorecard.supplier_scorecard import (
get_scorecard_date,
make_all_scorecards,
)
from erpnext.buying.doctype.supplier_scorecard.supplier_scorecard_dashboard import get_data
from erpnext.tests.utils import ERPNextTestSuite
@@ -90,30 +89,6 @@ class TestSupplierScorecard(ERPNextTestSuite):
self.assertGreater(created, 0)
self.assertEqual(make_all_scorecards(doc.name), 0)
def test_dashboard_endpoint_returns_connection_count_and_heatmap(self):
supplier = create_test_supplier("_Test Supplier SC Dashboard")
frappe.db.set_value("Supplier", supplier, "creation", add_days(nowdate(), -75))
frappe.delete_doc_if_exists("Supplier Scorecard", supplier)
doc = make_supplier_scorecard()
doc.supplier = supplier
doc.name = supplier
doc.insert()
endpoint = get_data().get("method") or "frappe.desk.notifications.get_open_count"
dashboard = frappe.get_attr(endpoint)("Supplier Scorecard", doc.name)
counts = {link["doctype"]: link["count"] for link in dashboard["count"]["external_links_found"]}
periods = frappe.db.count("Supplier Scorecard Period", {"supplier": supplier})
self.assertGreater(periods, 0)
self.assertEqual(counts["Supplier Scorecard Period"], periods)
timeline_data = dashboard["timeline_data"]
self.assertTrue(timeline_data)
for timestamp, score in timeline_data.items():
self.assertIsInstance(timestamp, int | float)
self.assertIsInstance(score, int | float)
def make_supplier_scorecard():
my_doc = frappe.get_doc(valid_scorecard[0])

File diff suppressed because one or more lines are too long

View File

@@ -9,7 +9,7 @@
"doctype": "Print Format",
"font": "Inter",
"font_size": 13,
"format_data": "{\"header\":{\"columns\":[{\"label\":\"\",\"fields\":[]}]},\"sections\":[{\"label\":\"\",\"columns\":[{\"label\":\"\",\"fields\":[{\"label\":\"Custom HTML\",\"fieldname\":\"custom_html_jtLStRVi\",\"fieldtype\":\"HTML\",\"html\":\"<div>\\n <div style=\\\"color:#6b7280;\\\">\\n Supplier\\n </div>\\n</div>\",\"custom\":1},{\"label\":\"Supplier\",\"fieldname\":\"vendor\",\"fieldtype\":\"Link\",\"show_label\":\"hide\",\"custom_style\":\"font-weight: bold;\"}],\"width\":53},{\"label\":\"\",\"fields\":[{\"label\":\"Request for Quotation\",\"fieldname\":\"name\",\"fieldtype\":\"Data\",\"align\":\"left\",\"label_justify\":\"space-between\",\"custom_style\":\"font-weight: bold;\\nborder-bottom: 1px solid #e5e7eb;\\npadding-bottom: 10px;\",\"label_color\":\"#292929\"},{\"label\":\"Order Date\",\"fieldname\":\"transaction_date\",\"fieldtype\":\"Date\",\"align\":\"left\",\"label_justify\":\"space-between\",\"custom_style\":\"border-bottom: 1px solid #e5e7eb;\\npadding-bottom: 10px;\"},{\"label\":\"Required By\",\"fieldname\":\"schedule_date\",\"fieldtype\":\"Date\",\"align\":\"left\",\"label_justify\":\"space-between\",\"custom_style\":\"border-bottom: 1px solid #e5e7eb;\\npadding-bottom: 10px;\"}],\"width\":44}],\"show_label\":\"hide\",\"field_orientation\":\"left-right\",\"margin\":{\"top\":15,\"right\":12,\"bottom\":0,\"left\":12}},{\"label\":\"\",\"columns\":[{\"label\":\"\",\"fields\":[{\"label\":\"\",\"fieldname\":\"items\",\"fieldtype\":\"Table\",\"options\":\"Request for Quotation Item\",\"table_columns\":[{\"label\":\"No\",\"fieldname\":\"idx\",\"fieldtype\":\"Data\",\"width\":5},{\"label\":\"Item\",\"fieldname\":\"item_name\",\"fieldtype\":\"Data\",\"width\":21,\"merged_fields\":[{\"fieldname\":\"description\",\"fieldtype\":\"Text Editor\",\"style\":\"secondary\"}]},{\"label\":\"Code\",\"fieldname\":\"item_code\",\"fieldtype\":\"Link\",\"options\":\"Item\",\"width\":12},{\"label\":\"Quantity\",\"fieldname\":\"uom\",\"fieldtype\":\"Link\",\"options\":\"UOM\",\"width\":13,\"merged_fields\":[{\"fieldname\":\"qty\",\"fieldtype\":\"Float\",\"style\":\"secondary\"}],\"merge_direction\":\"horizontal\",\"column_condition\":\"print_settings.print_uom_after_quantity != 1\"},{\"label\":\"Quantity\",\"fieldname\":\"qty\",\"fieldtype\":\"Float\",\"width\":14,\"merged_fields\":[{\"fieldname\":\"uom\",\"fieldtype\":\"Link\",\"style\":\"secondary\"}],\"merge_direction\":\"horizontal\",\"column_condition\":\"print_settings.print_uom_after_quantity\"}],\"table_style\":\"lined\",\"table_bordered\":true,\"table_header\":\"styled\",\"table_cell_padding\":10,\"table_radius\":10,\"table_header_bg\":\"#f3f3f3\",\"show_label\":\"hide\"}]}],\"has_fields\":true,\"margin\":{\"top\":15,\"right\":0,\"bottom\":0,\"left\":0}},{\"label\":\"\",\"columns\":[{\"label\":\"\",\"fields\":[{\"label\":\"Divider\",\"fieldname\":\"divider_LeiIYjph\",\"fieldtype\":\"Divider\",\"custom\":1}]}]},{\"label\":\"\",\"columns\":[{\"label\":\"\",\"fields\":[{\"label\":\"Terms and Conditions Details\",\"fieldname\":\"terms\",\"fieldtype\":\"Text Editor\"}]}],\"margin\":{\"top\":5,\"right\":12,\"bottom\":0,\"left\":12}}],\"footer\":{\"columns\":[{\"label\":\"\",\"fields\":[]}],\"show_label\":\"hide\"}}",
"format_data": "{\"header\":{\"columns\":[{\"label\":\"\",\"fields\":[]}]},\"sections\":[{\"label\":\"\",\"columns\":[{\"label\":\"\",\"fields\":[{\"label\":\"Custom HTML\",\"fieldname\":\"custom_html_jtLStRVi\",\"fieldtype\":\"HTML\",\"html\":\"<div>\\n <div style=\\\"color:#6b7280;\\\">\\n Supplier\\n </div>\\n</div>\",\"custom\":1},{\"label\":\"Supplier\",\"fieldname\":\"vendor\",\"fieldtype\":\"Link\",\"show_label\":\"hide\",\"custom_style\":\"font-weight: bold;\"}],\"width\":53},{\"label\":\"\",\"fields\":[{\"label\":\"Request for Quotation\",\"fieldname\":\"name\",\"fieldtype\":\"Data\",\"align\":\"left\",\"label_justify\":\"space-between\",\"custom_style\":\"font-weight: bold;\\nborder-bottom: 1px solid #e5e7eb;\\npadding-bottom: 10px;\",\"label_color\":\"#292929\"},{\"label\":\"Order Date\",\"fieldname\":\"transaction_date\",\"fieldtype\":\"Date\",\"align\":\"left\",\"label_justify\":\"space-between\",\"custom_style\":\"border-bottom: 1px solid #e5e7eb;\\npadding-bottom: 10px;\"},{\"label\":\"Required By\",\"fieldname\":\"schedule_date\",\"fieldtype\":\"Date\",\"align\":\"left\",\"label_justify\":\"space-between\",\"custom_style\":\"border-bottom: 1px solid #e5e7eb;\\npadding-bottom: 10px;\"}],\"width\":44}],\"show_label\":\"hide\",\"field_orientation\":\"left-right\",\"margin\":{\"top\":15,\"right\":12,\"bottom\":0,\"left\":12}},{\"label\":\"\",\"columns\":[{\"label\":\"\",\"fields\":[{\"label\":\"\",\"fieldname\":\"items\",\"fieldtype\":\"Table\",\"options\":\"Request for Quotation Item\",\"table_columns\":[{\"label\":\"No\",\"fieldname\":\"idx\",\"fieldtype\":\"Data\",\"width\":5},{\"label\":\"Item\",\"fieldname\":\"item_name\",\"fieldtype\":\"Data\",\"width\":21},{\"label\":\"Code\",\"fieldname\":\"item_code\",\"fieldtype\":\"Link\",\"options\":\"Item\",\"width\":12},{\"label\":\"Quantity\",\"fieldname\":\"uom\",\"fieldtype\":\"Link\",\"options\":\"UOM\",\"width\":13,\"merged_fields\":[{\"fieldname\":\"qty\",\"fieldtype\":\"Float\",\"style\":\"secondary\"}],\"merge_direction\":\"horizontal\",\"column_condition\":\"print_settings.print_uom_after_quantity != 1\"},{\"label\":\"Quantity\",\"fieldname\":\"qty\",\"fieldtype\":\"Float\",\"width\":14,\"merged_fields\":[{\"fieldname\":\"uom\",\"fieldtype\":\"Link\",\"style\":\"secondary\"}],\"merge_direction\":\"horizontal\",\"column_condition\":\"print_settings.print_uom_after_quantity\"}],\"table_style\":\"lined\",\"table_bordered\":true,\"table_header\":\"styled\",\"table_cell_padding\":10,\"table_radius\":10,\"table_header_bg\":\"#f3f3f3\",\"show_label\":\"hide\"}]}],\"has_fields\":true,\"margin\":{\"top\":15,\"right\":0,\"bottom\":0,\"left\":0}},{\"label\":\"\",\"columns\":[{\"label\":\"\",\"fields\":[{\"label\":\"Divider\",\"fieldname\":\"divider_LeiIYjph\",\"fieldtype\":\"Divider\",\"custom\":1}]}]},{\"label\":\"\",\"columns\":[{\"label\":\"\",\"fields\":[{\"label\":\"Terms and Conditions Details\",\"fieldname\":\"terms\",\"fieldtype\":\"Text Editor\"}]}],\"margin\":{\"top\":5,\"right\":12,\"bottom\":0,\"left\":12}}],\"footer\":{\"columns\":[{\"label\":\"\",\"fields\":[]}],\"show_label\":\"hide\"}}",
"idx": 0,
"label_color": "#6b7280",
"line_breaks": 0,
@@ -17,7 +17,7 @@
"margin_left": 8.0,
"margin_right": 8.0,
"margin_top": 10.0,
"modified": "2026-09-16 11:31:38.723639",
"modified": "2026-07-24 17:19:05.063875",
"modified_by": "Administrator",
"module": "Buying",
"name": "Request for Quotation Classic",

View File

@@ -51,6 +51,7 @@ def get_data(filters):
mr_item.item_code.as_("item_code"),
Sum(Coalesce(mr_item.qty, 0)).as_("qty"),
Sum(Coalesce(mr_item.stock_qty, 0)).as_("stock_qty"),
Max(Coalesce(mr_item.stock_uom, "")).as_("stock_uom"),
Sum(Coalesce(mr_item.ordered_qty, 0)).as_("ordered_qty"),
Sum(Coalesce(mr_item.received_qty, 0)).as_("received_qty"),
(Sum(Coalesce(mr_item.stock_qty, 0)) - Sum(Coalesce(mr_item.received_qty, 0))).as_(
@@ -77,14 +78,19 @@ def get_data(filters):
def apply_representative_lines(rows):
"""Fill the line-level columns from one real Material Request Item line: the first by idx."""
"""Fill item_name/description/uom from one real Material Request Item line per group.
All three are editable per line, so a request listing the same item twice holds several values
per group. Aggregating them sorts text, and MariaDB folds case while PostgreSQL orders by byte
value, so the engines pick differently. Take the first line by idx.
"""
material_requests = list({row.material_request for row in rows})
representative = {}
if material_requests:
for line in frappe.get_all(
"Material Request Item",
filters={"parent": ("in", material_requests), "docstatus": 1},
fields=["parent", "item_code", "item_name", "description", "uom", "stock_uom"],
fields=["parent", "item_code", "item_name", "description", "uom"],
order_by="idx",
):
representative.setdefault((line.parent, line.item_code), line)
@@ -94,7 +100,6 @@ def apply_representative_lines(rows):
row.item_name = line.item_name if line else None
row.description = line.description if line else None
row.uom = line.uom if line else ""
row.stock_uom = line.stock_uom if line else ""
def get_conditions(filters, query, mr, mr_item):

View File

@@ -74,54 +74,6 @@ class TestRequestedItemsToOrderAndReceive(ERPNextTestSuite):
self.assertEqual(len(data), 1)
self.assertEqual(getdate(data[0].required_date), getdate(add_days(today(), 1)))
def test_uom_pair_comes_from_one_line(self):
"""uom and stock_uom describe a line, so the reported pair must be one that was posted.
A request can list the same item twice in different units. Sourcing each column separately
can report one line's uom beside another's stock_uom -- a pair belonging to neither.
"""
create_item("Test MR Report Uom Item")
mr = frappe.copy_doc(self.globalTestRecords["Material Request"][0])
mr.transaction_date = today()
mr.schedule_date = add_days(today(), 5)
mr.set("items", mr.items[:1])
row = mr.items[0]
row.item_code = "Test MR Report Uom Item"
row.item_name = "Test MR Report Uom Item"
row.description = "Test MR Report Uom Item"
row.uom = "Nos"
row.schedule_date = mr.schedule_date
mr.append(
"items",
{
"item_code": "Test MR Report Uom Item",
"item_name": "Test MR Report Uom Item",
"description": "Test MR Report Uom Item",
"uom": "Nos",
"qty": row.qty,
"warehouse": row.warehouse,
"schedule_date": mr.schedule_date,
},
)
mr.submit()
# cross the two picks: the line holding the higher uom holds the lower stock_uom, so an
# independently aggregated pair cannot belong to either line
for line, uom, stock_uom in ((mr.items[0], "Nos", "Box"), (mr.items[1], "Box", "Nos")):
frappe.db.set_value(
"Material Request Item",
line.name,
{"uom": uom, "stock_uom": stock_uom},
update_modified=False,
)
posted = {("Nos", "Box"), ("Box", "Nos")}
data = get_data(self.filters.update({"item_code": "Test MR Report Uom Item"}))
self.assertEqual(len(data), 1)
self.assertIn((data[0].uom, data[0].stock_uom), posted)
self.assertEqual((data[0].uom, data[0].stock_uom), ("Nos", "Box"), "must be the first line by idx")
def setup_material_request(self, order=False, receive=False, days=0):
po = None
mr = frappe.copy_doc(self.globalTestRecords["Material Request"][0])

View File

@@ -1,139 +0,0 @@
# Copyright (c) 2026, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import json
import frappe
import frappe.permissions
from erpnext.buying.utils import get_linked_material_requests
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.stock.doctype.material_request.test_material_request import make_material_request
from erpnext.tests.utils import ERPNextTestSuite
def create_user_with_roles(email, *roles):
if frappe.db.exists("User", email):
user = frappe.get_doc("User", email)
else:
user = frappe.new_doc("User")
user.email = email
user.first_name = email.split("@", 1)[0]
user.insert(ignore_permissions=True)
user.set("roles", [])
for role in roles:
user.append("roles", {"role": role})
user.save(ignore_permissions=True)
# a user left without roles is downgraded to a Website User on save
frappe.db.set_value("User", email, "user_type", "System User")
return user
class TestGetLinkedMaterialRequests(ERPNextTestSuite):
def setUp(self):
self.material_request = make_material_request(item_code="_Test Item")
def test_permitted_role_can_fetch_linked_material_requests(self):
create_user_with_roles("test_buying_purchase_user@example.com", "Purchase User")
with self.set_user("test_buying_purchase_user@example.com"):
rows = get_linked_material_requests(["_Test Item"])
self.assertIn(self.material_request.name, {row.mr_name for row in rows})
def test_populated_result_is_a_flat_list_of_rows(self):
"""Both callers iterate the response directly, so it has to stay a flat list of rows
rather than a list of lists."""
create_user_with_roles("test_buying_purchase_user@example.com", "Purchase User")
with self.set_user("test_buying_purchase_user@example.com"):
rows = get_linked_material_requests(["_Test Item"])
self.assertIsInstance(rows, list)
self.assertTrue(rows)
for row in rows:
self.assertNotIsInstance(row, list | tuple)
self.assertIsInstance(row, dict)
for fieldname in ("mr_name", "mr_item", "item_code", "qty"):
self.assertIn(fieldname, row)
def test_empty_result_is_a_flat_empty_list(self):
item_without_request = make_item("_Test Item Without Material Request").name
create_user_with_roles("test_buying_purchase_user@example.com", "Purchase User")
with self.set_user("test_buying_purchase_user@example.com"):
rows = get_linked_material_requests([item_without_request])
self.assertEqual(rows, [])
def test_a_single_item_code_is_treated_as_one_code(self):
"""A lone code must be read as one item code, not iterated character by character."""
create_user_with_roles("test_buying_purchase_user@example.com", "Purchase User")
with self.set_user("test_buying_purchase_user@example.com"):
rows = get_linked_material_requests(json.dumps("_Test Item"))
self.assertIn(self.material_request.name, {row.mr_name for row in rows})
def test_items_that_are_not_item_codes_are_rejected(self):
"""Anything that is not a `str` or a `list` is already refused by the type annotation,
so these are the malformed inputs that reach the method."""
create_user_with_roles("test_buying_purchase_user@example.com", "Purchase User")
bad_inputs = (
"not json at all",
[{"item_code": "_Test Item"}],
[["_Test Item"]],
[None],
)
with self.set_user("test_buying_purchase_user@example.com"):
for bad_items in bad_inputs:
with self.subTest(items=bad_items):
self.assertRaises(frappe.ValidationError, get_linked_material_requests, bad_items)
def test_manufacturing_manager_can_fetch_linked_material_requests(self):
"""Manufacturing Manager holds write on Supplier Quotation and Request for Quotation,
both of which call this method, so it must hold Material Request read as well."""
create_user_with_roles("test_buying_mfg_manager@example.com", "Manufacturing Manager")
with self.set_user("test_buying_mfg_manager@example.com"):
rows = get_linked_material_requests(["_Test Item"])
self.assertIn(self.material_request.name, {row.mr_name for row in rows})
def test_unpermitted_role_cannot_fetch_linked_material_requests(self):
create_user_with_roles("test_buying_sales_user@example.com", "Sales User")
with self.set_user("test_buying_sales_user@example.com"):
self.assertRaises(frappe.PermissionError, get_linked_material_requests, ["_Test Item"])
def test_role_with_only_select_permission_cannot_fetch_linked_material_requests(self):
"""Material Request grants Delivery and Maintenance roles `select` and nothing else.
`select` is enough to list names, so the permitted set must be resolved through a
filter on the child table, which requires `read`."""
create_user_with_roles("test_buying_delivery_user@example.com", "Delivery User")
with self.set_user("test_buying_delivery_user@example.com"):
self.assertRaises(frappe.PermissionError, get_linked_material_requests, ["_Test Item"])
def test_results_are_restricted_by_user_permissions(self):
other_company_request = make_material_request(
item_code="_Test Item",
company="_Test Company 1",
warehouse="_Test Warehouse 2 - _TC1",
cost_center="Main - _TC1",
)
user = create_user_with_roles("test_buying_restricted_user@example.com", "Purchase User")
frappe.permissions.add_user_permission("Company", "_Test Company", user.name)
try:
with self.set_user(user.name):
mr_names = {row.mr_name for row in get_linked_material_requests(["_Test Item"])}
finally:
frappe.permissions.remove_user_permission("Company", "_Test Company", user.name)
self.assertIn(self.material_request.name, mr_names)
self.assertNotIn(other_company_request.name, mr_names)

View File

@@ -43,9 +43,7 @@ def update_last_purchase_rate(doc, is_submit) -> None:
frappe.throw(_("UOM Conversion factor is required in row {0}").format(d.idx))
# update last purchsae rate
frappe.db.set_value(
"Item", d.item_code, "last_purchase_rate", flt(last_purchase_rate), update_modified=False
)
frappe.db.set_value("Item", d.item_code, "last_purchase_rate", flt(last_purchase_rate))
def validate_for_items(doc) -> None:
@@ -131,33 +129,7 @@ def get_linked_material_requests(items: str | list):
Retrieve Material Requests linked to a list of items.
"""
try:
items = frappe.parse_json(items)
except (TypeError, ValueError):
frappe.throw(_("Items must be a list of Item codes"))
if isinstance(items, str):
items = [items]
if not isinstance(items, list | tuple) or any(not isinstance(item, str) for item in items):
frappe.throw(_("Items must be a list of Item codes"))
permitted_material_requests = frappe.get_list(
"Material Request",
filters=[
["material_request_type", "=", "Purchase"],
["docstatus", "=", 1],
["status", "!=", "Stopped"],
["per_ordered", "<", 99.99],
["Material Request Item", "item_code", "in", items],
],
pluck="name",
distinct=True,
)
if not permitted_material_requests:
return []
items = frappe.parse_json(items)
mr_list = []
mr = frappe.qb.DocType("Material Request")
@@ -174,7 +146,6 @@ def get_linked_material_requests(items: str | list):
mr_item.item_code,
mr_item.name.as_("mr_item"),
)
.where(mr.name.isin(permitted_material_requests))
.where(mr_item.item_code == item)
.where(mr.material_request_type == "Purchase")
.where(mr.per_ordered < 99.99)

View File

@@ -258,8 +258,6 @@ class AccountsController(TransactionBase):
if self.get("_action") and self._action != "update_after_submit":
self.set_missing_values(for_validate=True)
self.validate_price_list()
if self.get("_action") == "submit":
self.remove_bundle_for_non_stock_invoices()
@@ -348,28 +346,6 @@ class AccountsController(TransactionBase):
self.set_default_letter_head()
self.validate_company_in_accounting_dimension()
def validate_price_list(self):
price_list_field = "selling_price_list" if self.get("selling_price_list") else "buying_price_list"
price_list = self.get(price_list_field)
if not price_list or frappe.db.get_value("Price List", price_list, "enabled"):
return
# Returns retain a submitted voucher's pricing even if its price list is now disabled.
if (
self.get("is_return")
and self.get("return_against")
and price_list
== frappe.db.get_value(
self.doctype, {"name": self.return_against, "docstatus": 1}, price_list_field
)
):
return
frappe.throw(
_("Price List {0} is disabled").format(get_link_to_form("Price List", price_list)),
title=_("Disabled Price List"),
)
def set_default_letter_head(self):
if hasattr(self, "letter_head") and not self.letter_head:
self.letter_head = frappe.db.get_value("Company", self.company, "default_letter_head")
@@ -1212,44 +1188,32 @@ class AccountsController(TransactionBase):
self.unlink_ref_doc_from_po()
def unlink_ref_doc_from_po(self):
so_items = [item.name for item in self.items]
filters = {
"sales_order": self.name,
"sales_order_item": ["in", so_items],
"docstatus": ["<", 2],
}
so_items = []
for item in self.items:
so_items.append(item.name)
linked_po_items = frappe.get_all(
"Purchase Order Item", filters=filters, fields=["parent", "sales_order_item"]
)
if not linked_po_items:
return
frappe.db.set_value("Purchase Order Item", filters, {"sales_order": None, "sales_order_item": None})
self.update_ordered_qty_in_items({item.sales_order_item for item in linked_po_items})
linked_po = sorted({item.parent for item in linked_po_items})
frappe.msgprint(_("Purchase Orders {0} are unlinked").format("\n".join(linked_po)))
def update_ordered_qty_in_items(self, so_items: set[str]):
purchase_order_item = frappe.qb.DocType("Purchase Order Item")
ordered_qty = dict(
frappe.qb.from_(purchase_order_item)
.select(purchase_order_item.sales_order_item, Sum(purchase_order_item.stock_qty))
.where(
purchase_order_item.sales_order_item.isin(list(so_items))
& (purchase_order_item.docstatus == 1)
linked_po = list(
set(
frappe.get_all(
"Purchase Order Item",
filters={
"sales_order": self.name,
"sales_order_item": ["in", so_items],
"docstatus": ["<", 2],
},
pluck="parent",
)
)
.groupby(purchase_order_item.sales_order_item)
.run()
)
items_by_ordered_qty = defaultdict(list)
for so_item in so_items:
items_by_ordered_qty[flt(ordered_qty.get(so_item))].append(so_item)
if linked_po:
frappe.db.set_value(
"Purchase Order Item",
{"sales_order": self.name, "sales_order_item": ["in", so_items], "docstatus": ["<", 2]},
{"sales_order": None, "sales_order_item": None},
)
for qty, items in items_by_ordered_qty.items():
frappe.db.set_value("Sales Order Item", {"name": ["in", items]}, "ordered_qty", qty)
frappe.msgprint(_("Purchase Orders {0} are unlinked").format("\n".join(linked_po)))
def get_company_default(self, fieldname, ignore_validation=False):
from erpnext.accounts.utils import get_company_default

View File

@@ -23,11 +23,7 @@ from erpnext.stock.get_item_details import (
get_conversion_factor,
get_item_defaults,
)
<<<<<<< HEAD
from erpnext.stock.utils import _get_incoming_rate
=======
from erpnext.stock.utils import get_incoming_rate, is_serial_no_wise_valuation_disabled
>>>>>>> f09ce05 (feat: use serial no wise valuation switch on item (#59082))
from erpnext.stock.utils import get_incoming_rate
class QtyMismatchError(ValidationError):
@@ -184,7 +180,7 @@ class BuyingController(SubcontractingController):
for row in self.items:
if row.rate <= 0:
# override the rate with valuation rate
row.rate = _get_incoming_rate(
row.rate = get_incoming_rate(
{
"item_code": row.item_code,
"warehouse": row.warehouse,
@@ -668,7 +664,7 @@ class BuyingController(SubcontractingController):
if not posting_time:
posting_time = nowtime()
outgoing_rate = _get_incoming_rate(
outgoing_rate = get_incoming_rate(
{
"item_code": d.item_code,
"warehouse": d.get("from_warehouse"),
@@ -821,11 +817,9 @@ class BuyingController(SubcontractingController):
)
if self.is_return:
outgoing_rate = 0.0
if not is_serial_no_wise_valuation_disabled(d.item_code):
outgoing_rate = get_rate_for_return(
self.doctype, self.name, d.item_code, self.return_against, item_row=d
)
outgoing_rate = get_rate_for_return(
self.doctype, self.name, d.item_code, self.return_against, item_row=d
)
sle.update(
{

View File

@@ -40,11 +40,6 @@ def get_variant(
:param item: Template Item
:param args: A dictionary with "Attribute" as key and "Attribute Value" as value
"""
# The client callers are the Item form (item.js:1144, 1483), so the template Item is the boundary
# and `read` is loser-free: the roles that cannot read Item cannot open that form either. The two
# server-side callers (item.py:1083 on Item save, item_variant.py:393) already hold the template.
frappe.has_permission("Item", doc=template, throw=True)
item_template = frappe.get_doc("Item", template)
if item_template.variant_based_on == "Manufacturer" and manufacturer:
@@ -323,12 +318,6 @@ def find_variant(template, args, variant_item_code=None):
@frappe.whitelist()
def create_variant(item: str, args: dict | str, use_template_image: bool = False):
# Same right its sibling enqueue_multiple_variant_creation already requires — this builds an
# Item the caller is about to insert (item.js:1511) — plus record-level read on the template
# it copies from.
frappe.has_permission("Item", ptype="create", throw=True)
frappe.has_permission("Item", doc=item, throw=True)
use_template_image = frappe.parse_json(use_template_image)
args = frappe.parse_json(args)
@@ -353,7 +342,7 @@ def create_variant(item: str, args: dict | str, use_template_image: bool = False
return variant
@frappe.whitelist(methods=["POST"])
@frappe.whitelist()
def enqueue_multiple_variant_creation(item: str, args: dict | str, use_template_image: bool = False):
use_template_image = frappe.parse_json(use_template_image)
# There can be innumerable attribute combinations, enqueue
@@ -550,10 +539,6 @@ def make_variant_item_code(template_item_code, template_item_name, variant):
@frappe.whitelist()
def create_variant_doc_for_quick_entry(template: str, args: dict | str):
# Delegates to get_variant and create_variant below, which carry their own checks; this one
# fails fast rather than relying on that delegation.
frappe.has_permission("Item", doc=template, throw=True)
variant_based_on = frappe.db.get_value("Item", template, "variant_based_on")
args = frappe.parse_json(args)
if variant_based_on == "Manufacturer":

View File

@@ -482,71 +482,49 @@ def get_project_name(
doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict | None = None
):
proj = qb.DocType("Project")
meta = frappe.get_meta(doctype)
list_filters = [["status", "not in", ["Completed", "Cancelled", "On hold"]]]
qb_filter_and_conditions = []
qb_filter_or_conditions = []
if filters:
if filters.get("customer"):
# an `in` containing "" renders as `ifnull(customer,'') in (...)`: this customer, or none
list_filters.append(["customer", "in", [filters.get("customer"), ""]])
qb_filter_and_conditions.append(
(proj.customer == filters.get("customer")) | (proj.customer.isnull()) | (proj.customer == "")
)
if filters.get("company"):
list_filters.append(["company", "=", filters.get("company")])
qb_filter_and_conditions.append(proj.company == filters.get("company"))
# don't consider 'customer' and 'status' fields for pattern search, as they must be exactly matched
# permlevel fields go too: get_list refuses to filter on one, which would fail the whole call
searchfields = [
x
for x in meta.get_search_fields()
if x not in ["customer", "status"] and not (meta.get_field(x) and meta.get_field(x).permlevel)
]
qb_filter_and_conditions.append(proj.status.notin(["Completed", "Cancelled", "On hold"]))
q = qb.from_(proj)
fields = get_fields(doctype, ["name", "project_name"])
for x in fields:
q = q.select(proj[x])
# get_list applies the doctype check and the caller's record-level conditions
if not txt:
# no search term means no relevance ordering, so the whole query is expressible here and
# stays paginated in SQL rather than materialising every permitted name
return frappe.get_list(
"Project",
filters=list_filters,
fields=fields,
order_by="idx desc, name",
limit_start=start,
limit_page_length=page_len,
as_list=True,
# don't consider 'customer' and 'status' fields for pattern search, as they must be exactly matched
searchfields = [
x for x in frappe.get_meta(doctype).get_search_fields() if x not in ["customer", "status"]
]
# pattern search
if txt:
for x in searchfields:
qb_filter_or_conditions.append(proj[x].like(f"%{txt}%"))
q = q.where(Criterion.all(qb_filter_and_conditions)).where(Criterion.any(qb_filter_or_conditions))
# ordering
if txt:
# project_name containing search string 'txt' will be given higher precedence
q = q.orderby(
Case()
.when(
Locate(Lower(txt), Lower(proj.project_name)) > 0,
Locate(Lower(txt), Lower(proj.project_name)),
)
.else_(99999)
)
# with a search term, resolve the (already LIKE-narrowed) permitted names and rank them below:
# the relevance ordering is a CASE expression, which `order_by` rejects
permitted = frappe.get_list(
"Project",
filters=list_filters,
or_filters=[[x, "like", f"%{txt}%"] for x in searchfields],
pluck="name",
order_by="",
limit_page_length=0,
)
if not permitted:
return []
q = (
frappe.qb.from_(proj)
.select(*[proj[fieldname] for fieldname in fields])
.where(proj.name.isin(permitted))
)
# project_name containing search string 'txt' will be given higher precedence
q = q.orderby(
Case()
.when(
Locate(Lower(txt), Lower(proj.project_name)) > 0,
Locate(Lower(txt), Lower(proj.project_name)),
)
.else_(99999)
)
q = q.orderby(proj.idx, order=Order.desc).orderby(proj.name)
if page_len:
@@ -618,13 +596,15 @@ def get_batch_no(doctype: str, txt: str, searchfield: str, start: int, page_len:
if filters.get("is_inward"):
filtered_batches.extend(get_empty_batches(filters, start, page_len, filtered_batches, txt))
return filtered_batches
from erpnext.stock.serial_batch_identity import SerialBatchIdentity
labels = SerialBatchIdentity("Batch").labels([row[0] for row in filtered_batches])
return [(row[0], labels.get(row[0], row[0]), *row[1:]) for row in filtered_batches]
def get_empty_batches(filters, start, page_len, filtered_batches=None, txt=None):
query_filter = {"item": filters.get("item_code"), "disabled": 0}
if txt:
query_filter["name"] = ("like", f"%{txt}%")
or_filters = {"batch_id": ("like", f"%{txt}%"), "name": txt} if txt else None
exclude_batches = [batch[0] for batch in filtered_batches] if filtered_batches else []
if exclude_batches:
@@ -634,6 +614,7 @@ def get_empty_batches(filters, start, page_len, filtered_batches=None, txt=None)
"Batch",
fields=["name", "batch_qty"],
filters=query_filter,
or_filters=or_filters,
limit_start=start,
limit_page_length=page_len,
as_list=1,
@@ -709,7 +690,7 @@ def get_batches_from_stock_ledger_entries(searchfields, txt, filters, start=0, p
query = query.select(batch_table[field])
if txt:
txt_condition = batch_table.name.like(f"%{txt}%")
txt_condition = batch_table.batch_id.like(f"%{txt}%")
for field in [*searchfields, "name"]:
txt_condition |= batch_table[field].like(f"%{txt}%")
@@ -775,7 +756,7 @@ def get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start=0
bundle_query = bundle_query.select(batch_table[field])
if txt:
txt_condition = batch_table.name.like(f"%{txt}%")
txt_condition = batch_table.batch_id.like(f"%{txt}%")
for field in [*searchfields, "name"]:
txt_condition |= batch_table[field].like(f"%{txt}%")
@@ -820,33 +801,28 @@ def get_account_list(
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_blanket_orders(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
bo_filters = [
["docstatus", "=", 1],
["blanket_order_type", "=", filters.get("blanket_order_type")],
["company", "=", filters.get("company")],
]
bo = frappe.qb.DocType("Blanket Order")
bo_item = frappe.qb.DocType("Blanket Order Item")
if frappe.has_permission("Blanket Order", "read"):
bo_filters.append(["Blanket Order Item", "item_code", "=", filters.get("item")])
else:
parents = frappe.get_all(
"Blanket Order Item",
filters={"item_code": filters.get("item"), "parenttype": "Blanket Order"},
pluck="parent",
distinct=True,
query = (
frappe.qb.from_(bo)
.from_(bo_item)
.select(bo.name)
.distinct()
.select(bo.blanket_order_type, bo.to_date)
.where(
(bo_item.parent == bo.name)
& (bo_item.item_code == filters.get("item"))
& (bo.blanket_order_type == filters.get("blanket_order_type"))
& (bo.company == filters.get("company"))
& (bo.docstatus == 1)
)
bo_filters.append(["name", "in", parents or [""]])
)
if currency := filters.get("currency"):
bo_filters.append(["currency", "=", currency])
query = query.where(bo.currency == currency)
return frappe.get_list(
"Blanket Order",
filters=bo_filters,
fields=["name", "blanket_order_type", "to_date"],
group_by="name",
as_list=True,
)
return query.run()
@frappe.whitelist()
@@ -1042,22 +1018,21 @@ def get_doctype_wise_filters(filters):
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_batch_numbers(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
# get_list applies the select check and the caller's record-level conditions together
batch_filters = [["disabled", "=", 0], ["name", "like", f"%{txt}%"]]
batch = frappe.qb.DocType("Batch")
query = (
frappe.qb.from_(batch)
.select(batch.name, batch.batch_id, batch.item)
.where(
(batch.disabled == 0)
& (batch.expiry_date.isnull() | (batch.expiry_date >= today()))
& batch.batch_id.like(f"%{txt}%")
)
)
if filters and filters.get("item"):
batch_filters.append(["item", "=", filters.get("item")])
query = query.where(batch.item == filters.get("item"))
return frappe.get_list(
"Batch",
filters=batch_filters,
or_filters=[["expiry_date", "is", "not set"], ["expiry_date", ">=", today()]],
fields=["batch_id"],
order_by="batch_id",
limit_start=start,
limit_page_length=page_len,
as_list=True,
)
return query.orderby(batch.batch_id).limit(page_len).offset(start).run()
@frappe.whitelist()
@@ -1084,71 +1059,41 @@ def item_manufacturer_query(
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_purchase_receipts(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
pr_filters = [["docstatus", "=", 1], ["name", "like", f"%{txt}%"]]
pr = frappe.qb.DocType("Purchase Receipt")
pr_item = frappe.qb.DocType("Purchase Receipt Item")
query = (
frappe.qb.from_(pr)
.inner_join(pr_item)
.on(pr_item.parent == pr.name)
.select(pr.name)
.distinct() # one row per receipt, not per matching item line
.where((pr.docstatus == 1) & pr.name.like(f"%{txt}%"))
)
if filters and filters.get("item_code"):
if frappe.has_permission("Purchase Receipt", "read"):
# one indexed join, deduped by group_by below
pr_filters.append(["Purchase Receipt Item", "item_code", "=", filters.get("item_code")])
else:
# a select-only caller may use this picker but may not filter on a child table, so resolve
# the parents separately rather than losing the filter to a PermissionError
parents = frappe.get_all(
"Purchase Receipt Item",
filters={"item_code": filters.get("item_code"), "parenttype": "Purchase Receipt"},
pluck="parent",
distinct=True,
)
pr_filters.append(["name", "in", parents or [""]])
query = query.where(pr_item.item_code == filters.get("item_code"))
# get_list applies the select check and the caller's record-level conditions together.
# group_by, not distinct: it dedupes the child join just the same, and frappe drops ORDER BY
# from a distinct query on Postgres
return frappe.get_list(
"Purchase Receipt",
filters=pr_filters,
fields=["name"],
group_by="name",
order_by="name",
limit_start=start,
limit_page_length=page_len,
as_list=True,
)
return query.orderby(pr.name).limit(page_len).offset(start).run()
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_purchase_invoices(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
pi_filters = [["docstatus", "=", 1], ["name", "like", f"%{txt}%"]]
pi = frappe.qb.DocType("Purchase Invoice")
pi_item = frappe.qb.DocType("Purchase Invoice Item")
query = (
frappe.qb.from_(pi)
.inner_join(pi_item)
.on(pi_item.parent == pi.name)
.select(pi.name)
.distinct() # one row per invoice, not per matching item line
.where((pi.docstatus == 1) & pi.name.like(f"%{txt}%"))
)
if filters and filters.get("item_code"):
if frappe.has_permission("Purchase Invoice", "read"):
# one indexed join, deduped by group_by below
pi_filters.append(["Purchase Invoice Item", "item_code", "=", filters.get("item_code")])
else:
# a select-only caller may use this picker but may not filter on a child table, so resolve
# the parents separately rather than losing the filter to a PermissionError
parents = frappe.get_all(
"Purchase Invoice Item",
filters={"item_code": filters.get("item_code"), "parenttype": "Purchase Invoice"},
pluck="parent",
distinct=True,
)
pi_filters.append(["name", "in", parents or [""]])
query = query.where(pi_item.item_code == filters.get("item_code"))
# get_list applies the select check and the caller's record-level conditions together.
# group_by, not distinct: it dedupes the child join just the same, and frappe drops ORDER BY
# from a distinct query on Postgres
return frappe.get_list(
"Purchase Invoice",
filters=pi_filters,
fields=["name"],
group_by="name",
order_by="name",
limit_start=start,
limit_page_length=page_len,
as_list=True,
)
return query.orderby(pi.name).limit(page_len).offset(start).run()
@frappe.whitelist()
@@ -1235,30 +1180,9 @@ def get_payment_terms_for_references(
):
terms = []
if filters:
reference = filters.get("reference")
if not reference:
return terms
# only a plain name names one document: a filter operator (["like", "%"], ["!=", ""]) would
# widen this past the document the caller named, and past the one being authorised below
if not isinstance(reference, str):
frappe.throw(_("Invalid reference"), frappe.PermissionError)
# Payment Schedule is a child table and carries no permissions of its own, so the
# document the schedule belongs to is what decides access to these rows
# prefer the caller's own reference type; the lookup below cannot tell two parents of
# different types apart when they share a name
parenttype = filters.get("reference_doctype") or frappe.db.get_value(
"Payment Schedule", {"parent": reference}, "parenttype"
)
if not parenttype:
return terms
frappe.has_permission(parenttype, doc=reference, throw=True)
terms = frappe.db.get_all(
"Payment Schedule",
filters={"parent": reference, "parenttype": parenttype},
filters={"parent": filters.get("reference")},
fields=["payment_term"],
limit=page_len,
as_list=1,
@@ -1271,31 +1195,6 @@ def get_payment_terms_for_references(
def get_filtered_child_rows(
doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict
):
parent = filters.get("parent") if filters else None
# a plain name, never a filter operator: ["like", "%"] here would span parents, and only one
# of them would be the document authorised below
if not parent or not isinstance(parent, str):
frappe.throw(_("Parent document is required to search child rows"), frappe.PermissionError)
# `doctype` is caller supplied, so it has to be a child table before it is worth checking:
# any other doctype would put the caller's filters on a table this query never meant to read
if not frappe.get_meta(doctype).istable:
frappe.throw(_("{0} is not a child table").format(doctype), frappe.PermissionError)
# child tables carry no permissions of their own, so the document the rows hang off is what
# decides access. Read the parent type off the rows rather than off `filters`, so that the
# document being authorised is always the one being returned.
parenttype = frappe.db.get_value(doctype, {"parent": parent}, "parenttype")
if not parenttype or not frappe.db.exists(parenttype, parent):
return []
frappe.has_permission(doctype, parent_doctype=parenttype, throw=True)
# and on the parent record itself, so that User Permissions still apply
frappe.has_permission(parenttype, doc=parent, throw=True)
table = frappe.qb.DocType(doctype)
query = (
frappe.get_query(table, filters=filters)
@@ -1321,11 +1220,7 @@ def get_filtered_child_rows(
@frappe.validate_and_sanitize_search_inputs
def get_item_uom_query(doctype: str, txt: str, searchfield: str, start: int, page_len: int, filters: dict):
if frappe.get_single_value("Stock Settings", "allow_uom_with_conversion_rate_defined_in_item"):
item_code = filters.get("item_code")
if not item_code or not frappe.get_list("Item", filters=[["name", "=", item_code]], pluck="name"):
return []
query_filters = {"parent": item_code, "parenttype": "Item"}
query_filters = {"parent": filters.get("item_code")}
if txt:
query_filters["uom"] = ["like", f"%{txt}%"]
@@ -1340,7 +1235,7 @@ def get_item_uom_query(doctype: str, txt: str, searchfield: str, start: int, pag
as_list=1,
)
return frappe.get_list(
return frappe.get_all(
"UOM",
filters={"name": ["like", f"%{txt}%"], "enabled": 1},
fields=["name"],

View File

@@ -12,7 +12,7 @@ from frappe.utils import cint, flt, format_datetime, get_datetime
import erpnext
from erpnext.stock.serial_batch_bundle import get_batches_from_bundle
from erpnext.stock.utils import _get_incoming_rate, get_combine_datetime, get_valuation_method, getdate
from erpnext.stock.utils import get_combine_datetime, get_incoming_rate, get_valuation_method, getdate
class StockOverReturnError(frappe.ValidationError):
@@ -194,12 +194,7 @@ def validate_quantity(doc, key, args, ref, valid_items, already_returned_items):
if (doc.doctype == "Purchase Invoice" or doc.doctype == "Sales Invoice") and not doc.update_stock:
fields = ["qty"]
tracks_accepted_rejected_split = doc.doctype in (
"Purchase Receipt",
"Subcontracting Receipt",
) or (doc.doctype == "Purchase Invoice" and doc.update_stock)
if tracks_accepted_rejected_split:
if doc.doctype in ["Purchase Receipt", "Purchase Invoice", "Subcontracting Receipt"]:
if not args.get("return_qty_from_rejected_warehouse"):
fields.extend(["received_qty", "rejected_qty"])
else:
@@ -821,7 +816,7 @@ def get_rate_for_return(
rate = frappe.db.get_value(f"{voucher_type} Item", voucher_detail_no, "incoming_rate")
if rate is None and sle:
rate = _get_incoming_rate(
rate = get_incoming_rate(
{
"item_code": sle.item_code,
"warehouse": sle.warehouse,
@@ -1309,38 +1304,14 @@ def get_available_serial_nos(serial_nos, warehouse):
)
# the only doctypes these endpoints are called for; both reach get_value()/get_all() as the doctype itself
RETURNABLE_INVOICE_DOCTYPES = ("Sales Invoice", "POS Invoice")
@frappe.whitelist()
def get_payment_data(invoice: str):
# `invoice` may be either a Sales Invoice or a POS Invoice — both share the Sales Invoice
# Payment child table — so resolve which one it is before authorising rather than guessing.
parenttype = frappe.db.get_value("Sales Invoice Payment", {"parent": invoice}, "parenttype")
if not parenttype:
return []
if parenttype not in RETURNABLE_INVOICE_DOCTYPES:
frappe.throw(_("Invalid document type"), frappe.PermissionError)
frappe.has_permission(parenttype, doc=invoice, throw=True)
payment = frappe.db.get_all("Sales Invoice Payment", {"parent": invoice}, ["mode_of_payment", "amount"])
return payment
def validate_returnable_invoice(doctype: str, invoice: str) -> None:
if doctype not in RETURNABLE_INVOICE_DOCTYPES:
frappe.throw(_("Invalid document type"), frappe.PermissionError)
frappe.has_permission(doctype, doc=invoice, throw=True)
@frappe.whitelist()
def get_invoice_item_returned_qty(doctype: str, invoice: str, customer: str, item_row_name: str):
validate_returnable_invoice(doctype, invoice)
is_return, docstatus = frappe.db.get_value(doctype, invoice, ["is_return", "docstatus"])
if not is_return and docstatus == 1:
return get_returned_qty_map_for_row(invoice, customer, item_row_name, doctype)
@@ -1348,8 +1319,6 @@ def get_invoice_item_returned_qty(doctype: str, invoice: str, customer: str, ite
@frappe.whitelist()
def is_invoice_returnable(doctype: str, invoice: str):
validate_returnable_invoice(doctype, invoice)
is_return, docstatus, customer = frappe.db.get_value(
doctype, invoice, ["is_return", "docstatus", "customer"]
)

View File

@@ -13,7 +13,7 @@ from erpnext.controllers.sales_and_purchase_return import get_rate_for_return, i
from erpnext.controllers.stock_controller import StockController
from erpnext.stock.doctype.item.item import set_item_default
from erpnext.stock.get_item_details import get_bin_details, get_conversion_factor
from erpnext.stock.utils import _get_incoming_rate, get_combine_datetime, get_valuation_method
from erpnext.stock.utils import get_combine_datetime, get_incoming_rate, get_valuation_method
class SellingController(StockController):
@@ -588,7 +588,7 @@ class SellingController(StockController):
and self.get("is_return")
)
):
d.incoming_rate = _get_incoming_rate(
d.incoming_rate = get_incoming_rate(
{
"item_code": d.item_code,
"warehouse": d.warehouse,

View File

@@ -21,7 +21,8 @@ from erpnext.stock.doctype.serial_and_batch_bundle.serial_and_batch_bundle impor
)
from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
from erpnext.stock.serial_batch_bundle import SerialBatchCreation, get_serial_nos_from_bundle
from erpnext.stock.utils import _get_incoming_rate
from erpnext.stock.serial_batch_identity import SerialBatchIdentity
from erpnext.stock.utils import get_incoming_rate
class SubcontractingController(StockController):
@@ -89,7 +90,7 @@ class SubcontractingController(StockController):
}
)
rate = _get_incoming_rate(kwargs)
rate = get_incoming_rate(kwargs)
precision = frappe.get_precision("Subcontracting Receipt Supplied Item", "rate")
if flt(rate, precision) != flt(row.rate, precision):
row.rate = rate
@@ -433,9 +434,10 @@ class SubcontractingController(StockController):
consumed_bundles = voucher_bundle_data.get(bundle_key, frappe._dict())
if consumed_bundles.serial_nos:
self.available_materials[key]["serial_no"] = list(
set(self.available_materials[key]["serial_no"]) - set(consumed_bundles.serial_nos)
)
consumed_serials = set(consumed_bundles.serial_nos)
self.available_materials[key]["serial_no"] = [
sn for sn in self.available_materials[key]["serial_no"] if sn not in consumed_serials
]
if consumed_bundles.batch_nos:
for batch_no, qty in consumed_bundles.batch_nos.items():
@@ -449,9 +451,10 @@ class SubcontractingController(StockController):
from erpnext.deprecation_dumpster import deprecation_warning
deprecation_warning("unknown", "v16", "No instructions.")
self.available_materials[key]["serial_no"] = list(
set(self.available_materials[key]["serial_no"]) - set(get_serial_nos(row.serial_no))
)
consumed_serials = set(get_serial_nos(row.serial_no))
self.available_materials[key]["serial_no"] = [
sn for sn in self.available_materials[key]["serial_no"] if sn not in consumed_serials
]
# Will be deprecated in v16
if row.batch_no and not consumed_bundles.batch_nos:
@@ -531,6 +534,12 @@ class SubcontractingController(StockController):
self.__set_alternative_item_details(row)
serial_numbers = SerialBatchIdentity("Serial No").labels(
[sn for details in self.available_materials.values() for sn in details.serial_no]
)
for details in self.available_materials.values():
details.serial_no.sort(key=lambda sn: serial_numbers.get(sn) or sn)
self.__transferred_items = copy.deepcopy(self.available_materials)
self.__update_consumed_materials("Subcontracting Receipt")
@@ -682,7 +691,7 @@ class SubcontractingController(StockController):
return available_batches
def __get_serial_nos_for_bundle(self, qty, key):
available_sns = sorted(self.available_materials[key]["serial_no"])[0 : cint(qty)]
available_sns = self.available_materials[key]["serial_no"][0 : cint(qty)]
serial_nos = []
for serial_no in available_sns:
@@ -844,7 +853,7 @@ class SubcontractingController(StockController):
args["batch_no"] = rm_obj.batch_no
args["serial_no"] = rm_obj.serial_no
rm_obj.rate = _get_incoming_rate(args)
rm_obj.rate = get_incoming_rate(args)
def __set_batch_nos(self, bom_item, item_row, rm_obj, qty):
key = (rm_obj.rm_item_code, item_row.item_code, item_row.get(self.subcontract_data.order_field))

View File

@@ -1161,11 +1161,7 @@ def get_fg_reference_names(
"Subcontracting Inward Order Item",
limit_start=start,
limit_page_length=page_len,
filters={"parent": filters.get("parent"), "docstatus": 1},
or_filters=[
["name", "like", f"%{txt}%"],
["item_code", "like", f"%{txt}%"],
],
filters={"parent": filters.get("parent"), "item_code": ("like", f"%{txt}%"), "docstatus": 1},
fields=["name", "item_code", "delivery_warehouse"],
as_list=True,
order_by="idx",

View File

@@ -2410,10 +2410,4 @@ class TestAccountsController(ERPNextTestSuite):
si.set_posting_time = 1
si.posting_date = "2026-01-01"
si.save()
self.assertEqual(si.name, "SI-01-2026-00001")
si = create_sales_invoice(do_not_save=True)
si.set_posting_time = 1
si.posting_date = "2026-01-15"
si.save()
self.assertEqual(si.name, "SI-01-2026-00002")

View File

@@ -104,96 +104,3 @@ class TestReactivity(ERPNextTestSuite):
self.assertEqual(sales_invoice.items[0].uom, "Kg")
self.assertEqual(sales_invoice.items[0].conversion_factor, 1)
self.assertEqual(sales_invoice.items[0].stock_qty, sales_invoice.items[0].qty)
def add_optional_items_table(self):
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
create_custom_fields(
{
"Sales Order": [
{
"fieldname": "optional_items",
"label": "Optional Items",
"fieldtype": "Table",
"options": "Sales Order Item",
"insert_after": "items",
}
]
}
)
self.addCleanup(frappe.clear_cache, doctype="Sales Order")
self.addCleanup(frappe.delete_doc, "Custom Field", "Sales Order-optional_items")
def make_sales_order_with_optional_items(self, item_code, optional_item_codes):
from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
self.add_optional_items_table()
sales_order = make_sales_order(item_code=item_code, uom="Kg", rate=500, do_not_save=True)
for optional_item_code in optional_item_codes:
sales_order.append("optional_items", {"item_code": optional_item_code, "qty": 1})
return sales_order
def test_item_selection_updates_the_row_in_its_own_child_table(self):
from erpnext.stock.doctype.item.test_item import make_item
item = make_item(properties={"is_stock_item": 0, "stock_uom": "Kg"})
optional_item = make_item(properties={"is_stock_item": 0, "stock_uom": "Nos"})
sales_order = self.make_sales_order_with_optional_items(item.name, [item.name, optional_item.name])
standard_row = sales_order.items[0]
row_state = (standard_row.item_code, standard_row.uom, standard_row.rate)
edited_row = sales_order.optional_items[1]
sales_order.process_item_selection(
edited_row.idx, reset_item_details=True, parentfield="optional_items"
)
self.assertEqual(edited_row.item_name, optional_item.item_name)
self.assertEqual(edited_row.uom, "Nos")
self.assertEqual((standard_row.item_code, standard_row.uom, standard_row.rate), row_state)
def test_item_selection_ignores_a_row_that_is_gone(self):
from erpnext.stock.doctype.item.test_item import make_item
item = make_item(properties={"is_stock_item": 0, "stock_uom": "Kg"})
sales_order = self.make_sales_order_with_optional_items(item.name, [])
sales_order.process_item_selection(len(sales_order.items) + 1)
self.assertEqual(len(sales_order.items), 1)
def test_item_selection_rejects_a_field_that_is_not_a_child_table(self):
from erpnext.stock.doctype.item.test_item import make_item
item = make_item(properties={"is_stock_item": 0, "stock_uom": "Kg"})
sales_order = self.make_sales_order_with_optional_items(item.name, [])
self.assertRaises(
frappe.ValidationError, sales_order.process_item_selection, 1, parentfield="company"
)
def test_free_item_is_added_to_the_table_that_earned_it(self):
from erpnext.accounts.doctype.pricing_rule.test_pricing_rule import make_pricing_rule
from erpnext.stock.doctype.item.test_item import make_item
item = make_item(properties={"is_stock_item": 0, "stock_uom": "Kg"})
optional_item = make_item(properties={"is_stock_item": 0, "stock_uom": "Kg"})
free_item = make_item(properties={"is_stock_item": 0, "stock_uom": "Kg"})
make_pricing_rule(
title=f"_Test Free Item Rule {optional_item.name}",
selling=1,
item_code=optional_item.name,
price_or_product_discount="Product",
free_item=free_item.name,
free_qty=1,
)
sales_order = self.make_sales_order_with_optional_items(item.name, [optional_item.name])
sales_order.process_item_selection(sales_order.optional_items[0].idx, parentfield="optional_items")
self.assertEqual([row.item_code for row in sales_order.items], [item.name])
self.assertEqual(
[row.item_code for row in sales_order.optional_items],
[optional_item.name, free_item.name],
)

Some files were not shown because too many files have changed in this diff Show More