Compare commits

...

511 Commits

Author SHA1 Message Date
barredterra
2e8b96d816 test(manufacturing): cover MRP work orders created with a supplied BOM 2026-08-27 17:55:12 +02:00
barredterra
13e957bb7c feat(manufacturing): ask for a BOM before creating MRP work orders 2026-08-27 17:55:12 +02:00
barredterra
ad0d3e1fbf fix(manufacturing): classify MRP rows by purchase item, not missing BOM 2026-08-27 17:55:11 +02:00
Raffael Meyer
971b6fd49d fix(manufacturing): classify MRP items without a BOM as Purchase (#58509) 2026-08-27 17:55:08 +02:00
rohitwaghchaure
457283f2b0 Revert "refactor(stock): use db.count for the empty ledger check" (#58506)
Revert "refactor(stock): use db.count for the empty ledger check (#58486)"

This reverts commit 2866be2816.
2026-08-27 13:51:49 +00:00
Mihir Kandoi
0849f187e7 fix(projects): ignore cancelled invoices in timesheet portal (#58501) 2026-08-27 12:52:30 +00:00
Pandiyan P
a8ba713f80 fix(selling): check sales order permission before work order creation (#58492) 2026-08-27 12:05:43 +00:00
Pandiyan P
5f99a3418d fix(selling): check quotation write permission before marking lost (#58493) 2026-08-27 12:04:27 +00:00
Mihir Kandoi
b90e3d4656 fix(manufacturing): preserve job card qty in mr transfer (#58482) 2026-08-27 17:26:17 +05:30
Sudharsanan Ashok
2866be2816 refactor(stock): use db.count for the empty ledger check (#58486)
Align the existence check in `reset_bin_without_stock_ledger_entries()` with
the version-15-hotfix backport in #58434, per review feedback there.
2026-08-27 11:07:09 +00:00
Abdeali Chharchhodawala
6842ebb186 fix: improve message formatting and translation for validation issues (#58425) 2026-08-27 12:56:49 +02:00
Pandiyan P
4d4cf034b5 fix: clarify duplicate internal party messages (#58469) 2026-08-27 07:38:25 +00:00
Shllokkk
62e6e23581 fix: validate items against source Sales Order in Material Request (#58443) 2026-08-27 12:14:36 +05:30
Pandiyan P
0d90608bc1 fix(manufacturing): account for pending job card qty (#58466) 2026-08-27 12:12:46 +05:30
Pandiyan P
dd033cbc10 fix(stock): guard serial batch editor grid lookup (#58464) 2026-08-27 11:28:02 +05:30
Henil Maru
d6956790d8 fix: Work Order picks wrong Delivery Date when Sales Order has the same item in multiple rows (#58448) 2026-08-26 20:41:14 +05:30
MochaMind
4def9ed20a fix: sync translations from crowdin (develop) (#58458)
Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2026-08-26 13:13:08 +00:00
Diptanil Saha
b2489eaf1c ci: ignore python tests on update of **.po (#58457) 2026-08-26 18:29:57 +05:30
MochaMind
88948bab42 fix: sync translations from crowdin (#58349) 2026-08-26 14:44:17 +02:00
Diptanil Saha
98be36ef12 ci: use release token for crowdin translation push (#58454) 2026-08-26 12:16:49 +00:00
Diptanil Saha
687bb9c839 ci: fix crowdin branch (#58452) 2026-08-26 11:38:01 +00:00
rohitwaghchaure
731f03e2f2 feat: option to skip delivery note for service items in sales order (#58297)
* feat: option to skip delivery note for service items in sales order

* fix: reset stale skip delivery flags when setting is disabled

* fix: clear stale skip delivery note flag for non-sales order types

* fix: reset auto skip delivery flags on switch to maintenance order

* refactor: replace sales order skip_delivery_note with item level skip_delivery

* chore: drop skip delivery migration patch

* fix: honor legacy skip_delivery_note flag instead of data migration
2026-08-26 16:28:31 +05:30
Diptanil Saha
fd2057befa ci: crowdin actions (#58447)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 16:26:38 +05:30
Jatin3128
4cfa42921f fix(accounts): resolve subscription plans for any reference doctype in Payment Request (#58438)
fix(accounts): resolve subscription plans for any reference doctype and require read permission

get_subscription_details() was hardcoded to only resolve plans for
Sales Invoice, but is_a_subscription in make_payment_request() was set
for any reference doctype with a `subscription` field. Since Purchase
Invoice also has this field (supplier-side subscriptions), creating a
Payment Request against a subscription-linked Purchase Invoice set
is_a_subscription=1 with an empty subscription_plans table.

get_subscription_details() is also whitelisted with no permission
check, letting any logged-in user query which Subscription/plan/qty is
linked to an arbitrary Sales Invoice or Purchase Invoice.

Make plan resolution generic (guarded by Meta.has_field so doctypes
without a subscription field never hit a nonexistent column), derive
is_a_subscription from the resolved plans so the two can't disagree,
and add a frappe.has_permission read check before returning any data.
2026-08-26 16:16:40 +05:30
Jatin3128
8d2aa69e61 feat(accounts): split bank charges from exchange gain/loss on multi-currency transfers (#58071)
In a multi-currency Internal Transfer, the paid-vs-received difference was
booked entirely to Exchange Gain/Loss, so a bank charge entered as a deduction
pushed the Difference Amount non-zero and blocked submission. The exchange
gain/loss row now absorbs only the residual after user-entered deductions,
letting a Bank Charges row and the Exchange Gain/Loss row coexist and net to
zero.
2026-08-26 13:16:24 +05:30
Sudharsanan Ashok
3f29cdf8d2 feat(analytics): filter sales and purchase analytics by entity (#58402)
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-26 13:02:59 +05:30
Aarol D'Souza
ccc19f2554 Merge pull request #58351 from AarDG10/better-err-msg
fix(company): throw if linked to demo_company field
2026-08-26 12:53:01 +05:30
Mihir Kandoi
2ca02fb305 fix(stock): preserve LCV quantity across stock reconciliation (#58309)
Co-authored-by: RamachandranMD <ramachandran.md@finstein.ai>
2026-08-26 12:16:51 +05:30
Vishnu Priya Baskaran
1b81db4754 fix/payment-request-subscription-plans-population (#57494)
* fix(payment-request): populate subscription plans

* test: add coverage for subscription plans in payment request

---------

Co-authored-by: Dharanidharan2813 <dharanidharans1328@gmail.com>
2026-08-26 11:47:04 +05:30
Vishnu Priya Baskaran
918e5a28db fix(stock): carry accounting dimensions from Landed Cost Voucher char… (#56981)
* fix(stock): carry accounting dimensions from Landed Cost Voucher charges into GL entries

* feat(stock): add accounting dimension fields to Landed Cost Taxes and Charges

The charge row had no dimension fields, so a dimension marked mandatory for
Profit and Loss accounts could not be supplied anywhere on the voucher.

Add the accounting dimensions section, cost center and project, and register
the doctype in accounting_dimension_doctypes so custom dimension fields are
created on it. The section and column break are required for that hook to
place the generated fields correctly.

Cost center deliberately omits the ":Company" default used by Purchase Taxes
and Charges: this child table is also the additional costs table on Stock
Entry and Subcontracting Receipt, and auto-filling it there would change
existing postings.

* refactor(stock): group landed cost charges by expense account and dimensions

get_item_account_wise_lcv_entries keyed its inner map by expense account
alone, so two charge rows posting to the same account - whether in one voucher
or across vouchers - were merged. Amounts accumulated correctly but any
per-row context was lost to whichever row was seen first.

Key the grouping by (expense account, dimension values) and return a list of
charges per receipt item, each carrying its own dimensions, so rows that
differ only by dimension stay distinct.

Dimensions resolve from the charge row first, then the voucher item row.
Blanks are left blank so the GL composers can fall back to the receipt item
and receipt document as before.

* refactor(accounts): allow explicit accounting dimensions on add_gl_entry

get_gl_dict derives dimensions from the parent document and the item row, and
reads only custom dimensions off the item - never cost center or project.
Callers that need to set a dimension from some other source had no way to do
so except by building the args dict by hand.

Add a dimensions argument that is merged into the entry before get_gl_dict is
called, and thread it through the StockController and BaseGLComposer wrappers.

* fix(stock): carry landed cost charge dimensions onto the GL entries

Landed cost charges are posted into the receipt document's ledger, and their
expense account is a Profit and Loss account. Until now the entry took its
dimensions from the receipt item, which cannot know about a voucher created
after it was submitted, so a dimension mandatory for P&L accounts failed.

Take cost center, project and custom dimensions from the charge row, falling
back to the receipt item and receipt document when the row leaves them blank.
Only the leg posting to the charge account is affected; the reclass leg keeps
the item's dimensions so it still nets against the base item entry.

Also skip charges that prorate to zero, and hoist the landed cost lookup in
the Purchase Receipt composer out of the item loop - it was reloading every
voucher once per item.

* fix(stock): report missing mandatory dimensions on the Landed Cost Voucher row

Submitting a voucher re-makes the receipt document's GL entries, so a missing
mandatory dimension surfaced as a GL Entry error naming an account, raised
from the middle of update_landed_cost, with nothing pointing at the row that
caused it.

Check the charge rows during validate instead, against both the mandatory
for P&L / Balance Sheet flags and the per-account Accounting Dimension Filter,
and name the row, the dimension and the account in the message.

The check resolves values through the same fallback chain the GL composers
use, so it does not reject a voucher that would have posted successfully.

* test(stock): cover accounting dimensions on landed cost vouchers

Covers the charge row reaching the GL entry, cost center and project
overriding the receipt item, the blank row still falling back to it, and two
charge rows - and two vouchers - on the same expense account with different
dimensions staying separate entries.

Also covers the mandatory P&L dimension being satisfied from the charge row,
the missing one being reported on the voucher, dimensions surviving a repost,
and each dimension netting to zero on cancellation.

* refactor(lcv): apply custom dimension overrides via .update()

---------

Co-authored-by: nareshkannasln <nareshkannashanmugam@gmail.com>
Co-authored-by: rohitwaghchaure <rohitw1991@gmail.com>
2026-08-26 11:27:08 +05:30
Pandiyan P
c940bd1e66 fix(stock): validate serial inventory dimensions (#58394)
* fix(stock): validate serial inventory dimensions

* test(stock): cover serial inventory dimensions
2026-08-26 11:26:27 +05:30
Raffael Meyer
6bdc18b753 fix(asset): skip missing checkbox columns in asset type patch (#58416) 2026-08-26 02:46:20 +02:00
Khushi Rawat
35b3358a5d Merge pull request #58412 from khushi8112/fix-child-table-accounting-dimension
fix(accounts): prevent child table doctypes as accounting dimensions
2026-08-26 00:47:58 +05:30
khushi8112
55dd11f977 test(accounts): cover single doctype and non-scalar dimension safeguards 2026-08-26 00:36:29 +05:30
Shllokkk
6ddff9c386 Merge pull request #58400 from Shllokkk/reorder-email-single-company-perm
fix: send auto reorder email to all managers in single company setup
2026-08-25 17:38:19 +05:30
Raffael Meyer
84a32c40f4 fix(permissions): grant select on link targets to roles with write access (#58334)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 13:31:12 +02:00
khushi8112
7b32d07d1c fix(accounts): prevent child table doctypes as accounting dimensions 2026-08-25 16:09:59 +05:30
Mihir Kandoi
6a6f2ac127 ci: notify support when a PR is released (#58321) 2026-08-25 15:50:21 +05:30
Shllokkk
a01cc92184 test: auto reorder email reaches managers without company user permission 2026-08-25 15:44:29 +05:30
Shllokkk
ae119b1c29 fix: send auto reorder email to all managers in single company setup 2026-08-25 15:44:03 +05:30
Pandiyan P
ce23fcc055 fix: respect zero currency precision (#58395) 2026-08-25 10:06:06 +00:00
rohitwaghchaure
8b8422662c fix: production plan scheduling edge cases (#58388)
* fix: production plan scheduling edge cases

* fix: per-supplier schedule dates and item-wise amended row mapping

* fix: field-based matching for amended production plan rows

* fix: item-level lead time fallback for unconfigured suppliers

* fix: unambiguous amended row pairing and zero-day lead time fallback

* fix: clear sub assembly and material rows on production plan cancel
2026-08-25 14:45:05 +05:30
Sudharsanan Ashok
9cf76c6a68 fix(stock): keep pick list links when refetching stock entry items (#58374) 2026-08-25 07:50:50 +00:00
Sudharsanan Ashok
6fbcfade6c fix(stock): reset bin when no stock ledger entries remain (#58362)
* fix(stock): reset bin when no stock ledger entries remain

update_bin() only writes bins reachable through prev_sle_dict, and that
dict is empty once the last live sle for an item and warehouse is
cancelled or deleted. actual_qty is still recomputed, but stock_value
and valuation_rate stay stale and a repost cannot heal them, so bin
totals drift permanently from the stock balance.

zero those bins after the normal update, guarded by a re-check that no
live sle exists. also drop the prev_sle_dict seeding added earlier in
initialize_previous_data, which never took effect because
initialize_reposting() discards the dict before update_bin() reads it.

* test(stock): cover bin reset when ledger is empty

three cases that all leave an item and warehouse with no live sle:
cancelling the only voucher, deleting it with delete_linked_ledger_entries
on, and reposting over an already emptied ledger. each asserts actual_qty,
valuation_rate and stock_value are all zero.
2026-08-25 11:39:11 +05:30
Mihir Kandoi
5fa68dd068 fix(manufacturing): preserve job card transfer quantity (#58382) 2026-08-24 21:38:12 +05:30
Pandiyan P
ac2bacd3d0 fix: prevent duplicate supplier quotations from portal (#58377) 2026-08-24 18:32:12 +05:30
Pandiyan P
7ec34bab8d fix: hide supplier name in rfq portal (#58373) 2026-08-24 17:38:49 +05:30
Pandiyan P
75d6183bb6 fix: hide rfq status in supplier portal (#58368) 2026-08-24 16:29:05 +05:30
Vishnu Priya Baskaran
560ed25ff7 fix(italy): handle none price_list_rate in e-invoice xml generation (#58242) 2026-08-24 16:26:01 +05:30
Mohd Haris
ef7461cb5b fix: aggregate child warehouses in Stock Qty vs Serial No Count report (#58134)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Mihir Kandoi <kandoimihir@gmail.com>
2026-08-24 15:42:09 +05:30
Vishnu Priya Baskaran
abf94bc72d Fix/return qty validation different uom (#58298)
Co-authored-by: Afsal Syed <afsalsyed12@gmail.com>
2026-08-24 15:34:43 +05:30
Pandiyan P
59d80b29c4 fix: render missing terms before printing (#58358) 2026-08-24 14:53:08 +05:30
Mihir Kandoi
7149df398a fix: include time logs ending at midnight in timesheet billing summary (#58355) 2026-08-24 08:16:50 +00:00
Khushi Rawat
1b51f8cbd6 Merge pull request #58179 from aerele/fix-accounts-payable-supplier-group-filter
fix(accounts): supplier group filter not applied on accounts payable …
2026-08-24 12:22:21 +05:30
AarDG10
aaa3100efc fix(company): throw if linked to demo_company field
Throws an error msg if user is deleting demo company directly.
2026-08-24 11:10:50 +05:30
Raffael Meyer
64486f34e8 ci: bump po-review-action (#58346) 2026-08-23 17:05:22 +00:00
MochaMind
0ea36160fe fix: sync translations from crowdin (#58289) 2026-08-23 18:51:09 +02:00
MochaMind
6ba623e95f chore: update POT file (#58345) 2026-08-23 13:32:17 +02:00
Raffael Meyer
e71e08959f refactor: use Meta.get_translated_label (#58335) 2026-08-22 00:28:55 +02:00
Raffael Meyer
eae36c2d67 fix(i18n): translate get_label results at presentation with DocType context (#57217) 2026-08-21 23:19:36 +02:00
Jatin3128
275844d496 fix(journal-entry): avoid full grid re-render per row in set_exchange_rate (#58328)
refresh() loops over every row in the accounts child table and calls
set_exchange_rate() for each one. That function unconditionally ended
with frm.refresh_field("accounts"), rebuilding the whole grid (header,
pagination, current page) on every single row. For large child tables
this makes opening the form scale badly with row count.

Use grid.refresh_row(cdn) instead, which only re-renders the row that
actually changed and is a no-op for rows outside the current page.

Measured on a 1000-row Journal Entry: ~8.5s to first rendered row and
~7.9s of blocked main thread before this fix, ~2.3s and ~1.9s after.
2026-08-21 01:57:04 +05:30
Mihir Kandoi
624d402143 fix(projects): respect permissions in timesheet billing summary (#58320) 2026-08-20 09:43:18 +00:00
Mihir Kandoi
2328e6da94 fix: changing product bundle warehouse should change packed items war… (#58316) 2026-08-20 12:35:04 +05:30
Mihir Kandoi
941baffdda fix: correct to and from date filters in timesheet billing summary re… (#58317) 2026-08-20 04:12:30 +00:00
Pandiyan P
7faadb8282 fix: stop doubling totals in timesheet billing summary (#58311) 2026-08-20 02:26:23 +00:00
Mihir Kandoi
e8b214e7d3 chore: remove mistakenly committed file (#58310) 2026-08-19 15:49:02 +00:00
Mihir Kandoi
8320c77694 fix(manufacturing): scope secondary items to job card (#58260) 2026-08-19 20:53:53 +05:30
Mihir Kandoi
696f0df811 fix(stock): update pick list status for product bundles (#58306) 2026-08-19 20:52:47 +05:30
Mihir Kandoi
deeb787f57 fix(stock): support shared target UOM conversions (#58305) 2026-08-19 18:29:59 +05:30
Mihir Kandoi
478a2f4f4b fix(stock): ignore future stock during batch reservation (#58303) 2026-08-19 12:50:26 +00:00
Mihir Kandoi
cfca71782e fix(stock): preserve item UOM conversion factor (#58299) 2026-08-19 11:45:43 +00:00
Mihir Kandoi
f4ef7fdbcc fix(stock): preserve zero return incoming rates (#58302) 2026-08-19 11:45:29 +00:00
Mihir Kandoi
e5cd30c5ab fix(setup): handle Transaction Deletion Record CSV edge cases (#58300)
Co-authored-by: Pedro Barbosa <barbosamaverickv8@gmail.com>
2026-08-19 17:12:16 +05:30
Mihir Kandoi
8eeb0196e4 fix(stock): show backdated batches in stock entry (#58301) 2026-08-19 11:33:31 +00:00
rohitwaghchaure
d07f4bb857 feat: percentage based BOM (#58292)
* feat: percentage based BOM, fixed qty components and component qty tolerance

* fix: mandatory percentages, fixed qty explosion keys and expected qty aggregation

* fix: percentage BOM incompatible with semi FG tracking, fixed qty in production plan explosion

* refactor: remove component_qty_tolerance from Manufacturing Settings

* refactor: drop fixed qty components and consumption tolerance, keep percentage-based BOM only
2026-08-19 17:03:20 +05:30
Mihir Kandoi
2524af4758 fix: new docs should refetch incoming rates (#58097) 2026-08-19 12:36:22 +05:30
Sudharsanan Ashok
3a6e17a03d fix(stock): fetch item stock UOM in stock reconciliation (#58284) 2026-08-19 10:27:07 +05:30
Diptanil Saha
d070a1daa1 Merge pull request #58286 from diptanilsaha/template-text-context-escaping
fix: escape interpolated values in text positions across portal and desk templates
2026-08-19 02:30:23 +05:30
diptanilsaha
8d4c10871d fix: read project from url argument in project portal script 2026-08-19 02:06:25 +05:30
diptanilsaha
449c90f05f fix: escape event subject in crm activities template 2026-08-19 02:06:24 +05:30
diptanilsaha
96f51092a0 fix: escape help article title, description and category on support page 2026-08-19 02:06:22 +05:30
diptanilsaha
02434ee98c fix: escape partner introduction and address details in partner pages 2026-08-19 02:06:21 +05:30
diptanilsaha
09e1c6024d fix: escape project name and task subject in project portal templates 2026-08-19 02:06:20 +05:30
diptanilsaha
e88164e8c7 fix: escape items preview in transaction row template 2026-08-19 02:06:19 +05:30
diptanilsaha
a5aec7ed84 fix: escape party name and contact display on order page 2026-08-19 02:06:17 +05:30
Diptanil Saha
25dfcb17c8 fix: escape on status image for workstations in production status (#58279) 2026-08-18 17:58:23 +00:00
Diptanil Saha
a667cd7cc6 Merge pull request #58273 from diptanilsaha/template-output-escaping
fix: escape interpolated values in portal, print and desk templates
2026-08-18 23:09:09 +05:30
diptanilsaha
93d6ccd041 refactor: build document links with get_form_link in form scripts 2026-08-18 22:49:47 +05:30
diptanilsaha
cfb664804c refactor: build document links with get_form_link in report formatters 2026-08-18 22:49:45 +05:30
diptanilsaha
57c2887ab4 fix: escape attribute values in shared client side templates 2026-08-18 22:49:43 +05:30
diptanilsaha
09eae9886a fix: escape activity type in project dashboard template 2026-08-18 22:49:41 +05:30
diptanilsaha
79284d8430 fix: escape item and document values in manufacturing preview templates 2026-08-18 22:49:39 +05:30
diptanilsaha
ffb7a708e4 fix: escape item, warehouse and label values in form grid templates 2026-08-18 22:49:28 +05:30
diptanilsaha
0541635f48 fix: escape item image url and item name in item image print formats 2026-08-18 22:49:26 +05:30
diptanilsaha
dc7822b319 fix: escape item image url in compact item print description 2026-08-18 22:49:24 +05:30
diptanilsaha
303c4f9081 fix: escape help article route on support page 2026-08-18 22:49:23 +05:30
diptanilsaha
9a4cb48429 fix: escape partner logo url and partner name in partner pages 2026-08-18 22:49:22 +05:30
diptanilsaha
53394478d9 fix: escape pathname and document name in transaction row link 2026-08-18 22:49:10 +05:30
diptanilsaha
0b1dd6cccf fix: encode image url and escape alt text in shared media macros 2026-08-18 22:49:09 +05:30
diptanilsaha
a3032f2f66 fix: serialize document values with tojson in rfq portal script 2026-08-18 22:49:07 +05:30
diptanilsaha
c42d653da5 fix: render terms and conditions through sanitize_html on order page 2026-08-18 22:49:06 +05:30
diptanilsaha
bc0fd611d4 fix: escape forum topics and get started sections on help page 2026-08-18 22:49:05 +05:30
diptanilsaha
5c4fb99f68 fix: urlencode project name in project portal page and script 2026-08-18 22:49:03 +05:30
diptanilsaha
4c0f0299ea fix: escape assigned user full name in project portal row templates 2026-08-18 22:49:02 +05:30
Mihir Kandoi
d91fce90c7 fix: use user data fields hook (#58274) 2026-08-18 16:07:06 +00:00
MochaMind
f6ab73d5ac fix: sync translations from crowdin (#58225) 2026-08-18 10:15:01 +00:00
Mihir Kandoi
27b06fcb61 fix(accounts): match returns to source invoice items (#58250) 2026-08-18 08:14:48 +00:00
rohitwaghchaure
b68324ce78 fix: work order finish dialog with process loss qty from job card (#58256)
* fix(manufacturing): cap job card completed qty by previous operation and show process loss on finish dialog

* fix: revert job card finish dialog changes
2026-08-18 13:26:56 +05:30
Pandiyan P
1fa057b943 fix: skip covered rows when ordering from the mrp report (#58249)
* test: cover the rows that have nothing left to order in the mrp report

a row whose requirement is already met by stock or by an order placed earlier
fails the order it is selected for, takes the rows beside it down with it, and
what rounding leaves behind of it is ordered as if it were a real quantity. the
work order made from a row of the schedule also has to keep the work in progress
warehouse the company keeps for it.

* fix: skip covered rows when ordering from the mrp report

a row whose requirement is already met by stock or by orders that were placed
earlier nets down to a required qty of zero. making an order from it threw
"Qty To Manufacture cannot be 0", and since nothing caught it, none of the other
selected rows were created either. such rows are now left alone, and selecting
only covered rows says so instead of failing.

the quantity ordered stays the one that is still needed. taking the planned qty
instead would order everything that stock and the open orders already cover. it
is read at the precision an order stores it in, so what is left of a covered row
after all the subtracting does not become an order line of its own.
2026-08-18 11:22:18 +05:30
rohitwaghchaure
1f83906189 fix: don't set work order status to In Process only due to skip material transfer (#58244) 2026-08-17 18:29:24 +05:30
Mihir Kandoi
d40679cffe fix(accounts): allocate drop-ship cost by invoice quantity (#58226) 2026-08-17 18:04:02 +05:30
rohitwaghchaure
bf1ec51680 Pick list stock availability (#58243)
* feat: stock availability insight on pick list

* fix: show holding pick lists inline in stock availability dialog

* fix: dashboard layout for stock availability dialog

* fix: reword stock release hint in availability dialog

* fix: tree layout for stock held by section

* fix: escape values in blocking pick lists table
2026-08-17 17:58:15 +05:30
Ejaaz Khan
e9c6ec4d33 Merge pull request #58241 from iamejaaz/feat/pf-split-across-pages
feat: allow Terms to split across pages in standard print formats
2026-08-17 16:01:42 +05:30
Ejaaz Khan
bd2a709ed1 feat: allow Terms to split across pages in standard print formats 2026-08-17 15:35:43 +05:30
Mihir Kandoi
baa20e5e49 fix(manufacturing): preserve attribution through consumption (#58146)
* fix(manufacturing): preserve attribution through consumption

* fix(manufacturing): preserve consumed quantity matching

* fix(manufacturing): assign consumption once
2026-08-17 09:57:57 +00:00
Pandiyan P
4dc0b2ea52 fix(manufacturing): fall back to item group defaults for work order warehouses (#58231) 2026-08-17 08:06:01 +00:00
Diptanil Saha
2f82e0dd36 fix(bank_statement_import): add missing permission check on multiple whitelisted methods (#58221) 2026-08-16 17:29:37 +00:00
Diptanil Saha
9a71ab4d79 fix(bank_statement_import): add missing permission check on get_import_status (#58217) 2026-08-16 20:22:44 +05:30
Diptanil Saha
5a69bb9001 fix(crm)!: remove unused get_last_interaction endpoint (#58214) 2026-08-16 19:32:24 +05:30
MochaMind
6c7b6bd87d fix: sync translations from crowdin (#58203) 2026-08-16 18:03:42 +05:30
MochaMind
b082f60e48 chore: update POT file (#58206) 2026-08-16 18:03:12 +05:30
Pandiyan P
9ee41029c8 fix: drop removed Restaurant doctype from sales tax template dashboard (#58191) 2026-08-16 10:50:11 +00:00
Pandiyan P
4a5943e2fb fix: correct Item Group doctype name in item tax template dashboard (#58192) 2026-08-16 16:14:52 +05:30
Shllokkk
8b8223f48b Merge pull request #58198 from Shllokkk/supplier-quotation-comparison-status-filter
feat: add status filter to Supplier Quotation Comparison report
2026-08-16 15:51:51 +05:30
Diptanil Saha
1212a278c6 Merge pull request #58197 from diptanilsaha/fix/get_digest_msg
refactor(email_digest): convert `get_digest_msg` from module function to instance method
2026-08-15 21:05:44 +05:30
diptanilsaha
c6b172999c fix(email_digest): added permission check for get_msg_html 2026-08-15 20:53:38 +05:30
Shllokkk
7cc236d1a8 feat: add status filter to Supplier Quotation Comparison report 2026-08-15 20:51:30 +05:30
Diptanil Saha
d472e17c75 Revert "refactor(email_digest)!: convert get_digest_msg from module function to instance method" (#58196) 2026-08-15 19:59:33 +05:30
Diptanil Saha
4cd8fbf1c0 refactor(email_digest): convert get_digest_msg from module function to instance method (#58193) 2026-08-15 14:10:14 +00:00
Pandiyan P
cc60c80e68 fix: correct is_frozen description on customer and supplier (#58168) 2026-08-15 12:24:12 +00:00
rohitwaghchaure
70a8a2d0c5 feat: validate purchase receipt exchange rate parity on purchase invoice (#58177) 2026-08-15 14:20:55 +05:30
Antoine Maas
a5472b5080 feat: Belgian Charts of Accounts (commercial + non-profit, FR + NL) (#54679)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Diptanil Saha <diptanil@frappe.io>
2026-08-14 22:06:40 +05:30
MochaMind
4316cf2f65 fix: sync translations from crowdin (#58145) 2026-08-14 20:03:05 +05:30
Mihir Kandoi
ef24974645 fix(stock): restore subcontracting inward warehouse checks (#58183) 2026-08-14 14:26:25 +00:00
Sudharsanan Ashok
fb7c2caf29 fix(stock): honour pick serial / batch based on in the batch selector (#58176) 2026-08-14 19:25:35 +05:30
Pandiyan P
1519770cb0 perf: filter stock projected qty bins by company in sql (#58173) 2026-08-14 19:20:43 +05:30
Pandiyan P
92c372c6a1 fix: rename misspelled delink_refernce_from_voucher (#58169) 2026-08-14 19:19:17 +05:30
ervishnucs
513f19924d fix(accounts): supplier group filter not applied on accounts payable report 2026-08-14 18:02:25 +05:30
Khushi Rawat
0b01b9bcd3 Merge pull request #57838 from khushi8112/hide/redundant-primary-address-contact-fields
refactor(ui): hide the primary address and contact preview fields
2026-08-14 17:32:09 +05:30
Jatin3128
cbf8f61101 fix: rewriting the description of the overdue billing checkbox (#58172)
fix: rewritting the description of the overdue billing checkbox
2026-08-14 11:18:38 +00:00
Nishka Gosalia
525930c5eb Merge pull request #58167 from nishkagosalia/gh-57661
fix: validation for task end date check
2026-08-14 16:22:07 +05:30
nishkagosalia
7c6da80f98 fix: validation for task end date check 2026-08-14 16:05:52 +05:30
rohitwaghchaure
e5c24fb398 feat: cross-plan load and overlap validation in production plan scheduling (#58127)
* feat: cross-plan load and overlap validation in production plan scheduling

* fix: row-level job card exclusion and locking read in schedule overlap check

* fix: operation-level job card exclusion and workstation locking in capacity check

* fix: keep plan schedule load when job cards carry no booked time

* fix: qty-coverage based job card exclusion for plan schedule load
2026-08-14 10:24:48 +00:00
Jatin3128
917badb82b fix: renaming the overdue billing checkbox (#58165) 2026-08-14 10:16:47 +00:00
Pandiyan P
10109674a4 feat(selling): add shipping contact person to sales order, delivery note and sales invoice (#58159) 2026-08-14 15:04:31 +05:30
Mihir Kandoi
73957dc84b refactor(selling): reorder sales invoice mapper arguments (#58162) 2026-08-14 14:36:37 +05:30
Diptanil Saha
3558ce3b59 feat(accounts): opt-in 'Consider Accounting Dimension' filter on General Ledger Report (#58156) 2026-08-14 08:12:08 +00:00
Khushi Rawat
7e2edb5c27 Merge pull request #58092 from aerele/fix/disallow-reverse-of-reverse-journal-entry
fix(accounts): disallow reversing a reverse journal entry
2026-08-14 11:30:44 +05:30
Mihir Kandoi
8632119f11 fix(accounts): filter parties by transaction company (#58147) 2026-08-14 11:02:13 +05:30
rohitwaghchaure
9239d1c2a3 fix: ignore historical negative batch stock in outward validation (#58148) 2026-08-14 10:56:27 +05:30
Mihir Kandoi
eae6d10304 fix(manufacturing): preserve alternative material attribution (#58131) 2026-08-14 03:44:39 +00:00
Diptanil Saha
081d269f6d Merge pull request #58141 from diptanilsaha/fix/fcrm_custom_field
fix(crm_settings): create `crm_deal` fields on enabling frappe crm data synchronization
2026-08-13 23:09:17 +05:30
diptanilsaha
9613d72d81 fix: patch to delete the crm_deal custom fields 2026-08-13 22:56:25 +05:30
diptanilsaha
be2dea0ba2 fix(crm_settings): create custom fields for Frappe CRM on enabling synchronization 2026-08-13 22:56:05 +05:30
Nikhil Kothari
0bbaf4da3e chore(deps): update eslint in banking app (#58129) 2026-08-13 12:29:13 +00:00
Pandiyan P
fd728dacca fix(buying): allow purchase returns against a closed purchase order (#58126) 2026-08-13 17:55:41 +05:30
Sudharsanan Ashok
1e583725a1 feat: delivery note billing based on quantity (#56149)
* feat(stock): bill delivery note by qty when invoiced amount is short

* test(stock): add test for qty fallback in delivery note billing
2026-08-13 16:28:35 +05:30
Sudharsanan Ashok
a2976dd29e fix(stock): confirm before changing item qty from the batch selector (#58123)
the batch selector silently overwrote the item qty with the bundle total,
so editing a row qty in the dialog changed the delivered qty without any
warning. prompt for confirmation when the rows do not add up to the qty
to fetch, and only proceed if the user agrees.
2026-08-13 16:27:45 +05:30
Khushi Rawat
99cb98d96c Merge pull request #58120 from khushi8112/stale-exchange-rate-description
fix: describe stale exchange rate settings
2026-08-13 15:10:41 +05:30
Mihir Kandoi
1534e2fad6 fix(manufacturing): derive material transfers from actual coverage (#58110) 2026-08-13 15:06:03 +05:30
khushi8112
84cdd0daf0 fix: describe stale exchange rate settings 2026-08-13 14:51:31 +05:30
Jatin3128
4a8342496e fix: keep Currency and Price List section open for foreign currency (#58074)
The section is marked collapsible with no condition, so it always
rendered collapsed. When the transaction currency differs from the
company currency the exchange rate is relevant and was hidden behind
a click.

Adds collapsible_depends_on so the section starts expanded whenever
the transaction currency differs from the company currency, and stays
collapsed otherwise.
2026-08-13 12:48:43 +05:30
Khushi Rawat
7212e6d989 Merge pull request #58096 from khushi8112/refactor/item-prices-embedded-list
refactor: use EmbeddedList for item prices
2026-08-13 12:33:51 +05:30
Khushi Rawat
c973de27d4 Merge pull request #58078 from khushi8112/fix/ar-sales-person-user-permission
fix: apply Sales Person user permissions in Accounts Receivable
2026-08-13 11:45:28 +05:30
Khushi Rawat
1fd653b1d3 Merge pull request #57563 from khushi8112/refactor-depreciation-entry
refactor: split make_depreciation_entry into public and internal helpers
2026-08-13 11:38:53 +05:30
khushi8112
51cefeffef refactor: use EmbeddedList for item prices
Replaces the hand-rolled item_prices.html table with frappe.ui.EmbeddedList,
the same primitive the proforma list uses. Drops the custom markup and styles.

The 10-row cap and the "View All Prices" link stay: the query fetches 11 rows
to return 10 plus a has_more flag, and the link routes to the Item Price list
filtered by item.
2026-08-13 11:34:12 +05:30
Mohsin Akhtar
e72aabcdb8 Fix/item description in the item price list (#58084) 2026-08-13 09:41:30 +05:30
rohitwaghchaure
c6d08979d3 feat: capacity aware scheduling for production plan (#58094)
* feat: capacity aware scheduling for production plan

* fix: do not apply incomplete schedule proposals

* fix: lock plan re-scheduling once work orders exist

* test: concurrent jobs across multiple machines with job capacity

* chore: fix linter and semgrep issues

* fix: readable subject for production plan schedule entries

* fix: persist computed start for item rows without explicit dates

* fix: block manual creation of production plan schedule entries

* chore: replace em-dashes with hyphens in design doc

* fix: cleared item-wise dates no longer constrain the schedule

* chore: format test file
2026-08-12 12:40:03 +00:00
Mihir Kandoi
43de54b907 fix(work order): exclude corrective transfers from item-level transferred qty (#58091) 2026-08-12 11:11:12 +00:00
pandiyan
9dd37d5f32 fix(accounts): disallow reversing a reverse journal entry
check read permission on the source entry before the guards run, so the reversal relationship is not disclosed to a user who cannot read it.
2026-08-12 15:59:16 +05:30
pandiyan
80422d2108 test(accounts): cover reversal of a reverse journal entry
also assert that a user without read access on the entry gets a permission error instead of the reversal relationship.
2026-08-12 15:59:16 +05:30
Mihir Kandoi
e5a0b5f61e fix(manufacturing): refine corrective job cards (#58079) 2026-08-12 10:13:29 +00:00
Mihir Kandoi
68a30f1568 fix(work order): don't count corrective job card transfers as transferred qty (#58080) 2026-08-12 15:35:55 +05:30
Mihir Kandoi
994703c2f3 Merge pull request #58073 from mihir-kandoi/codex/mrp-detailed-chart-timescale
fix(manufacturing): show full date range in MRP chart
2026-08-12 14:54:15 +05:30
Khushi Rawat
ca1b03cd46 Merge pull request #57820 from aerele/fix-asset-capitalization-grouped-row-valuation
fix(assets): split fifo/lifo rate across grouped stock item rows
2026-08-12 14:34:12 +05:30
khushi8112
8b09ba429e fix: apply Sales Person user permissions in Accounts Receivable
The report only narrowed by sales person when the filter was set, so a user
restricted to a Sales Person saw every row once the filter was cleared.

Resolve the permitted Sales Persons from user permissions and apply them on
top of the filter. Each Sales Team parent type is matched against its own
applicable_for scope, so a permission scoped to one doctype cannot authorise
rows through the other. Descendants are already expanded by
get_user_permissions, so Hide Descendants is respected. Gated to Receivable,
since the class is shared with Accounts Payable.
2026-08-12 14:26:10 +05:30
Krishna Pramod Shirsath
18dff27f65 Merge pull request #57995 from krishna-254/fix/available-batch-report-company-filter
fix: filter available batch report by company
2026-08-12 13:19:16 +05:30
Mihir Kandoi
5ad085887d fix(manufacturing): keep MRP chart dates distinct 2026-08-12 12:28:13 +05:30
Krishna Pramod Shirsath
c34e6fba32 Merge branch 'develop' into fix/available-batch-report-company-filter 2026-08-12 12:23:04 +05:30
Krishna Shirsath
484beb9fba fix: filter available batch report by company 2026-08-12 12:18:25 +05:30
Mihir Kandoi
592924cc0d test(manufacturing): cover MRP chart date range 2026-08-12 11:39:53 +05:30
MochaMind
83e33b343c fix: sync translations from crowdin (#58070) 2026-08-11 23:28:18 +00:00
Diptanil Saha
c52552ecfa fix(coa_importer): added server-side validations for importing chart of accounts (#58065) 2026-08-12 03:32:19 +05:30
Vishnu Priya Baskaran
89e2c3c3e5 fix: allow non-admin roles to import chart of accounts (#57454) 2026-08-11 23:26:58 +05:30
Vishnu Priya Baskaran
39403a5ef3 refactor:fix item property updates in POS and transactions, and add styling (#57189)
Co-authored-by: Afsal Syed <afsalsyed12@gmail.com>
2026-08-11 22:50:28 +05:30
soulxone
3c17a604be fix(Material Requirements Planning Report): detailed-view chart timescale
The detailed-view chart collapsed every row into a single "today" column
and was additionally capped at 10 points, so the chart never matched the
report's date filters or the table data.

Two causes in get_detailed_view_chart_data:

1. `row.deliver_date` was a typo for `row.delivery_date` (the name used
   everywhere else in this report). On a frappe._dict the missing
   attribute resolves to None, so `getdate(None)` returned today and the
   past-date filter silently compared every row against today instead of
   its own delivery date.

2. A hard `if i == 10: break` truncated the chart to 10 date buckets.

Use the correct field name and drop the cap. The null check now runs
before the date comparison, since `getdate(None)` returning today meant
the original ordering could never filter a null delivery_date out.

Fixes #52632
2026-08-11 11:55:49 -05:00
Vishnu Priya Baskaran
8802000ba2 fix(consolidated cash flow): correct totals and labels in section foo… (#57336) 2026-08-11 21:58:53 +05:30
Raffael Meyer
e591c7e8b6 fix: mirror rounding adjustment on distributed_discount_amount (#58047) 2026-08-11 18:26:26 +02:00
Mihir Kandoi
a7e5e1209b Merge pull request #58051 from mihir-kandoi/codex/fix-sales-order-item-reset
fix(selling): reset stale item details on item change
2026-08-11 21:05:04 +05:30
Mihir Kandoi
e8c890a844 fix(selling): preserve explicit UOM during item selection 2026-08-11 20:54:04 +05:30
Mihir Kandoi
e6966627b8 Merge pull request #58050 from mihir-kandoi/codex/fix-bom-creator-item-selection
fix(manufacturing): preserve BOM Creator item details
2026-08-11 20:53:31 +05:30
Mihir Kandoi
009961edc7 fix(selling): reset stale item details on item change 2026-08-11 20:41:47 +05:30
Mihir Kandoi
439eb250f5 fix(manufacturing): preserve BOM Creator item details 2026-08-11 20:40:30 +05:30
Mihir Kandoi
7e4e9860ef Merge pull request #58045 from mihir-kandoi/codex/repair-underbilled-pr-status
fix(stock): repair existing underbilled purchase receipts
2026-08-11 19:52:08 +05:30
Mihir Kandoi
620465220b test: cover repair of underbilled receipts from mixed billing 2026-08-11 19:21:38 +05:30
Mihir Kandoi
e99ae3796c fix(stock): repair existing underbilled purchase receipts
The qty-sync fix corrects allocation going forward, but receipts billed
before it can keep understated billed_amt, per_billed, and status. The
earlier repair patch only selects over-billed PO items, so it never picks
these up.

Recompute every candidate PO item (multiple submitted receipts, PO-level
invoicing, no invoice-created receipts). update_billed_amount_based_on_po
only writes rows whose recomputed value differs, so already-correct items
are untouched and the patch stays idempotent. This also converges receipts
left with direct-only billed_amt by last-event-wins overwrites.
2026-08-11 19:21:38 +05:30
Mihir Kandoi
4108be4637 Merge pull request #58036 from mihir-kandoi/codex/fix-disabled-warehouse-account-resolution
fix(stock): validate warehouse accounts when used
2026-08-11 18:54:39 +05:30
Mihir Kandoi
ce847b6c29 Merge pull request #58044 from mihir-kandoi/fix-po-billing-qty-sync-develop
fix: keep PO billed qty in sync when allocating amount to receipts
2026-08-11 18:53:46 +05:30
Mihir Kandoi
031e7c0eb7 test: cover mixed direct and PO-invoice billing across receipts 2026-08-11 18:40:35 +05:30
Mihir Kandoi
7803998fce fix: keep PO billed qty in sync when allocating amount to receipts
The amount-capped allocation branch reduced the remaining PO-invoiced
amount but left the invoiced qty untouched. A later receipt entering the
qty-proportional branch then divided by the stale qty and was under-billed:
PO 10 x 500, PO-level PI for 5 (2500), PR1 qty 3 with 500 billed directly
consumes 1000 (pool 2500 -> 1500, qty stuck at 5), PR2 qty 3 got
1500 * 3/5 = 900 instead of its full 1500. Scale the remaining qty by the
consumed fraction so both stay proportional.

Follow-up to #58021.
2026-08-11 18:39:52 +05:30
Mihir Kandoi
abb23fffdc Merge pull request #58021 from harisansari008/fix-po-invoice-billing-distribution-develop
fix: distribute PO-invoice billed amount across receipts without duplication
2026-08-11 18:36:09 +05:30
Mihir Kandoi
b54a4f6285 test(stock): cover named validation error and same-transaction parent inheritance 2026-08-11 18:26:10 +05:30
Mihir Kandoi
624e97f6c1 chore(stock): drop redundant supplier warehouse comment 2026-08-11 18:26:09 +05:30
Mihir Kandoi
d2b5c6ad40 fix(stock): validate new warehouse inventory account after naming
Move the insert-time check from before_insert to validate. before_insert
runs before set_new_name, so the validation message rendered the
warehouse name as None. validate runs after naming and only applies to
new documents via is_new().

Resolve inheritance through the parent's lft/rgt bounds instead of the
request-cached warehouse account map. The cached map can be stale within
a request (a parent created moments earlier is missing from it), which
made get_warehouse_account trigger a full nested-set rebuild_tree and
could falsely reject a child whose parent carries a valid account.
rebuild_tree enables auto_commit_on_many_writes, which must not run
inside a document insert.
2026-08-11 18:26:08 +05:30
Mihir Kandoi
0171b07023 Merge pull request #58032 from aerele/perf/batch-bin-lookups
perf: batch per-row bin lookups in sales invoice and delivery note
2026-08-11 18:20:50 +05:30
Mihir Kandoi
13883a00b0 fix(stock): validate warehouse accounts when used 2026-08-11 18:16:47 +05:30
Mihir Kandoi
d34519f536 test: cover repair patch exclusion for invoice-created receipts 2026-08-11 18:16:38 +05:30
Mihir Kandoi
ace4230f97 fix: skip PO items with invoice-created receipts in billing repair patch
A Purchase Receipt row created from a Purchase Invoice carries both
purchase_order_item and purchase_invoice_item, and its billed_amt is pinned
to the row amount by update_billing_status. Redistributing the PO-invoiced
pool over such rows zeroes the invoice-created receipt and flips it from
Completed to To Bill, so the repair leaves those PO Items untouched.
2026-08-11 18:16:38 +05:30
Mihir Kandoi
d8d0ea01c4 Merge pull request #58041 from mihir-kandoi/fix-auto-reserve-packed-items
fix: set auto reserve stock flag before packing list generation
2026-08-11 18:07:39 +05:30
Mihir Kandoi
b879c491b0 fix: set auto reserve stock flag before packing list generation
enable_auto_reserve_stock ran at the end of validate, after
make_packing_list. On a new Sales Order saved with auto_reserve_stock
enabled, packed item rows were built while the parent reserve_stock
flag was still unset, so they never inherited it. Since the stamping in
packed_item.py is gated on doc.is_new(), later saves could not repair
the rows either; only the client-side toggle could. Move the
auto-enable before packing list generation so packed rows are stamped
on first save.
2026-08-11 17:53:47 +05:30
pandiyan
6bf00d3c8b perf: batch per-row bin lookups in sales invoice and delivery note
sales invoice's update_current_stock ran one bin query per item row and one
per packed row. delivery note already batched the same work by warehouse, so
lift that into get_bin_qty_map in stock/utils.py and have both call it.

also batch the per-batch expiry_date lookup in get_batches_by_oldest, and drop
three now-unused per-row setters: delivery note's set_actual_qty (already dead
before this change), sales invoice item's set_actual_qty and packed item's
set_actual_and_projected_qty.
2026-08-11 17:52:27 +05:30
Mihir Kandoi
27da94610c Merge pull request #58037 from aerele/feat/multi-select-item-warehouse-filters
feat(stock): multi select item and warehouse filters in warehouse wise item balance
2026-08-11 17:04:41 +05:30
Mihir Kandoi
db78dd1ef3 Merge pull request #58033 from mihir-kandoi/gate-selling-toggle-setters
perf: rewrite selling settings toggle setters only on change
2026-08-11 16:42:36 +05:30
Sudharsanan11
eb4bb2cbce test(stock): cover multi select item and warehouse filters in warehouse wise item balance
three cases: multiple warehouses get a column each plus the total qty
column, a selected group warehouse still expands to its children, and
multiple items report side by side while unselected items stay out.
2026-08-11 16:34:12 +05:30
Sudharsanan11
3c92a9e853 feat(stock): multi select item and warehouse filters in warehouse wise item balance
the item and warehouse filters took one value at a time, so comparing a
few warehouses meant re-running the report for each one.

both are multiselectlist now, matching the stock balance report. the
warehouse column list unions the subtree of every selected warehouse,
and get_items passes a list through instead of wrapping it. plain string
values still work, so saved filters and existing callers are unaffected.
2026-08-11 16:34:12 +05:30
Mihir Kandoi
6c5aca0b37 Merge pull request #57983 from Jatin3128/fix/disabled-party-validation-opportunity-rfq
fix: block disabled/frozen party on Opportunity and Request for Quotation
2026-08-11 16:31:52 +05:30
Mihir Kandoi
f3a8f02c5f Merge pull request #58031 from mihir-kandoi/gate-naming-property-setters
perf: rewrite customer and supplier naming setters only on change
2026-08-11 16:27:39 +05:30
Mihir Kandoi
27f0ffdde5 Merge pull request #58018 from mihir-kandoi/codex/reduce-test-setup-overhead
perf(tests): reduce repeated setup work
2026-08-11 16:27:15 +05:30
Mihir Kandoi
c9f74e21a0 test: cover selling settings toggle setter gating 2026-08-11 16:22:21 +05:30
Mihir Kandoi
136e00d513 perf: rewrite selling settings toggle setters only on change
on_update reran toggle_hide_tax_id, toggle_editable_rate_for_bundle_items
and toggle_discount_accounting_fields on every save, rewriting 11
property setters and clearing the meta cache of five doctypes.

Gate each toggle on has_value_changed. Fresh installs save the settings
with pure defaults (set_single_defaults), so the gated-off state must
match the JSON schema: align sales_invoice.json and
sales_invoice_item.json with the values every saved site already has —
tax_id printed when hide_tax_id is off, discount accounts hidden while
discount accounting is disabled. Packed Item rate already matches.
2026-08-11 16:21:21 +05:30
Mihir Kandoi
8b7e04eae1 fix(stock): repair duplicated purchase receipt billing 2026-08-11 16:16:53 +05:30
harisansari008
5e33a3c0bf fix: distribute PO-invoice billed amount across receipts without duplication
When a Purchase Invoice is raised directly from a Purchase Order (po_detail
set, pr_detail null), update_billed_amount_based_on_po distributes the billed
amount across the PO's Purchase Receipts in FIFO order.

The proportional branch, taken when the invoiced qty exceeds a single
receipt's qty, computed each receipt's share but never deducted the consumed
amount/qty from the running po_billed_amt_details total. As a result every
subsequent receipt was billed against the same amount again, so the receipts
together showed more billed amount than was actually invoiced. A receipt with
no invoice truly against it could reach 100% billed and become Completed,
dropping out of pending-invoice reports.

Deduct the consumed billed_amt and billed_qty in the proportional branch,
mirroring the existing else branch, so each receipt only consumes what is
left. Add a regression test covering a PO invoice spanning two receipts.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-11 16:16:33 +05:30
Diptanil Saha
2f1548c0f8 chore: disable mergifyio queue comment (#58030) 2026-08-11 16:11:31 +05:30
Mihir Kandoi
909e7b1457 test: cover customer and supplier naming setter gating 2026-08-11 16:10:15 +05:30
Mihir Kandoi
94320a9928 perf: rewrite customer and supplier naming setters only on change
Every Selling Settings save reran set_by_naming_series for Customer and
every Buying Settings save reran it for Supplier, rewriting the
naming_series property setters with their cache clears and running the
naming_series backfill UPDATE on the master table.

Gate both on has_value_changed, following Stock Settings. Naming
behaviour is unaffected: Customer.autoname and Supplier.autoname read
the master-name default, which is still set on every save.
2026-08-11 16:09:08 +05:30
Mihir Kandoi
d6e2d7105f perf(tests): run sales partner summary reports on shared fixtures
Both sales partner summary suites created identical submitted, draft,
cancelled, and returned transactions per doctype. Run both reports
against one fixture set and receive stock only for Delivery Note and
POS Invoice, the doctypes that consume it.
2026-08-11 16:03:51 +05:30
Mihir Kandoi
7aa6a07e74 test(stock): cover item metadata rewrite gating 2026-08-11 16:03:50 +05:30
Mihir Kandoi
a8e2351169 perf(stock): skip item metadata rewrite when settings unchanged
Every Stock Settings save rewrote the Item naming property setters and
the barcode visibility property setters. make_property_setter without a
doctype fans out to every doctype that has the fieldname and clears each
doctype's cache, and set_by_naming_series also backfills tabItem.

Gate both on has_value_changed. Item naming behaviour is unaffected: it
reads the item_naming_by default, which is still set on every save.
2026-08-11 16:03:49 +05:30
Jatin3128
58491723e7 feat(accounts): add Bank Charges account for Payment Entry deductions (#57840)
* feat(accounts): add Bank Charges account for Payment Entry deductions

Add an optional Bank Charges Account field on Company. When a Payment
Entry has a difference between the paid and received amount (e.g. a
same-currency Internal Transfer where the bank deducted a fee), that
amount now books to the Bank Charges account in the deductions table
instead of always going to the Exchange Gain/Loss account. Left blank,
behavior is unchanged.

Mirrors the resolution on both the server (set_exchange_gain_loss) and
client (set_exchange_gain_loss_deduction) so the deduction row is
pre-filled consistently before and after save. A user's manual account
edit on an existing deduction row is preserved across recalculation,
same as before this change.

* fix(accounts): only route Payment Entry difference to Bank Charges for same-currency transfers

Cross-currency Payment Entries were also matching the unconditional
bank_charges_account precedence, misrouting a genuine exchange
gain/loss into the Bank Charges account. Only prefer Bank Charges
Account when paid_from and paid_to share a currency; cross-currency
differences continue to book to Exchange Gain/Loss Account.

* test(payment_entry): assert against actual exchange gain/loss account, not a hardcoded name

CI failed: _Test Company's exchange_gain_loss_account is auto-provisioned
as "Exchange Gain/Loss - _TC" by the standard chart of accounts, not the
"_Test Exchange Gain/Loss - _TC" account used only by a sibling test.

* fix(accounts): auto-set Bank Charges Account from chart of accounts default

The standard chart of accounts already ships a "Bank Charges" ledger
account, but set_default_accounts() never picked it up into the
Company's bank_charges_account field, unlike its write_off_account and
exchange_gain_loss_account siblings. New and existing companies now
get it auto-populated the same way.

---------

Co-authored-by: test <test@test.com>
2026-08-11 15:47:51 +05:30
Smit Vora
4c5d54096f Merge pull request #57965 from ljain112/set-missing-values
fix: run set_missing_values before creating Purchase Order from MRP report
2026-08-11 15:46:28 +05:30
Sudharsanan Ashok
b5a3815a64 fix(selling): read overdue amount from payment ledger, not gl tags (#57786) 2026-08-11 15:37:17 +05:30
Jatin3128
6b35c51ff1 refactor: move RFQ supplier disabled filter to link_filters
Static filters with no doc-dependent values belong on the field
definition, not in JS. Matches the existing pattern used for
Warehouse/Item link_filters elsewhere (e.g. job_card_item.json,
product_bundle_item.json).
2026-08-11 15:35:28 +05:30
Mihir Kandoi
e258921681 Merge pull request #58020 from mihir-kandoi/codex/fix-driver-supplier-address
fix(setup): fetch driver address by supplier link
2026-08-11 15:17:24 +05:30
Mihir Kandoi
3ffb888d26 fix(setup): fetch driver address by supplier link 2026-08-11 15:09:48 +05:30
Mihir Kandoi
575f34e7c6 Merge pull request #58016 from mihir-kandoi/fix-job-card-operation-row-id
fix: preserve original operation idx in manually created Job Cards
2026-08-11 14:19:25 +05:30
Mihir Kandoi
cb7201cc18 fix: preserve original operation idx in manually created Job Cards
The Create Job Card dialog on Work Order lists only pending operations,
so the row idx sent to make_job_card is the dialog's position, not the
Work Order Operation idx. create_job_card stamped that dialog idx into
operation_row_id, and get_required_items then matched raw materials of
whichever operation held that idx originally.

Resolve idx server-side from the Work Order Operation row that
get_operation_details already looks up by name.

Fixes https://github.com/frappe/erpnext/issues/57985
2026-08-11 14:05:21 +05:30
Mihir Kandoi
3c000929e2 Merge pull request #58005 from mihir-kandoi/restore-manufactured-qty-check
fix: reinstate mandatory manufactured qty check for manufacture entries
2026-08-11 14:00:05 +05:30
Mihir Kandoi
1543ee9350 test: manufacture entry blocked without manufactured qty 2026-08-11 13:47:26 +05:30
Mihir Kandoi
b6ca708d9f fix: reinstate mandatory manufactured qty check for manufacture entries 2026-08-11 13:46:40 +05:30
Mihir Kandoi
3379907564 Merge pull request #58004 from mihir-kandoi/restore-duplicate-entry-check
fix: reinstate duplicate entry check for manufacture entries
2026-08-11 13:45:07 +05:30
Mihir Kandoi
148d6aad5f Merge pull request #58009 from mihir-kandoi/require-transfer-before-job-card-start
fix: require material transfer before job card start and completion
2026-08-11 13:31:05 +05:30
Mihir Kandoi
e5344cc07e test: overproduction allowance permits a further manufacture entry 2026-08-11 13:27:02 +05:30
Mihir Kandoi
492ee05727 fix: honor overproduction allowance in duplicate entry check
Compare already-entered finished good qty against the work order qty plus
the configured overproduction percentage, mirroring the submit-time guard
in work_order/services/status.py, so a save is never rejected that the
submission contract would accept.
2026-08-11 13:27:02 +05:30
Mihir Kandoi
1665873fc9 test: duplicate manufacture entry against a work order
A second Manufacture stock entry saved while existing entries already
cover the full work order qty must raise DuplicateEntryForWorkOrderError.
2026-08-11 13:27:02 +05:30
Mihir Kandoi
22fa520500 fix: reinstate duplicate entry check for manufacture entries
The stock_entry.py split (#54466) dropped check_duplicate_entry_for_work_order
and DuplicateEntryForWorkOrderError with no replacement. The Work Order still
throws StockOverProductionError when submitted entries exceed the planned qty,
but nothing blocks saving another Manufacture entry, draft or submitted, once
existing entries already cover the full work order qty.

Restore the validation in the manufacture purpose handler, gated to work
orders without track_semi_finished_goods, matching the pre-split behaviour.
2026-08-11 13:27:02 +05:30
Mihir Kandoi
fee2672bf9 Merge pull request #58000 from mihir-kandoi/restore-operations-completed-check
fix: reinstate operations completed check for manufacture entries
2026-08-11 13:25:04 +05:30
Mihir Kandoi
704adeb96e Merge pull request #58003 from mihir-kandoi/codex/fix-sales-invoice-return-redelivery
fix(selling): bill re-delivered sales order quantities
2026-08-11 13:20:01 +05:30
Mihir Kandoi
e9533495fc fix: keep job card actions visible for corrective job cards
Corrective job cards regenerate required items but are exempt from the
transfer gate on the server; mirror that exemption in materials_ready.
2026-08-11 13:18:55 +05:30
Mihir Kandoi
c95705dc64 test: job card start and completion blocked until material transfer 2026-08-11 13:14:38 +05:30
Mihir Kandoi
808b2e2984 fix: require material transfer before job card start and completion
When the work order transfers material against Job Card, the Start Job
and Complete Job actions (and the whitelisted start_timer and
complete_job_card methods behind them) accepted work before any
Material Transfer for Manufacture existed; the transfer gate only fired
on job card submission.

Run validate_transfer_qty on both actions, and drop the finished_good
escape in materials_ready so the dashboard hides the buttons while
transfer is pending. Job cards that skip material transfer, corrective
job cards, and work orders transferring against Work Order are exempt,
as on submit.
2026-08-11 13:08:33 +05:30
Mihir Kandoi
af234a2d16 Merge pull request #58006 from mihir-kandoi/subcontracting-fg-items-list
fix: pass finished goods as list to subcontracting BOM lookup
2026-08-11 12:57:55 +05:30
Mihir Kandoi
3704d1513b Merge pull request #57963 from frappe/codex/fix-bom-explorer-quantities
fix(manufacturing): correct nested BOM Explorer quantities
2026-08-11 12:56:08 +05:30
Mihir Kandoi
40fc6c8b8a fix: pass finished goods as list to subcontracting BOM lookup
set_service_items_for_finished_goods built a set and passed it to
get_subcontracting_boms_for_finished_goods, whose filter builder only
handles str and list. Whitelist type validation lax-coerces the set to a
list during HTTP requests and tests, hiding the mismatch, but from
console, bench execute or background contexts the set reaches
frappe.get_all verbatim and is inlined into invalid SQL on both MariaDB
and PostgreSQL.

Ref #57996
2026-08-11 12:41:47 +05:30
Mihir Kandoi
9f108e4b75 fix(selling): clamp pending qty to qty field precision 2026-08-11 12:38:26 +05:30
Mihir Kandoi
dd23cf40e1 perf(selling): batch billed quantity lookup 2026-08-11 12:27:22 +05:30
Mihir Kandoi
26a05044c0 fix: link an active non-corrective job card in the operations error
Cancelled, amended, and corrective job cards do not contribute to the
operation's completed qty, so the error should not direct users there.
2026-08-11 12:16:46 +05:30
Mihir Kandoi
114ba42850 fix(selling): bill re-delivered sales order quantities 2026-08-11 12:16:00 +05:30
Mihir Kandoi
fe8bedef93 Merge pull request #57997 from kaulith/fix/bom-item-query-barcode-search
fix: keep item code searchable when a barcode matches the same text
2026-08-11 12:12:07 +05:30
Mihir Kandoi
2d022ffb66 test: manufacture entry blocked until operations are completed 2026-08-11 12:11:19 +05:30
Mihir Kandoi
401eb30963 fix: reinstate operations completed check for manufacture entries
The stock_entry.py split (#54466) dropped check_if_operations_completed
and OperationsNotCompleteError with no replacement, so a Manufacture or
Material Consumption for Manufacture entry could be submitted against a
work order whose operations (job cards) were never completed.

Restore the validation in the manufacture purpose handler, gated to
work orders without track_semi_finished_goods, which has its own
per-operation enforcement.
2026-08-11 12:09:33 +05:30
Mihir Kandoi
70f236ae2e Merge pull request #57972 from aerele/fix/workstation-time-in-mins
refactor: drop redundant time_in_mins assignment in workstation complete_job
2026-08-11 12:08:43 +05:30
Kaushal Shriwas
23024d1ea9 test(manufacturing): cover BOM item search when item code collides with a barcode 2026-08-11 11:58:36 +05:30
Kaushal Shriwas
bf5d506637 fix(manufacturing): keep item code searchable when a barcode matches the same text 2026-08-11 11:58:33 +05:30
Mihir Kandoi
3cffeb68e3 refactor: drop redundant time_in_mins assignment in complete_job 2026-08-11 11:56:13 +05:30
Nabin Hait
e4f9c664a8 refactor: stock write-path cleanups (SLE/Bin chokepoint groundwork) (#57980)
* fix: skip zero-qty rows in make_sl_entries instead of reusing the previous entry

A row with zero actual_qty that is not a Stock Reconciliation never gets an
SLE, but the loop body still ran with the previous iteration's sle_doc:
repost_current_voucher and the bin update executed twice for the previous
row, or the whole call crashed with UnboundLocalError when the zero-qty row
came first. Skip such rows entirely.

* refactor: remove dead update_entries_after.update_bin_data

No callers anywhere in the codebase; it duplicates update_bin() with subtly
different semantics (no update_modified) and would only invite accidental
resurrection as a second Bin write path.

* refactor: rename bin.update_qty to update_qty_from_sle

Two unrelated functions circulated under the name update_bin_qty:
bin.update_qty (recomputes quantities from the ledger, aliased on import in
stock_ledger.py) and stock_balance.update_bin_qty (writes caller-supplied
absolute values, imported by six modules). Give the SLE-driven one a name
that states its semantics and drop the alias.
2026-08-11 11:35:24 +05:30
Jatin3128
8c0a945417 fix: scope Opportunity party validation to Customer only
validate_party_frozen_disabled only enforces Customer/Supplier/Employee,
so passing opportunity_from straight through silently no-op'd for Lead
and Prospect. Made the Customer-only scope explicit instead of relying
on that implicit fallthrough.

Lead.disabled is not enforced anywhere else in the codebase (lead_query,
the picker used for this same field, only filters status/docstatus), so
deliberately not extending validation to Lead-sourced Opportunities.
2026-08-11 11:02:29 +05:30
Diptanil Saha
b55c6d16c9 refactor(queries): using frappe.get_query in get_filtered_child_rows (#57991) 2026-08-10 19:33:29 +00:00
Diptanil Saha
02118e7ba0 fix: preserve custom title on new JV (#57987)
Co-authored-by: rehanrehman389 <rehanrehman389@gmail.com>
2026-08-10 21:27:44 +05:30
Jatin3128
4bf65ffc1d fix: block disabled/frozen suppliers on Request for Quotation
Request for Quotation overrides validate() entirely and never calls
super().validate(), so it never goes through AccountsController's
party validation. Suppliers also sit in a child table, so the shared
PartyValidator wouldn't have caught it anyway (it only checks a single
top-level party field). A disabled or frozen Supplier could be added
to an RFQ and the RFQ submitted without any warning.

Also filters the suppliers grid's supplier Link field to disabled=0,
matching the same client-side fix applied to Opportunity's party_name.
2026-08-10 18:02:34 +05:30
Jatin3128
90937ce6d9 fix: block disabled/frozen customers on Opportunity
Opportunity inherits TransactionBase instead of AccountsController, so
it never ran validate_party_frozen_disabled like Quotation, Sales Order
and Sales Invoice do. A disabled Customer could be saved as an
Opportunity's party and only get caught later at Quotation stage.

Also fixes the party_name Link query on the client: it referenced
erpnext.queries.customer, which was never defined, so disabled
customers showed up in the picker.
2026-08-10 18:02:16 +05:30
pandiyan
422a9161dd fix: convert hours to minutes in workstation complete_job
`time_diff_in_hours` returns hours, so `time_in_mins` needs `* 60`, not
`/ 60`. Matches `Job Card.validate_time_log_row`.

No behaviour change: the `doc.save()` on the next line runs Job Card's
`validate`, which recomputes `time_in_mins` correctly before the row is
written. This only stops the expression from reading as a bug.
2026-08-10 16:02:39 +05:30
Nikhil Kothari
5b2952aa23 chore: update deps in banking app (#57971) 2026-08-10 09:45:11 +00:00
Diptanil Saha
ef1d83c298 fix: field validation and perm checks on get_stock_reservation_entries_for_voucher (#57968) 2026-08-10 09:18:53 +00:00
ljain112
94d363851f fix: run set_missing_values before creating Purchase Order from MRP report 2026-08-10 14:11:41 +05:30
Mihir Kandoi
bf9744e145 fix(manufacturing): correct nested BOM quantities 2026-08-10 13:25:38 +05:30
Shllokkk
a25decfa50 fix: skip incoming rate calc when serial no qty is zero (#57427) 2026-08-10 11:54:49 +05:30
Pandiyan P
399ff463cc fix: re-check future sle before queuing repost on submit (#57664)
* test: cover both repost branches and the no-repost case

* fix: queue repost for entries backdated by a concurrent submit

---------

Co-authored-by: nareshkannasln <nareshkannashanmugam@gmail.com>
2026-08-10 11:53:49 +05:30
Khushi Rawat
d618ad24f1 Merge pull request #57822 from Shllokkk/asset-repair-downtime-recalc
fix: keep asset repair downtime in sync with entered dates
2026-08-10 11:50:22 +05:30
Diptanil Saha
e342bf765e fix: escape customer_details on lead creation from appointment (#57947) 2026-08-09 19:14:33 +00:00
Shllokkk
5486fbff03 Merge pull request #57927 from Shllokkk/sales-register-ledger-pos-paid
fix: reflect in-invoice receivable credits in Sales Register ledger view
2026-08-09 23:39:10 +05:30
Shllokkk
45a9294476 test: cover POS-paid invoice in Sales Register ledger view 2026-08-09 20:22:14 +05:30
Shllokkk
40c356d166 fix: reflect in-invoice receivable settlements in Sales Register ledger view 2026-08-09 20:22:12 +05:30
Mihir Kandoi
fe09f45ca7 Merge pull request #57895 from mihir-kandoi/fix-track-sfg-finished-good
fix: track semi finished goods production flow
2026-08-09 20:11:05 +05:30
Mihir Kandoi
0bb322f4d1 Merge pull request #57560 from nishkagosalia/gh-56632
fix: handling negative grand total
2026-08-09 16:45:13 +05:30
Mihir Kandoi
bf13284137 Merge pull request #57917 from mihir-kandoi/fix/italy-customer-name-fields
fix(regional): rename Italy's duplicate Customer name fields
2026-08-09 16:44:54 +05:30
Mihir Kandoi
4089f138f2 fix(controllers): correct negative rate settings link 2026-08-09 16:29:28 +05:30
Mihir Kandoi
110d0a38a6 fix(regional): rename Italy's duplicate Customer name fields
The Italy regional setup created Custom Fields first_name/last_name on
Customer. Since #46281 added standard quick-entry fields with the same
names, every Italian site carries duplicate field definitions:

- the setup wizard creates the duplicates silently because it skips
  validation, and any later Custom Field on Customer then raises
  UniqueFieldnameError (#50915)
- without the duplicates, creating an Italian company aborts inside
  install_country_fixtures; on MariaDB an interrupted fixture run
  persists Custom Field documents whose columns were never added, after
  which every Company insert fails with "Unknown column
  'fiscal_regime'" (#57215)

Re-land the rename from #50921 (reverted in #53409): the fields become
italy_customer_first_name/italy_customer_last_name and the e-invoice
template reads the new names. The migration patch runs only on sites
with Italy fixtures, re-runs them, explicitly syncs the schema of every
affected doctype (create_custom_fields skips unchanged fields, so its
own schema sync cannot restore missing columns), copies the old column
values wherever the new field is empty (also on sites that removed the
duplicate fields with the documented manual workaround), and deletes
the duplicate Custom Fields last so an interrupted run stays resumable.

The old insert_after anchor "salutation" no longer exists on Customer;
the renamed fields anchor after customer_type.
2026-08-09 16:29:17 +05:30
Mihir Kandoi
7d1d5a1309 Merge pull request #57918 from mihir-kandoi/fix/qi-reference-notify-update
fix: sync open reference forms after Quality Inspection submit
2026-08-09 16:04:39 +05:30
Mihir Kandoi
e8a6884d5e test: doc_update published for reference on Quality Inspection submit 2026-08-09 15:53:37 +05:30
Mihir Kandoi
647452c95b fix: sync open reference forms after Quality Inspection updates them
update_qc_reference() writes the QI link and bumps the reference
document's modified timestamp via raw db writes, which emit no realtime
event. A reference form (Purchase Receipt, Delivery Note, Stock Entry,
Job Card) still open in the browser keeps the old timestamp and fails
the timestamp conflict check on the next save/submit, forcing a manual
refresh after every QI submit/cancel/delete.

Calling notify_update() on the reference publishes the standard
doc_update event, so an open, unedited form silently reloads and syncs
its timestamp. get_lazy_doc skips child table loading since
notify_update only needs the parent row.
2026-08-09 15:45:07 +05:30
MochaMind
40d59f9a15 chore: update POT file (#57915) 2026-08-09 10:02:29 +00:00
Mihir Kandoi
4a31772f3d Merge pull request #57914 from aerele/fix/outward-bundle-sign
fix: negate stock value difference for outward transfer bundles
2026-08-09 14:37:06 +05:30
pandiyan
eff29565ae fix: negate stock value difference for outward transfer bundles
make_bundle_for_material_transfer squares stock_value_difference for
outward rows instead of negating it. multiply by -1, matching the qty
negation on the line above.

no behaviour change: set_incoming_rate and calculate_qty_and_amount both
recompute the field from qty * incoming_rate before the bundle is saved.
2026-08-09 13:20:48 +05:30
Mihir Kandoi
691c341edd Merge pull request #57911 from aerele/fix/sales-team-allocated-percentage-float
fix: tolerate floating-point drift in sales team allocated percentage
2026-08-09 12:28:56 +05:30
pandiyan
4afba94d1c test: sales team allocation totalling 100 in floating point
covers the case where the percentages are correct but the accumulated
sum is 100.00000000000001. two rows can never drift, since the second
reconstructs exactly as 100 - first, so the case needs three rows.
2026-08-09 11:25:24 +05:30
pandiyan
f7b2775829 fix: tolerate floating-point drift in sales team allocated percentage
the total of allocated_percentage was compared to 100 with exact float
equality, so a correct allocation could be rejected when the sum drifts
in binary floating point (10.0 + 58.02 + 31.98 -> 100.00000000000001).

round the total to the field precision before comparing, in both
SellingController.calculate_contribution and Customer.validate.
2026-08-09 11:25:12 +05:30
pandiyan
24de81f9fa test: work order process loss for semi finished goods
Cover both shapes: a single operation that books the loss itself, and a
chain where an earlier operation books it and the final operation loses
nothing, so the sum over the operations is the only correct source.
2026-08-09 09:45:49 +05:30
pandiyan
0eb61c9fac fix: roll up process loss to the work order for semi finished goods
update_work_order_qty() returns early when track_semi_finished_goods is
enabled, so set_process_loss_qty() never ran and Work Order.process_loss_qty
stayed at zero even though the job cards and the work order operations had
booked the loss. The work order also never reached the Completed status,
since that needs produced_qty + process_loss_qty to cover the ordered qty.

Calling set_process_loss_qty() from that early return is not enough: the
final operation has no semi finished good bom, so its manufacture entry is
not from a bom, remove_fg_completed_qty() zeroes fg_completed_qty and
update_work_order_qty() is never reached at all.

The manufacture entries cannot be summed either. Each one is reset to
MAX(Work Order Operation.process_loss_qty), so every entry of a multi
operation chain carries the running maximum instead of the loss of its own
operation. Aggregate the operations instead, and refresh the work order from
the job card, which is where the operation loss is written.
2026-08-09 09:45:49 +05:30
Mihir Kandoi
529a003ed1 Merge pull request #57832 from nishkagosalia/st-75115
fix: validate webform for project
2026-08-09 09:41:24 +05:30
Nishka Gosalia
53d3ba7a78 Merge pull request #57903 from SuhasBharadwajK/develop
fix: condition check with empty object for falsy case
2026-08-09 00:18:36 +05:30
Diptanil Saha
13d3101f12 fix: set restrict_globals=True in frappe.render_template (#57899) 2026-08-08 23:40:58 +05:30
nishkagosalia
126966d1db fix: validate webform for project 2026-08-08 23:20:14 +05:30
rohitwaghchaure
ca0a5cb67c feat: sync serial no status from stock ledger in Stock Qty vs Serial No Count report (#57863)
* feat: sync serial no status from stock ledger in Stock Qty vs Serial No Count report

* fix: pick last bundle move in SQL ordered by posting datetime and SLE creation

* fix: derive synced serial no status from stock ledger helper and validate sync args
2026-08-08 13:48:13 +00:00
Mihir Kandoi
1478e2a4cb test: transfer qty exemption only applies when material transfer is skipped 2026-08-08 17:37:42 +05:30
Mihir Kandoi
1deae664ce fix: keep the transfer qty check for legacy semi FG cards without an FG item
Existing submitted BOMs may carry operations without a finished good,
and no migration repairs them. Exempting every semi FG job card from
the transfer check let such a card submit after a partial transfer.
Exempt only cards that skip material transfer; legacy cards with
transfer enabled keep the strict transferred qty check.
2026-08-08 17:37:42 +05:30
Mihir Kandoi
8f0617c834 test: partial entries consume exactly the job card's material requirement 2026-08-08 17:37:42 +05:30
Mihir Kandoi
0428cddf5b fix: scale generated raw materials to the manufacture entry's production share
Every generated entry copied each Job Card Item's full required_qty in
the skip-transfer and BOM-backflush paths, so two entries for one job
card consumed the requirement twice. Scale the rows to the share of
production this entry accounts for and cap them at the requirement
still unconsumed, dropping rows that have nothing left. An entry whose
materials are exhausted then fails the existing at-least-one-raw-material
check instead of minting finished goods from nothing.
2026-08-08 17:37:42 +05:30
Mihir Kandoi
424a1dfa87 test: update-after-submit save keeps the manufacture entry intact 2026-08-08 17:37:42 +05:30
Mihir Kandoi
bed957fa67 fix: skip the pending production check on update-after-submit saves
Saving a submitted manufacture entry to change an allowed field re-ran
the pending production cap with a manufactured aggregate that already
includes the entry itself, so the save was rejected against the
post-entry remainder. Quantities are not editable after submit, so the
check has nothing to protect there.
2026-08-08 17:37:42 +05:30
Mihir Kandoi
db99657c47 test: target warehouse stays optional for semi FG work orders 2026-08-08 17:37:42 +05:30
Mihir Kandoi
9df527bf3f fix: keep Target Warehouse optional for work orders tracking semi finished goods
The WIP warehouse change also removed the Target Warehouse exemption
for semi FG orders, but those may validly carry the target on each
operation instead. Restore the exemption in the form and the submit
check; the WIP warehouse requirement stays.
2026-08-08 17:37:42 +05:30
Mihir Kandoi
eb7537c8df test: partial manufacture entry then finishing the job card 2026-08-08 17:37:42 +05:30
Mihir Kandoi
b8dd886cd4 fix: generate the next manufacture entry net of booked process loss
After a partial entry booked the job card's full process loss, the
next generated entry was sized qty-to-produce minus manufactured only.
It exceeded the pending production cap, so Make Stock Entry could not
finish the card. Subtract the consumed loss when sizing the entry.
2026-08-08 17:37:03 +05:30
Mihir Kandoi
7157e4357b test: stale manufacture draft cannot over-produce without an operation BOM 2026-08-08 17:37:03 +05:30
Mihir Kandoi
94cd27ce5d fix: cap a manufacture entry at the job card's pending production
Entries from operations without their own BOM carry no For Quantity,
so the finished-good reconciliation cannot run for them and a draft
created before other entries were submitted could still over-produce.

Validate every job-card manufacture entry against the job card
directly: finished goods plus process loss must fit in what the job
card still has left to produce after earlier submitted entries.
2026-08-08 17:30:55 +05:30
Mihir Kandoi
9ef386dfd2 test: operation BOM materials expand on single-pass submit, final FG must match the BOM item 2026-08-08 17:29:59 +05:30
Mihir Kandoi
1e2e87daac fix: derive operation FG items before material expansion, keep the final one the BOM's item
The finished_good derivation ran in validate_semi_finished_goods,
after set_materials_based_on_operation_bom had already expanded
operation BOM materials. A single-pass insert-and-submit (API or
import) with bom_no set but finished_good empty skipped the expansion,
persisting a submitted BOM without the referenced components. The
derivation also let a final operation inherit another item from its
bom_no, so downstream job cards would produce the wrong item.

Move the derivation into set_operation_finished_goods, called before
the expansion, prefer the BOM's own item for the final operation, and
reject a final operation whose FG item is not the BOM's item.
2026-08-08 17:29:59 +05:30
Mihir Kandoi
0aec62a8dd test: raw material dialog adds a row for its operation despite duplicates 2026-08-08 17:29:59 +05:30
Mihir Kandoi
24f1f3dea8 fix: add raw material to its operation even when another operation uses the item
get_item_details returns the whole Item document, so the dialog row's
name became the item code. get_item_data then matched that item code
against every Components row regardless of operation, so adding an item
already used by another operation silently updated that row's qty
instead of appending one for the target operation — which stayed empty
and failed 'please add raw materials or set a BOM' on submit.

Match the existing row by item code within the same operation: same
operation updates the qty, any other match appends a new row.
2026-08-08 17:29:59 +05:30
Mihir Kandoi
5e0f056284 test: manufacture entry keeps process loss scoped to its own operation 2026-08-08 17:29:59 +05:30
Mihir Kandoi
1b335973b7 fix: scope manufacture entry process loss to its own job card
set_process_loss_qty stamped MAX(process_loss_qty) across every
operation of the work order onto each manufacture entry. With semi
finished goods tracking, one operation's process loss leaked into the
entries of every other operation: validate_fg_completed_qty then
rejected the entry when it had a BOM, or the wrong loss was recorded
silently when it did not, double-counting the loss across operations.

When the entry belongs to a job card, use that job card's loss net of
what its earlier entries already booked. The MAX fallback stays for
work-order level entries without a job card.

Fixes frappe/erpnext#57892
2026-08-08 17:29:59 +05:30
Mihir Kandoi
335dbdaca4 test: previous operation shortfall from process loss gets the right message 2026-08-08 17:29:59 +05:30
Mihir Kandoi
1e22695eae fix: stop asking for a manufacturing entry when process loss explains the shortfall
When a previous operation manufactured less than the current job card
is completing, the error always said 'Submit the manufacturing entry
for the operation first' — even when the entry was already submitted
and the missing quantity was booked as process loss, which made the
advice a dead end.

Sum the process loss of the previous operation's job cards alongside
the manufactured quantity. When manufactured + process loss covers the
requested quantity, say the shortfall is process loss so the user
knows to reduce the completed quantity; keep the submit-first message
for genuinely pending manufacturing entries.
2026-08-08 17:29:59 +05:30
Mihir Kandoi
f61f6523b9 test: WIP warehouse required for work orders tracking semi finished goods 2026-08-08 17:29:59 +05:30
Mihir Kandoi
198eb60df7 fix: require WIP warehouse for work orders tracking semi finished goods
Work orders with track_semi_finished_goods were exempt from the
Work-in-Progress Warehouse requirement in three places: the field's
mandatory_depends_on, the fg_warehouse reqd toggle in the form script,
and validate_warehouse on submit.

The exemption was misleading. The flow still transfers materials to a
WIP warehouse when 'Skip Material Transfer' is unchecked: operations
default their WIP warehouse from the work order, and
set_default_warehouse silently restores the company default after the
user clears the field. Make the field genuinely required instead of
pretending it is optional.
2026-08-08 17:29:59 +05:30
Mihir Kandoi
4b3904c6d7 test: semi FG job card is exempt from the legacy transfer qty check 2026-08-08 17:29:59 +05:30
Mihir Kandoi
6c8f0b9b56 fix: don't demand raw material transfer for semi FG job cards on submit
validate_transfer_qty uses an empty finished_good to detect legacy job
cards, and unlike validate_semi_finished_goods it ignores
skip_material_transfer. A job card tracking semi finished goods whose
operation had no finished_good fell into the legacy branch and could
not be submitted even with 'Skip Material Transfer' checked on the
work order.

Return early for semi FG job cards; validate_semi_finished_goods
already enforces the transfer requirement for them and honours
skip_material_transfer.
2026-08-08 17:29:59 +05:30
Mihir Kandoi
aed7c70b1c test: BOM tracking semi finished goods rejects operations without FG item 2026-08-08 17:29:59 +05:30
Mihir Kandoi
3497a6a6bf fix: require FG / Semi FG Item on operations when tracking semi finished goods
A BOM with track_semi_finished_goods enabled could be saved with no
finished_good on any operation: validate_semi_finished_goods only
checked that one row had 'Is Final Finished Good' set, and a list
containing None passed the emptiness check.

Such a BOM breaks every downstream step. The work order copies the
empty finished_good into its operations, job cards inherit it, and
Make Stock Entry finally fails with 'Item None not found' because the
manufacture entry has no production item.

Derive the finished good where it is unambiguous: an operation that
references a BOM produces that BOM's item, and the final operation
produces the BOM's own item. Otherwise require it on the row, since
each operation's job card books its output through it.
2026-08-08 17:29:59 +05:30
Mihir Kandoi
11a902eb5f Merge pull request #57887 from mihir-kandoi/fix-repost-ma-return-sibling-rate
fix: repost read stale sibling SLE rate for moving average returns
2026-08-08 12:02:24 +05:30
Mihir Kandoi
b3f97cd389 fix: incorrect entry detection in Stock Ledger Invariant Check (#57886) 2026-08-08 05:31:21 +00:00
Mihir Kandoi
97d41867b5 fix: zero-rate repost fallback could still read sibling SLE
When the in-memory running rate is zero, the fallback went through
get_incoming_rate, whose previous-SLE lookup matches the same
posting_datetime and can land on a sibling line of the voucher being
replayed. Replace it with get_previous_sle_of_current_voucher excluding
the current voucher, keeping the get_valuation_rate chain when no
previous entry exists. get_incoming_rate is no longer used in this
module.
2026-08-08 11:00:47 +05:30
Mihir Kandoi
1a47c61b67 test: repost of multi-line moving average return is idempotent
Reposting a return that removes most of the stock across several lines
of the same item must keep every line at the running average and produce
identical results on a second repost. Before the fix the first repost
already drifted, seeding each line from a sibling row of the same
voucher.
2026-08-08 10:53:04 +05:30
Mihir Kandoi
b589a4d335 fix: repost read stale sibling SLE rate for moving average returns
During repost, a return line with recalculate_rate resolved its moving
average rate through get_incoming_rate -> get_previous_sle, which matches
posting_datetime <= and orders by creation desc. For a multi-line return
of the same item, every line shares one posting_datetime, so the query
landed on a sibling line of the same voucher whose stored valuation_rate
was still the previous repost run's output, not the rate before the
voucher.

Each repost run therefore re-seeded the voucher from its own prior
output. The error gain per run is (qty returned at the stale rate) /
(qty remaining after the return), so whenever a return removes most of
the stock the loop diverges instead of converging, alternating sign and
growing until stock_value overflows decimal(21,9) and the repost dies
with 'Out of range value for column stock_value'.

Use the in-memory running valuation rate that update_entries_after
already tracks for the warehouse at this point in the repost. It is the
authoritative pre-entry state, is immune to sibling rows, and makes the
repost idempotent. The database lookup is kept only as a fallback for a
zero in-memory rate, preserving the existing zero-rate fallback chain.
2026-08-08 10:51:13 +05:30
Pandiyan P
55fe269046 fix: allow selecting a warehouse for new items in the update items dialog (#57876) 2026-08-07 17:32:29 +00:00
Mihir Kandoi
5822cef1d9 feat(manufacturing): prompt for qty when creating material request from work order (#57855) 2026-08-07 17:25:51 +00:00
Mihir Kandoi
5e372df533 Merge pull request #57883 from mihir-kandoi/fix-pp-min-order-qty-round-up
fix: order smallest purchase UOM qty that meets min order qty
2026-08-07 22:49:55 +05:30
Mihir Kandoi
1ca06024cb test: marginal min order qty overage raises a toast 2026-08-07 22:36:02 +05:30
Mihir Kandoi
1aa6f8d1a7 feat: warn when ordered qty exceeds min order qty only by UOM rounding
A minimum order qty defined in stock UOM often has no exact
representation in the purchase UOM, so the smallest valid order slightly
exceeds the minimum. Surface that overage on the Purchase Order with a
toast on first save when an item's ordered stock qty is above its
minimum by less than one purchase-UOM step, so the buyer sees the
marginal increase before sending the order. Sub-precision dust stays
silent.
2026-08-07 22:36:02 +05:30
Mihir Kandoi
1b2090820a Merge pull request #57873 from mihir-kandoi/fix-conversion-factor-precision
fix: declare precision 9 on all conversion_factor fields
2026-08-07 22:20:57 +05:30
Mihir Kandoi
e4b66dc731 test: min order qty conversion takes the grid ceiling
Covers both rounding brackets, an exactly representable conversion, the
no-minimum path, and the ceiling through the plan items and materials
from other locations flows.
2026-08-07 22:20:38 +05:30
Mihir Kandoi
ee8eb18daf fix: order smallest purchase UOM qty that meets min order qty
A Production Plan with Consider Minimum Order Qty raises the requirement
to the item's minimum in stock UOM, then converts it to the purchase UOM
with round-to-nearest. Nearest rounding can land below the minimum it
just applied: min order qty 50000 with purchase UOM conversion factor
453.592292197 becomes 110.231, which is 49999.932 in stock UOM, and the
mapped Purchase Order is then rejected by validate_minimum_order_qty.

When the minimum binds and the nearest-rounded value dips below it,
quantize to the smallest representable purchase-UOM quantity whose stock
equivalent meets the minimum, using Decimal grid-ceiling arithmetic.
110.232 converts to 50000.386: demand stays as planned and the overage
is order-unit granularity, the standard MRP lot-sizing outcome. Ordinary
conversions keep the historical round-to-nearest behavior.
2026-08-07 22:20:30 +05:30
Mihir Kandoi
594ff24dae Merge pull request #57879 from mihir-kandoi/remove-dead-mr-po-mapper
refactor: remove unused make_purchase_order_based_on_supplier
2026-08-07 21:03:07 +05:30
Shllokkk
67f4b7a483 Merge pull request #57880 from Shllokkk/guard-clear-reconciliation-patch
fix: guard reconciliation table deletes when tables are missing
2026-08-07 20:03:19 +05:30
Shllokkk
8a2b2a2b68 fix: guard reconciliation table deletes when tables are missing 2026-08-07 19:33:45 +05:30
Mihir Kandoi
8b2946ca6b refactor: remove unused make_purchase_order_based_on_supplier
Its only caller, Purchase Order's get_items_from_open_material_requests,
was deleted in 91e9867fb1 (refactor: Cleanup buying module forms). The
old dotted path was already broken by the move to mapper.py, so no
external caller can be using it either.
2026-08-07 18:42:00 +05:30
Mihir Kandoi
ca5a673409 fix: round computed conversion factors to field precision
The inverse (1 / value) and intermediate-UOM branches of
get_uom_conv_factor returned raw float quotients like
0.4535922921968971, bypassing the precision the docfields now declare.
Same for the client-side back-calculation from an edited stock qty.
Round both to the UOM Conversion Factor value precision.
2026-08-07 17:47:50 +05:30
Mihir Kandoi
69a35a12cb fix: declare precision 9 on all conversion_factor fields
The Float control parses values with the field precision, falling back
to the global float precision when the docfield declares none
(frappe ControlFloat.parse / get_precision). On a site with float
precision 2, a fetched UOM factor of 0.453592292 was written back to
the model as 0.45, silently corrupting every derived quantity by 0.8
percent. A ratio must not inherit display precision meant for
quantities, so declare the same precision 9 the UOM Conversion Factor
master already uses on every transaction-level conversion_factor
field.
2026-08-07 17:31:32 +05:30
Mihir Kandoi
b3300c20a3 Merge pull request #57866 from krishna-254/fix/product-bundle-item-search
fix: optimize product bundle item search
2026-08-07 16:02:51 +05:30
Mihir Kandoi
4e9b069c20 Merge pull request #57861 from mihir-kandoi/fix-uom-integer-check-dust
fix: UOM whole number check truncated instead of rounding
2026-08-07 14:03:26 +05:30
Mihir Kandoi
e6a6458ebe test: UOM whole number check tolerates conversion dust 2026-08-07 13:49:00 +05:30
Mihir Kandoi
a464a6e4a1 fix: UOM whole number check truncated instead of rounding
cint truncates, so a stock_qty of 1999.9998 (dust from qty times
conversion factor) compared as abs(1999 - 2000.0) > epsilon and was
rejected as fractional even though it rounds to a whole number at
field precision, with the error confusingly printing the rounded
value: 'Quantity (2000.0) cannot be a fraction'. Round to field
precision first, then require the result to be a whole number.
Dust above an integer already passed; this fixes the asymmetry for
dust below.
2026-08-07 13:48:38 +05:30
Mihir Kandoi
a219f890df Merge pull request #57859 from mihir-kandoi/fix-po-min-order-qty-precision
fix: compare ordered qty to min order qty at stock_qty precision
2026-08-07 13:46:55 +05:30
Krishna Shirsath
b3867f1428 fix: optimize product bundle item search 2026-08-07 13:44:57 +05:30
Mihir Kandoi
c652f47931 test: min order qty check tolerates UOM conversion dust 2026-08-07 12:51:40 +05:30
Nishka Gosalia
d9e048ece7 Merge pull request #57845 from nishkagosalia/settings-mapping-cleanup
chore: restructure exported files of doctype settings
2026-08-07 12:46:43 +05:30
Mihir Kandoi
98b7407949 fix: compare ordered qty to min order qty at stock_qty precision
stock_qty is stored as raw qty * conversion_factor, so a UOM-converted
order for exactly the minimum (e.g. LB to Kg) produces values like
1999.999999131832 vs a min_order_qty of 2000 and blocks the Purchase
Order. Round both sides to the stock_qty field precision before
comparing, and show the rounded qty in the error message.
2026-08-07 12:44:28 +05:30
Mihir Kandoi
3f8b263014 Merge pull request #57854 from mihir-kandoi/fix/work-order-create-button-group
fix(UX): group work order actions under the Create menu
2026-08-07 04:22:33 +05:30
MochaMind
523d0e4312 fix: sync translations from crowdin (#57842) 2026-08-06 20:03:30 +02:00
Mihir Kandoi
780ab3ba3e fix(UX): group work order actions under the Create menu
Pick List, Material Request, Material Consumption and Additional
Material Transfer were spread across two standalone buttons and a
separate Make menu. Put them all under a single Create menu, and rename
Create Pick List to Pick List since the menu already says Create.
custom_make_buttons is updated to the new label so the connections
shortcut still finds the button.
2026-08-06 23:02:05 +05:30
Mihir Kandoi
e1815cb5a9 Merge pull request #57851 from mihir-kandoi/fix-production-plan-mr-qty-precision
fix: round Production Plan mr_items quantity to field precision
2026-08-06 21:11:10 +05:30
Mihir Kandoi
75145cc72c test: remaining purchase qty is rounded to field precision
Covers the _add_remaining_purchase_request path: partial stock in
another warehouse is allocated as a transfer and the residual purchase
qty goes through the second rounding site.
2026-08-06 20:59:04 +05:30
Mihir Kandoi
f5157bf3c4 test: mr_items quantity is rounded to field precision 2026-08-06 20:49:42 +05:30
Mihir Kandoi
ffc515f046 fix: round production plan mr_items quantity to field precision
The stock-UOM qty is rounded in _accumulate_so_items, but the purchase
UOM conversion divided it by the conversion factor without re-rounding,
storing values like 5738748.300863984 in mr_items.quantity. The raw
value flowed into Material Request qty and the raw materials CSV, and
make_material_request compares quantity to requested_qty with exact
float equality, so any rounding downstream left dust quantities.
2026-08-06 20:48:42 +05:30
Mihir Kandoi
44260b469f refactor: remove unreachable UOM conversion in production plan
The division by conversion_factor in _adjust_required_qty_for_uom sits
directly after frappe.throw inside the same block, so it can never run.
It has been dead since commit 2a8cd05b44 (#27278) re-indented it into
the throw branch; the actual purchase-UOM conversion happens in
_material_request_item_row via _mr_purchase_conversion_factor.
2026-08-06 20:48:19 +05:30
Jatin3128
96a6db7387 feat(accounts): split exchange gain and exchange loss accounts (#57839)
* feat(accounts): split exchange gain and exchange loss accounts

Add optional Exchange Gain Account and Exchange Loss Account fields on
Company. When set, realized FX gain/loss from settling an invoice in a
foreign currency (via Payment Entry, Payment Reconciliation, or a
Journal-Entry-based advance) books to the matching account instead of
the single Exchange Gain/Loss account. Either field left blank falls
back to the existing Exchange Gain/Loss account, so companies that
don't configure the new fields are unaffected.

New companies get "Exchange Gain" and "Exchange Loss" accounts
auto-created in their chart of accounts and auto-assigned to the new
fields, same as the existing Exchange Gain/Loss account provisioning.

The Payment Reconciliation tool's per-allocation "Difference Account"
override in its reconcile dialog continues to work as before; the
split accounts only change the computed default shown there.

* test(account_balance): account for new Exchange Gain account in income report

The new auto-provisioned Exchange Gain account under Indirect Income
now shows up in the Income root type report for _Test Company 2.

---------

Co-authored-by: test <test@test.com>
2026-08-06 17:36:43 +05:30
Suhas Bharadwaj
e0b9351d49 fix: condition check with empty object for falsy case 2026-08-06 16:38:46 +05:30
nishkagosalia
8096766d71 chore: restructure exported files of doctype settings 2026-08-06 16:28:18 +05:30
rohitwaghchaure
a49fcfe888 fix: purchase return of batchwise valuation batch valued at original receipt rate instead of batch avg rate (#57835)
* fix: use current batch avg rate for outward returns of batchwise valuation batches

* fix: honor zero batch average and avoid duplicate batch classification query
2026-08-06 15:21:44 +05:30
khushi8112
757eaf5fcf refactor(ui): hide the primary address and contact section
The Address & Contact cards now show these details and mark which record
is primary, so the section below only repeats it. Values are still stored
and Customer.search_fields keeps working, since search reads the column
rather than the form.

Depends on frappe/frappe#41600.
2026-08-06 15:16:00 +05:30
Diptanil Saha
12359c36bc Merge pull request #57825 from diptanilsaha/st/72599/arpbmd/pinv
refactor(accounts)!: rework Purchase Invoice hold actions and enforce them on Journal Entry
2026-08-06 13:11:51 +05:30
diptanilsaha
1a8d438b21 test(journal_entry): added test cases for blocked purchase invoices 2026-08-06 12:31:00 +05:30
diptanilsaha
cbafa16fbc fix(journal_entry): validate blocked purchase invoices 2026-08-06 11:56:58 +05:30
diptanilsaha
6c33ede45c refactor(purchase_invoice): expose invoice hold actions as document methods 2026-08-06 11:18:46 +05:30
rohitwaghchaure
742e0e16cf fix: XSS through unescaped work order name in shop floor view (#57826) 2026-08-06 08:53:46 +05:30
Shllokkk
8269f8a362 test: assert asset repair downtime recalculates on date change 2026-08-06 00:33:26 +05:30
Shllokkk
4406bb9068 fix: keep asset repair downtime in sync with entered dates 2026-08-06 00:33:24 +05:30
ervishnucs
2cbc5b89d6 test(assets): cover grouped stock item rows splitting FIFO rate 2026-08-05 19:01:10 +05:30
ervishnucs
a05ec49062 fix(assets): split FIFO/LIFO rate across grouped stock item rows 2026-08-05 19:00:51 +05:30
MochaMind
1ffcfeb11b fix: sync translations from crowdin (#57743) 2026-08-05 15:13:07 +02:00
Henil Maru
8e8ef1602e fix(sales-invoice): respect Customize Form hidden setting on Update Stock (#57818)
set_dynamic_labels() unconditionally forced update_stock's hidden
property based only on is_debit_note/has_subcontracted, overwriting
whatever Customize Form had set on every refresh. OR it with the
field's original (property-setter-driven) hidden value instead.
2026-08-05 18:00:26 +05:30
rohitwaghchaure
d71fc3b774 feat: validate stock value and stock closing entry before period closing (#57811)
* feat: validate stock value and stock closing entry before period closing

* fix: do not accept scoped stock closing entries as period closing prerequisite

* feat: seed batch valuation from stock closing balance and freeze closed-period stock
2026-08-05 15:45:16 +05:30
Mihir Kandoi
8aadffa73c Merge pull request #57810 from aerele/fix/blanket-order-mapped-naming-series
fix: do not copy Blanket Order naming series to the mapped order
2026-08-05 14:12:11 +05:30
pandiyan
7620553418 test: assert mapped order keeps its own naming series 2026-08-05 13:03:10 +05:30
pandiyan
fe7128f02f fix: do not copy blanket order naming series to the mapped order
get_mapped_doc copies every same-named field that is not no_copy, so the
Sales Order / Purchase Order / Quotation created from a Blanket Order
inherited MFG-BLR-.YYYY.- and was named MFG-BLR-2026-00003 instead of
SAL-ORD-2026-00001.

exclude naming_series from the mapping, same as job card does when it
maps to a Purchase Order.
2026-08-05 13:03:10 +05:30
Mihir Kandoi
1f42eb1a3c Merge pull request #57793 from aerele/fix/blanket-order-zero-qty-validation
fix: validate Blanket Order item quantity is greater than zero
2026-08-05 12:11:48 +05:30
rohitwaghchaure
d3a8c329dd fix: incorrect batch-wise valuation rate for entries with same posting datetime (#57803)
fix: incorrect batch-wise valuation rate for entries with same posting datetime (#57794)

* fix: incorrect batch-wise valuation rate for entries with same posting datetime

The tie-breaker in get_batch_no_ledgers compared the bundle's creation
against the SLE's creation. These are different timelines - a bundle can
be created (drafted) much before its SLE (created at submission). For
entries sharing a posting datetime (backdated / amended vouchers), this
mis-ordered the entries against the ledger's replay order (SLE creation),
causing double counting or omission of batch qty / value and runaway
outgoing rates that no repost could heal.

Now the tie is broken using the creation of the bundle's own SLE (same
timeline on both sides). When the valuation runs through the bundle
before its SLE exists, the entry is by definition last in its timestamp
group, so all same-timestamp entries already in the ledger precede it.



* test: batch-wise valuation ordering for same posting datetime entries

Covers both tie-breaking branches of get_batch_no_ledgers:
- submission (pre-insertion) branch: same-timestamp inward at a different
  rate plus a multi-row outward voucher (same item and warehouse), at
  submission and after a backdated repost
- existing-SLE branch: a bundle created after its sibling's SLE, the
  ordering must follow the SLE creation and not the bundle creation

Both tests fail with the previous parent.creation < sle.creation
tie-breaker and pass with the fix.



---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 11:06:30 +05:30
Diptanil Saha
4d511a1521 chore(CODEOWNERS): add @nikkothari22 for banking (#57801) 2026-08-04 19:53:54 +00:00
Diptanil Saha
fc8e2e8627 Merge pull request #57734 from aerele/fix/payment-reconciliation-supplier-gain-loss-sign
fix(payment reconciliation): correct supplier gain/loss posting
2026-08-04 23:55:38 +05:30
Sudharsanan Ashok
0dbe410414 fix(stock): handle multi-item opening balance in Stock Ledger report (#57591)
* fix(stock): handle multi-item opening balance in Stock

* test(stock): add unit test for multi-item Stock Ledger report

---------

Co-authored-by: Afsal Syed <afsalsyed12@gmail.com>
2026-08-04 22:14:16 +05:30
R-Jayaraman
d80b0f67cc test: add regression test for zero quantity Blanket Order 2026-08-04 19:06:25 +05:30
R-Jayaraman
e897c4d82d fix: validate Blanket Order item quantity is greater than zero 2026-08-04 19:05:51 +05:30
Shllokkk
b9dafafeee Merge pull request #57790 from Shllokkk/warehouse-account-override-value-comparison
test: child warehouse account override in stock vs account value comparison
2026-08-04 17:30:28 +05:30
Shllokkk
ef7a3cb4c8 test: child warehouse account override excluded in stock vs account value comparison 2026-08-04 17:03:25 +05:30
Mihir Kandoi
afdb951eb4 Merge pull request #57757 from aerele/fix/opportunity-qty-validation
fix(opportunity): add validation for positive item quantities
2026-08-04 16:52:55 +05:30
R-Jayaraman
69de8f2d62 chore: use flt() in qty check 2026-08-04 16:38:49 +05:30
Mihir Kandoi
8b710ddbf1 Merge pull request #57772 from aerele/fix/party-dashboard-doctype-permission
fix(accounts): skip party dashboard without invoice permission
2026-08-04 16:33:30 +05:30
Jatin3128
0f428ed854 fix(subscription): don't reactivate a cancelled subscription (#57774)
* fix(subscription): don't reactivate a cancelled subscription

set_subscription_status() unconditionally set status to Active once
there was no outstanding invoice, even if the subscription had been
intentionally cancelled. Paying off an invoice issued before
cancellation (directly, or via the Payment Entry -> refresh hook)
flipped a Cancelled subscription back to Active while cancelation_date
stayed set.

process()'s cancel_at_period_end check compared posting_date against
getdate(self.end_date), and getdate(None) returns today, so an empty
end_date was silently treated as "cancel now" on every scheduler run.
Combined with the reactivation bug, this let a cancelled subscription
toggle Cancelled -> Active on each run and generate another invoice at
the next period boundary.

Fixes #57761

* fix(test): compare normalized dates in subscription cancellation test

cancelation_date read straight off an unsaved in-memory doc is a
string from nowdate(), but the same field comes back as a
datetime.date after reload(). Wrap both sides in getdate() so the
comparison isn't type-sensitive.
2026-08-04 15:59:44 +05:30
Mihir Kandoi
3dd01e5120 Merge pull request #57777 from mihir-kandoi/fix/bom-creator-toolbar-actions
fix(manufacturing): reach the whole configurator from tree toolbar actions
2026-08-04 15:38:28 +05:30
Mihir Kandoi
097ce0f348 fix(manufacturing): reach the whole configurator from tree toolbar actions
The toolbar handlers were copied onto view.events as unbound functions, so
`this` inside them was that object literal rather than the BOMConfigurator.
They worked only because the literal also carried `frm`, and broke as soon as
a handler called a method the literal did not list: get_item_code, added when
the tree started keying nodes on the row name, threw
"this.get_item_code is not a function" and killed Add Raw Material, Add Sub
Assembly and Convert to Sub Assembly.

Assign the instance instead of a hand-maintained whitelist. Every method is
reachable, `this.frm` keeps working, and no future method can be forgotten.

Fixes #57773
2026-08-04 15:34:59 +05:30
Diptanil Saha
9ce32fc1da fix(sales_invoice): enable repost on account change of account in payments (#57775) 2026-08-04 09:52:28 +00:00
Sudharsanan11
ed78dd37be fix(accounts): skip party dashboard without invoice permission 2026-08-04 14:10:55 +05:30
Jatin3128
c1717d8689 fix: keep source rate on re-fetch when maintain same rate is enabled (#57479)
* fix: keep source rate on re-fetch when maintain same rate is enabled

With "maintain same rate" on, re-fetching item details on a row mapped from a
source document (e.g. a Purchase Order) pulled the latest Item Price, giving a
rate the document can never be saved with. Skip the price list fetch for such
rows and keep the source rate.

Fixes frappe/erpnext#57436

* fix: keep source rate on bulk apply_price_list when maintain same rate is on

The single-row re-fetch guard skipped the bulk apply_price_list path, so
changing the price list, party, or conversion rate on a mapped transaction
re-fetched current Item Prices and overwrote the mapped rates, breaking the
maintain-same-rate check on save.

Guard apply_price_list_on_item with the same source-row lookup, and resolve the
parent doctype via ctx.parenttype since the bulk path carries the child doctype
in ctx.doctype.

* fix: preserve full source pricing on rate-locked rows

Restoring only price_list_rate on a mapped row dropped any manual discount or
margin, so re-running pricing produced a rate that differed from the source and
still failed the maintain-same-rate check on save.

Copy the source row's whole pricing block (rate, discount, margin) and skip
pricing rules for locked rows, in both get_item_details and the bulk
apply_price_list path.

* fix: pass child_docname in server bulk price apply so the rate lock is reachable

The server-side _apply_price_list builds its item ctx from as_dict(), which omits
the child_docname key the desk (JS) callers add, so the maintain-same-rate lock in
apply_price_list could not match rows in that path. Pass child_docname for
consistency with the desk callers.

* test: cover maintain-same-rate preservation on re-fetch of a discounted row

Reproduces the end-to-end symptom: a mapped Purchase Receipt row with a source
discount (rate != price_list_rate) keeps its rate after a re-fetch, so the
document saves under maintain-same-rate. Covers percentage and amount discounts
via process_item_selection, the server recompute the desk mirrors.

* fix: read the locked rate from the persisted source row

get_rate_locked_source_row returned the mutable target row, so an unsaved rate or
discount edit on a mapped row was preserved on re-fetch instead of the source
pricing, and the document still failed maintain-same-rate on save. Read the
pricing straight from the linked source row in the database, and cover the
edit-then-refresh case with a test.

* fix: permission-check the source row before returning its rate

The rate lock reads the linked source row with a direct db.get_value, which
bypasses permissions on a whitelisted endpoint. Only return the source pricing
when the caller can read the source document, so a crafted request cannot
disclose another document's rate. Covered by a test.

* fix: import make_purchase_receipt from its current mapper module

make_purchase_receipt moved from purchase_order.py to
purchase_order/mapper.py in a develop refactor pulled in by this
branch's merge commit. Two tests added afterwards still imported it
from the old path, failing CI with an ImportError.

* fix: Simplify source retrieval logic in get_item_details

Removed permission check for source parent in get_item_details.py.

* Revert "fix: Simplify source retrieval logic in get_item_details"

This reverts commit 58863805bd.
2026-08-04 13:28:57 +05:30
Khushi Rawat
8cefaa355c Merge pull request #57539 from harisansari008/fix/dunning-timestamp-mismatch-multi-installment
fix: prevent TimestampMismatchError resolving Dunning with multiple overdue installments
2026-08-04 13:02:44 +05:30
Diptanil Saha
4255df05cd Merge pull request #57742 from diptanilsaha/fix/escape_data_in_templates
fix: escape data in multiple templates
2026-08-04 12:11:43 +05:30
ruthra kumar
bca3889f97 Merge pull request #57719 from krishna-254/fix/reversal-journal-entry-custom-remark
Fix/reversal journal entry custom remark
2026-08-04 10:59:46 +05:30
Krishna Shirsath
5e0e9ba668 fix: allow custom remark on reversal journal entry 2026-08-03 17:16:09 +05:30
Mihir Kandoi
e8b16a4228 Merge pull request #57754 from mihir-kandoi/fix/isolate-disabled-attribute-test-fixtures
test: isolate the disabled item attribute test fixtures
2026-08-03 17:01:24 +05:30
Mihir Kandoi
ae6749470f test(stock): isolate the disabled attribute fixtures
The test disabled the shared `Test Size` Item Attribute. On version-15
`FrappeTestCase` rolls back once per class instead of once per test, so the
flag stayed visible for the rest of `TestItem` and broke the seven tests that
build a variant from that attribute.

Build a dedicated attribute and template instead. Nothing the test writes is
reachable from another test, on either branch, so no cleanup is needed.
2026-08-03 16:43:07 +05:30
R-Jayaraman
c47cc37441 fix(opportunity): add validation for positive item quantities 2026-08-03 16:41:43 +05:30
Mihir Kandoi
8db8c6a83d fix(stock): allocate secondary item cost from the consumption entry (#57738)
* fix(stock): allocate secondary item cost from the consumption entry

A secondary item's rate is its BOM share of the cost of the consumed
rows. With Get RM Cost From Consumption Entry enabled the consumption
happens in a separate document, so the Manufacture entry carries no
consumed rows and that cost is zero. The share evaluated to zero, and the
row fell through to the item's own valuation rate.

Only the finished good substituted the consumption entry's cost. Against
a consumption entry of 1000 and a BOM allocating 75% to the finished good
and 25% to scrap, the finished good took its 750 while the scrap took an
unrelated valuation of 100, booking 850 for 1000 consumed.

Derive the allocation base once and use it for both sides.

* test(stock): cover secondary allocation against a consumption entry

A consumption entry of 1000 splits into 750 and 250 by the BOM's shares.
2026-08-03 10:58:23 +00:00
Mihir Kandoi
aef69202ea Merge pull request #57747 from mihir-kandoi/fix/disabled-attribute-blocks-variant-edits
fix: disabled item attribute blocks unrelated edits to existing variants
2026-08-03 16:16:24 +05:30
diptanilsaha
3df596d84e fix: escape data on stock_summary_template 2026-08-03 16:16:07 +05:30
diptanilsaha
10c439ff01 fix: escape item name and item title on item_selector 2026-08-03 16:16:07 +05:30
diptanilsaha
2d387002d9 fix(workstation): escape data on get_workstations 2026-08-03 16:15:59 +05:30
Mihir Kandoi
7d901ed92c fix(stock): treat a 0% BOM cost allocation as no cost (#57736)
* fix(stock): treat a 0% BOM cost allocation as no cost

A BOM splits its raw material cost between the finished good and its
secondary items, and validate_total_cost_allocation holds the two to
100%. An allocation of 0% therefore means the finished good takes
everything and the secondary item carries no cost.

The code read it as no allocation at all. A cost_allocation_per of 0 is
falsy, so the branch was skipped, the row kept a rate of zero, and the
fallback below handed it the item's own valuation rate. Producing 1000 of
raw material into a finished good at 100% and scrap at 0% booked 1000 to
the finished good and another 100 to the scrap.

Apply the BOM's share whatever it is, and mark the rate as derived so the
valuation fallback leaves a deliberate zero alone. rate_derived_from_consumption
becomes has_derived_rate, since it now guards more than the consumption case.

* test(stock): cover a secondary item allocated 0% of the cost

The finished good takes the full 1000 and the scrap row is worth nothing.
2026-08-03 10:42:24 +00:00
Mihir Kandoi
8d5326196e test(stock): cover editing a variant whose attribute is disabled
Assert that a variant saves after its attribute is disabled when the edit
leaves the attribute rows alone, and that changing an attribute value still
throws.
2026-08-03 16:00:27 +05:30
Mihir Kandoi
25cd793617 fix(stock): validate only the variant attributes that changed
Disabling an Item Attribute writes `disabled = 1` into every Item Variant
Attribute row, including the rows on the template. `validate_variant` runs
on every save and walks the whole attribute table, so any later save of an
existing variant re-checked its untouched rows against the now-disabled
template row and threw. `update_variants` hit the same wall, which made a
single template save fail once an attribute was disabled.

The flag exists to keep an attribute out of new variants, not to freeze the
variants that already use it. item.js only reads it to drop the attribute
from the variant creation dialog.

Skip rows that are unchanged since the last save. New and edited rows are
still checked, so a disabled attribute cannot be added to an existing
variant, and the same guard covers the sibling checks for attributes and
values that the template no longer offers.
2026-08-03 15:57:35 +05:30
Mihir Kandoi
7886bd2cab fix(stock): stop treating a Repack secondary item as a finished good (#57735)
* fix(stock): stop treating a Repack secondary item as a finished good

mark_finished_and_secondary_items flagged every incoming Repack row as a
finished item, secondary rows included. Two things followed from that.
The row never reached the secondary-item branch in _set_incoming_item_rate,
so its own cost_allocation_per was never applied, and the BOM's
finished-good percentage was applied to every incoming row rather than
to the finished good alone.

Value was destroyed as a result. Repacking 1000 of raw material under a
BOM that allocates 75% to the finished good and 25% to scrap booked 500
to the finished good and 250 to the scrap: 750 in against 1000 out.

Leave secondary rows unflagged so each side takes the share the BOM
declares.

* test(stock): cover cost allocation for a Repack secondary item

A BOM allocating 75% to the finished good and 25% to scrap must split
1000 of raw material into 750 and 250, leaving no difference.
2026-08-03 10:19:09 +00:00
Mihir Kandoi
be3df759f1 Merge pull request #57732 from mihir-kandoi/fix/secondary-item-without-bom-balances-manufacture
fix(stock): cost a BOM-less secondary item out of the finished good
2026-08-03 15:22:16 +05:30
Mihir Kandoi
7f47361ebd test(stock): cover a secondary item added without a BOM
A Manufacture entry with a raw material worth 1000, a finished good and a
Scrap row typed in the UI must value the scrap at its own rate and take
that value out of the finished good, leaving no difference.
2026-08-03 15:01:08 +05:30
Mihir Kandoi
5e81cd1540 fix(stock): cost a BOM-less secondary item out of the finished good
The legacy scrap checkbox deducted the scrap row's value from the
finished good, so a Manufacture entry balanced. Its replacement, the
Secondary Item Type dropdown, only balances when the row carries a BOM
Secondary Item link, because the cost allocation percentage lives there.
A row typed as Scrap in the UI has no such link, so its value was added
on top of a finished good that already absorbed the whole raw material
cost, and the entry closed with a non-zero difference.

Treat a secondary row with no BOM link the way the legacy scrap item was
treated: deduct its value from the finished good.

The finished good's rate is derived from the other incoming rows, so
those rows must be rated first. Previously the finished good was rated
in row order, ahead of the secondary rows, and picked up their amounts
only on a later validate pass. Rate the finished goods last so a single
pass is correct.
2026-08-03 15:00:41 +05:30
Mihir Kandoi
33ea059018 Merge pull request #57737 from mihir-kandoi/fix/secondary-item-must-not-waive-quality-inspection
fix(stock): stop a secondary item type from waiving quality inspection
2026-08-03 14:59:13 +05:30
Nikhil Kothari
abc3da6b97 fix(banking): fetch company list from DB instead of boot (#57731)
* fix(banking): fetch company list from DB instead of boot

* fix: show error banner for company list fail fetch
2026-08-03 14:11:36 +05:30
Mihir Kandoi
fec5dae639 test(stock): cover inspection on a receipt row typed as a secondary item
The row must be blocked with or without the type set.
2026-08-03 13:55:27 +05:30
Mihir Kandoi
dfec7bd5c7 fix(stock): stop a secondary item type from waiving quality inspection
The inspection skip for secondary rows applied to every purpose, and in
validate_inspection it skipped the row even when the item itself mandated
inspection. Secondary Item Type is only meaningful on the purposes that
produce secondary items, but nothing clears it elsewhere, since
mark_finished_and_secondary_items runs for Manufacture and Repack alone.

A Material Receipt of an item marked Inspection Required Before Purchase
is blocked without an inspection. Setting Secondary Item Type on the row
submitted it clean.

Limit the exemption to the purposes that produce secondary items, and to
other doctypes such as Subcontracting Receipt, which carry the field with
its intended meaning. The client-side mirror is kept in sync.
2026-08-03 13:55:26 +05:30
Sudharsanan11
5442ad4c48 test(payment reconciliation): cover supplier exchange gain posting 2026-08-03 13:40:45 +05:30
Sudharsanan11
4688ddd217 fix(payment reconciliation): correct supplier gain/loss posting 2026-08-03 13:40:45 +05:30
Raffael Meyer
915eef0355 ci: hide eo.po from translation PR review details (#57200) 2026-08-03 07:38:11 +00:00
Mihir Kandoi
947f1b148c Merge pull request #57647 from aerele/fix/sales-zero-qty-return-validation
fix(sales): reject sales returns where every item has zero quantity
2026-08-03 12:56:02 +05:30
R-Jayaraman
732c884633 test(sales): add coverage for zero-qty return rejection
Greptile flagged that the sales-side zero-qty-return fix had no dedicated
test proving the behavior - the existing suite happened to pass, but
nothing specifically asserted that an all-zero return is rejected while
a normal negative-qty return still succeeds.

Adds two tests covering the doctypes that rely entirely on this check
(no other guard covers them for a non-stock-effect return):
- Delivery Note return with qty 0 -> rejected
- Sales Invoice return with qty 0 (no update_stock) -> rejected

POS Invoice is not covered separately here since it always runs with
update_stock=1, which is already guarded by the pre-existing
validate_zero_qty_for_return_invoices_with_stock check regardless of
this fix.
2026-08-03 12:41:38 +05:30
R-Jayaraman
a3e9d13da3 fix(sales): reject sales returns where every item has zero quantity
validate_returned_items() set items_returned=True whenever a row matched
a valid item from the original document, even if its qty was 0. This let
a Sales Invoice, Delivery Note, or POS Invoice return be submitted with
every line at qty=0 - a no-op document with no stock or financial effect
that still consumed a document number and linked back to the original
transaction.

Scoped to the Sales side only: items_returned now flips to True for
Sales Invoice/Delivery Note/POS Invoice only when qty (or received_qty)
is actually negative, so an all-zero sales return correctly hits the
existing "At least one item should be entered with negative quantity"
check. Purchase Invoice, Purchase Receipt, and Subcontracting Receipt
are unchanged.
2026-08-03 12:40:57 +05:30
Mihir Kandoi
b4d73cd934 Merge pull request #57725 from aerele/fix/stock-over-delivery-role-scope
fix(stock): scope over deliver/receive role check to delivery and receipt overflow
2026-08-03 12:39:08 +05:30
Afsal Syed
99630f40eb test(stock): prevent settings leakage in purchase order tests 2026-08-03 12:27:33 +05:30
Afsal Syed
0b271e24b6 test(stock): add test cases verifying stock over delivery role does not bypass order allowance 2026-08-03 12:27:33 +05:30
Afsal Syed
248873034d fix(stock): scope over deliver/receive role check to delivery and receipt overflow 2026-08-03 12:27:33 +05:30
Afsal Syed
446ec6030a fix(stock): validate over delivery/receipt allowance in stock settings 2026-08-03 12:27:33 +05:30
Mihir Kandoi
c020de5a69 Merge pull request #57097 from aerele/fix/qi-reading-number-format
fix(stock): read quality inspection readings in the user's number format
2026-08-03 12:26:18 +05:30
Mihir Kandoi
f03c1311cd fix(controllers): source trend report labels from the master (#57724)
* fix(controllers): source trend report labels from the master

item_name, customer_name, territory and supplier_name are stored on each
transaction and editable, so they are not functionally dependent on the grouped
key and historical documents can hold different values for the same item,
customer or supplier. Aggregating them with Max() is a text sort, and MariaDB
folds case while PostgreSQL orders by byte value, so the two engines can label
the same row differently.

Read each from its master instead. Those values ARE dependent on the grouped
key, so they can be grouped without splitting rows and agree on both engines by
construction rather than by an assumption about the data. Supplier needed no new
join -- the Supplier master was already joined as t3 for supplier_group.

A Quotation's party_name is a dynamic link to either a Customer or a Lead, so
neither master can be joined without dropping the other; there the values come
from correlated subqueries over both, keyed only on the grouped party_name.

Row counts and every numeric total are unchanged. What changes is that a
renamed record now shows its current name rather than whichever historical
snapshot happened to sort highest.

* test(selling): assert which label the trends report returns

The existing tests assert the customer stays one row but never which territory
or name comes back, so a divergence between engines passes unnoticed. Asserts
both equal the Customer master's values while an order stores a different
territory.

* fix(controllers): resolve a Quotation's party label through quotation_to

party_name is a dynamic link, so looking it up in Customer and Lead alone was
wrong twice over: a Quotation raised against a Prospect or a CRM Deal got a
blank label, and when a Lead shared its name with a Customer the Customer-first
lookup returned the wrong record's name and territory.

Resolve through the quotation_to discriminator instead, mirroring
Quotation.set_customer_name -- Customer, Lead (company_name falling back to
lead_name), Prospect, and CRM Deal. The CRM Deal branch is emitted only when its
table exists, since it ships with the CRM app.

quotation_to joins the GROUP BY as well: two parties of different types can
share a name, and merging them into one row was never right.

* style(controllers): name the quotation CASE branches

semgrep's string-concat-in-list flags adjacent string literals inside a list,
since that shape is usually a missing comma rather than deliberate. Bind each
branch to a name first so the concatenation is unambiguous.
2026-08-03 06:52:25 +00:00
Mihir Kandoi
8154c45bf0 fix(accounts): key the payment ledger CTEs on account, not Max(account) (#57720)
* fix(accounts): key the payment ledger CTEs on account, not Max(account)

QueryPaymentLedger builds two CTEs -- voucher amount and outstanding -- and
joins them on account among other columns. Both sides selected Max(account)
while grouping without it, so the join key was an aggregate over two different
row sets. A voucher posting ledger entries against two party accounts could
have the two sides pick different accounts, the join miss, and the outstanding
come back NULL. Max() over text is a sort, so which account wins is also
collation-dependent, and the engines sort text differently.

Group both CTEs by account instead. That makes the join key a real column and
scopes each Sum() to a single account -- so amount_in_account_currency is no
longer summed across accounts that may not share a currency. Row shape only
changes for a voucher that genuinely spans two party accounts for one party,
where today's single row is already an arbitrary pick over mixed currencies.

cost_center and remarks stay descriptive but genuinely vary per entry, and were
aggregated independently, so they could be stitched together from different
entries into a row that was never posted. They now come off one real entry,
picked by Min(name) -- Payment Ledger Entry declares no autoname rule, so
frappe names it by hash, and those are lower-case, which keeps the pick free of
the collation divergence.

* test(accounts): cover payment ledger metadata coherence

A Journal Entry posting two receivable lines for one customer with different
cost centers and remarks. Whatever row the ledger returns, its cost center and
remarks must be a pair that was actually posted. Guards the fixture itself, so
it cannot pass by posting only one distinct pair.

* test(accounts): cover the account-keyed payment ledger aggregation

The coherence test posts both party lines to one account, so it exercises the
representative-row metadata but not the account-keyed grouping or the CTE join.
Adds a Journal Entry posting to two receivable accounts for one customer and
asserts each account comes back as its own row, with its own amount and a
non-null outstanding.
2026-08-03 06:46:04 +00:00
Mihir Kandoi
00d17ca5db test(stock): cover reading number formats end to end
Set the number format on the session user rather than on System Settings: the
code reads the user default, which shadows the global one, so these tests never
exercised the path they were written for. Restoring it in a finally also keeps
a failed assertion from leaving the whole suite in another locale.

Add a table test over every format in NUMBER_FORMAT_MAP, covering the grouped
values and the three formats parse_float used to read as 0, and restore the
formula-based coverage for non-numeric readings.
2026-08-03 12:14:19 +05:30
Mihir Kandoi
5b5f354090 fix(stock): accept every number a reading can be written as
parse_float and is_valid_number each re-derived the number grammar, so the
validator accepted strings flt() cannot parse: str.isdigit() lets superscripts
through and lstrip("+-") lets repeated signs through, both then silently scored
as 0. One parse_reading() returning None when float() refuses the value makes
acceptance and conversion true by construction.

The grammar was also wrong for several formats. Where the group separator is
not a dot, a dot-decimal reading such as 1.15 parsed correctly before and is
accepted again. #,### and #.### report no decimal separator at all, which
rejected every fractional reading outright and, for #.###, reread a stored
1.500 as 1500.0; they now fall back to a dot and give up the grouping that
would collide with it.

Only readings that change are checked, so an inspection entered by a user in
one locale stays saveable and submittable by a user in another, and manual
inspection rows keep the free text they were never parsed for.

NumberFormat replaces get_number_format_info, which frappe drops in v16.
2026-08-03 12:14:19 +05:30
Sudharsanan11
b1f188146e test(stock): cover quality inspection readings in every number format
covers the reported case, a 1,15 reading in the space grouped "# ###,##"
format, which was read as 115 and rejected. also covers the dot grouped
comma format, and asserts that a reading written with the wrong separator,
or one that is not a number at all, is now rejected with an error rather
than read as a different value.
2026-08-03 12:14:19 +05:30
Sudharsanan11
3752be809f test(stock): drop non numeric reading from formula based quality inspection
a numeric reading of "random text" was read as 0 and pulled the mean from
0.6 down to 0.4, which the test then asserted as accepted. such a reading
is now rejected outright, and the test is about formula evaluation, so drop
the row. its assertions are unchanged.
2026-08-03 12:14:19 +05:30
Sudharsanan11
e74c0a3cdb fix(stock): read quality inspection readings in the user's number format
readings are Data fields, so they are parsed server side. parse_float only
swapped the separators for "#.###,##", so in the space grouped "# ###,##"
(polish) a reading of 1,15 was read as 115, fell outside the acceptance
range and silently rejected the inspection. strip whatever the group
separator is and normalise whatever the decimal separator is instead.

it also read the global number format, while the desk formats numbers with
the user's own. a user whose locale differs from the site therefore typed
readings in a format the server did not parse them with. read the user
default, which falls back to the global one.

a reading that is not a valid number in that format is now rejected with an
error instead of being read as a different number.
2026-08-03 12:14:19 +05:30
Mihir Kandoi
d74add35d4 fix(accounts): take POS summary warehouse and cost centre from one item line (#57723)
* fix(accounts): take POS summary warehouse and cost centre from one item line

Both describe an item line, not the invoice, and an invoice can carry several.
They were aggregated independently per invoice, so the report could show a
warehouse from one line beside a cost centre from another -- a pair that was
never posted.

The warehouse then becomes an outer grouping key, so the pick is not merely a
label: it decides how rows are partitioned across owner/date and therefore what
each row totals. Max() over text is a sort, and MariaDB folds case while
PostgreSQL orders by byte value, so the two engines can partition differently.

Take both off one real line instead, and the mode of payment off one real
payment line for the same reason. Sales Invoice Item is hash-named and Sales
Invoice Payment declares no autoname rule, so frappe hash-names it too -- which
keeps Min(name) free of the collation divergence that sorting text has.

* test(accounts): cover POS summary warehouse/cost-centre coherence

The existing tests post a single item line, so they cannot see this. Adds an
invoice with two lines whose warehouse and cost centre are deliberately
crossed: the higher warehouse sits on the line with the lower cost centre, so
an independently aggregated pair belongs to neither line.

* fix(accounts): pick the POS summary representative by idx, not by hash

Min(name) selected whichever child row happened to have the lowest hash, which
is arbitrary and turns on something unrelated to the data. Min(idx) selects the
first line the user actually entered: an integer, so the pick is free of
collation, and it is meaningful rather than incidental.

The join moves to (parent, idx), which is unique per parent.
2026-08-03 06:42:28 +00:00
Mihir Kandoi
bf869c3426 Merge pull request #57718 from frappe/pg-audit/search-ranking-case-insensitive
fix(controllers): restore case-insensitive employee/lead/bom search ranking
2026-08-03 12:08:33 +05:30
Mihir Kandoi
d44ed5357d Merge pull request #57645 from aerele/fix/purchase-zero-qty-return-validation
fix(purchase): reject purchase returns where every item has zero quan…
2026-08-03 11:45:36 +05:30
Mihir Kandoi
1968f06cc8 test(controllers): assert lead search ranking, not just result count
The existing query tests assert only how many rows come back, so an ordering
divergence between engines passes unnoticed. Adds a case-adversarial pair: a
lead whose name starts with the search term in upper case, and one containing
it in lower case later on. The first must rank ahead of the second.
2026-08-03 11:38:58 +05:30
Mihir Kandoi
a7a14c82da fix(controllers): restore case-insensitive employee/lead/bom search ranking
Reapplies #56330, which was reverted by #56389 with no recorded reason and has
been absent since 23 June.

The search filter uses .like(), which frappe renders as ILIKE on PostgreSQL, so
a candidate matches regardless of case. The ranking used a bare Locate(), which
frappe renders as strpos() -- case-sensitive there. A candidate can therefore
pass the filter, score no match in the ranking, fall back to 99999 and sort
last, while MariaDB's case-insensitive LOCATE ranks it first.

Same query, different order on the two engines, and a different result page
once page_len cuts between them.

Lower() both operands, matching the item, project, user and pick list handlers
in this same file, which were already correct.
2026-08-03 11:38:57 +05:30
Mihir Kandoi
282712eec2 Merge pull request #57716 from frappe/pg-audit/collation-representative-lines
fix(postgres): read BOM/SO/MR line columns off one line, not Max()
2026-08-03 09:41:36 +05:30
Mihir Kandoi
c8adf9937b refactor(postgres): memoise representative lines with frappe's request_cache
Three helpers each managed their own dictionary on frappe.local, duplicating
cache lifecycle and key handling. @request_cache does the same thing centrally
and is cleared with the request, so the copies cannot drift apart.

Behaviour is unchanged: the decorator keys on the call arguments, which are the
same tuple each hand-rolled key was built from.
2026-08-03 01:03:11 +05:30
Mihir Kandoi
100d0ee784 test(manufacturing): cover the BOM representative-line pick
A BOM listing one item on two lines, with descriptions and source warehouses
that differ. The second line's description sorts above the first on either
engine, so an aggregated value would win; the row must instead carry the first
line's description together with that same line's warehouse.
2026-08-03 00:56:56 +05:30
Mihir Kandoi
414e6560af fix(postgres): read BOM/SO/MR line columns off one line, not Max()
Max() over a text column is a sort, and the engines sort text differently:
MariaDB's utf8mb4 collations fold case, the CI PostgreSQL orders by byte
value. MAX('abc','ABD') is 'ABD' on MariaDB and 'abc' on PostgreSQL --
confirmed on CI in the probe attached to #56241.

The parity effort wrapped many descriptive columns in Max() on the reasoning
that it returns the value MySQL picked arbitrarily. Where the column is
functionally dependent on the group key that holds and the wrap is a genuine
no-op. Where it genuinely varies -- description, item_name, uom and their
warehouses all describe a LINE, not the item -- it does not: MySQL picked a
row, not a maximum, and the sort now diverges between engines. Aggregating
each column separately can also pair one line's description with another's
warehouse, or a uom with the wrong conversion factor.

Take those columns from a single real line instead, the first by idx.

Only groups built from more than one line need it. Each query now also selects
Count(<line>.name).distinct(), and the representative pass returns immediately
when no group has more than one line -- in that case Max() of a single value
is already exact and collation cannot apply. A BOM with no repeated item
therefore issues no extra query at all, which matters because the explosion
and sub-assembly resolution recurse per sub-BOM. Genuine repeats are memoised
per request.

Sites covered: BOM explosion and sub-item queries, sub-assembly raw materials,
get_bom_items_as_dict, BOM Stock Analysis (both queries), Requested Items to
Order and Receive, Pending SO Items for Purchase Request, and Job Card
secondary items.
2026-08-03 00:56:55 +05:30
Mihir Kandoi
a30f3dde0f Merge pull request #57711 from frappe/pg-audit/purchase-register-add-deduct
fix(accounts): net Add and Deduct tax rows in Purchase Register
2026-08-03 00:52:24 +05:30
Mihir Kandoi
03183fc4d9 fix(stock): take disassembly source columns from one posted line (#57710)
* fix(stock): take disassembly source columns from one posted line

get_items_from_manufacture_stock_entry collapses a work order's Manufacture
entries to one row per item and wrapped fifteen Stock Entry Detail columns in
independent Max() to satisfy Postgres' strict GROUP BY. Those columns describe
a line, not an item, and three sets have to stay together:

  uom only means something beside its conversion_factor
  batch_no and serial_no only beside their warehouse
  is_finished_item decides whether the row is the output or an input

Aggregated separately they can be drawn from different lines. Two Manufacture
entries consuming the same item in Nos and in Box return ("Nos", 5) -- a pair
that was never posted, and one that does not describe the summed quantity.

Keep the sums (and the qty-weighted basic_rate) in the aggregate, and read the
descriptive columns off a single real line: the earliest by Stock Entry
creation then idx. That is what MariaDB returned in practice, it is
deterministic, and it is identical on both engines. Same representative-row
shape already used by BOM Stock Analysis and the sub-assembly queries.

* test(manufacturing): cover disassembly source-row coherence

Two Manufacture entries consume the same raw material in different UOMs, so
the max uom and the max conversion factor come from different lines. Asserts
the returned pair is one that was actually posted. Fails on the previous
per-column Max() with ('Nos', 5.0) not found in {('Nos', 1.0), ('Box', 5.0)}.

* fix(stock): aggregate disassembly quantities in stock UOM
2026-08-03 00:52:24 +05:30
Mihir Kandoi
d5ea0d1f6f fix(manufacturing): stop BOM Stock Analysis inflating both its sums (#57709)
* fix(manufacturing): stop BOM Stock Analysis inflating both its sums

get_bom_data left-joined Bin on item_code alone and then summed over the
result. Bin holds one row per warehouse and BOM Item one row per line, so the
join is a cross product and each SUM counts the other side's rows:

  Sum(qty_consumed_per_unit) x (number of warehouses holding the item)
  Sum(bin.actual_qty)        x (number of BOM lines carrying the item)

A component on two BOM lines, stocked in two warehouses, reported a per-unit
requirement of 10 instead of 5 and available stock of 20 instead of 10 --
wrong on both engines, and wrong in the single-line case too as soon as the
item sits in more than one warehouse.

Aggregate Bin to one row per item_code before joining, so neither sum can see
the other's duplicates. The warehouse filter moves into that subquery; it
previously sat in the outer WHERE against a left-joined column, which
silently made the join inner, so the join is now made inner explicitly when a
warehouse is given to keep items with no bin there excluded as before.

* test(manufacturing): cover the BOM Stock Analysis bin-join cross product

Component on two BOM lines, stocked in two warehouses: the join yields four
rows, so both sums are doubled. Asserts qty_per_unit is the sum of the lines'
own per-unit quantities and actual_qty the real total across warehouses.
Fails on the previous single-query form with 10.0 != 5.0.
2026-08-03 00:52:23 +05:30
Mihir Kandoi
5eabd176f5 fix(manufacturing): compute BOM item amount per line (#57708)
* fix(manufacturing): compute BOM item amount per line

get_bom_items_as_dict groups BOM lines by item_code, so a BOM listing the
same item on more than one line collapses to a single row. The amount column
multiplied the summed quantity by a single line's rate:

    Sum(stock_qty / bom.quantity) * Max(rate) * qty

That is neither line's amount and not their total. The Max() was added to
satisfy Postgres' strict GROUP BY on the assumption that rate is constant per
item, but rate is editable per line.

Fold the rate into the sum so every line contributes its own:

    Sum(stock_qty / bom.quantity * rate) * qty

Identical for the common single-line item, correct for duplicates, and valid
on both engines. Same class as the fix applied to budget_controller's
requested amount.

* test(manufacturing): cover BOM item amount across duplicate lines

A BOM listing the same item twice, once in the stock UOM and once in a UOM
with a conversion factor, gives the two lines different rates (rate is the
valuation rate scaled by the conversion factor). The two lines collapse into
one row in get_bom_items_as_dict, so amount must be the sum of each line's
own qty x rate.

Guards the fixture with an assertion that the two rates actually differ,
so the test cannot pass vacuously. Fails on the previous
Sum(stock_qty) * Max(rate) expression.

* fix(manufacturing): use matching UOM quantity for BOM amount
2026-08-03 00:52:23 +05:30
Mihir Kandoi
8f227ad80e Merge pull request #57715 from frappe/pg-audit/collation-taxonomy
docs(postgres): catalog the collation-dependent text pick
2026-08-02 22:20:20 +05:30
Mihir Kandoi
2c6208ad00 Merge pull request #57714 from frappe/ci/patch-test-stacked-pr-base
ci(patch): fall back to develop when the base ref has no frappe branch
2026-08-02 22:18:50 +05:30
Mihir Kandoi
80ca8b3a25 docs(postgres): catalog the collation-dependent text pick
Max()/Min() over a text column is a sort, and the engines sort text
differently: MariaDB's utf8mb4 collations fold case, PostgreSQL as CI runs it
orders by byte value. MAX('abc','ABD') is 'ABD' on MariaDB and 'abc' on
PostgreSQL, confirmed on CI in the probe attached to #56241.

That makes a Max() over a text column which varies in case within its group a
live parity gap, rather than the arbitrary-pick preservation the wrap is
usually justified as. Where the column is functionally dependent on the group
key it stays a genuine no-op and collation cannot matter, so the rule is
scoped to non-FD columns to keep it a high-precision signal.

Recorded as a fifth second-order trap in the guide and in the Greptile
instructions, including the trap that a local macOS PostgreSQL agrees with
MariaDB here and reports a false all-clear.
2026-08-02 22:08:01 +05:30
Mihir Kandoi
39b6f37a48 ci(patch): use GITHUB_REF instead of rebuilding it from type and name
GITHUB_REF is already the fully qualified ref for both branch and tag events,
so reconstructing refs/heads/$GITHUB_REF_NAME and refs/tags/$GITHUB_REF_NAME
just risks the two drifting apart. Keep the type check, since it still decides
whether the develop fallback applies, and take the ref verbatim.
2026-08-02 22:06:21 +05:30
Mihir Kandoi
28d498012a ci(patch): resolve the frappe ref by type and only fall back for branches
The probe used --heads with a bare name, so it could not describe a tag push
and would have fallen back to develop for one. Resolve a fully qualified ref
from the event instead: the PR base or pushed branch under refs/heads, a tag
under refs/tags, and fail loudly on an unrecognised ref type.

Only branch refs are eligible for the develop fallback. A tag that is absent
from frappe is a real error, not a stacked-PR base, so it still fails.
2026-08-02 22:04:48 +05:30
Mihir Kandoi
ccf54b5881 ci(patch): only fall back when the frappe branch is genuinely absent
The previous `||` treated every fetch failure as a missing branch, so a
transient network or auth error on a base that does exist in frappe would
silently substitute develop and report Patch Test results against the wrong
revision.

Probe with `ls-remote --exit-code` instead: exit 2 means no matching ref, so
fall back; any other non-zero status is a real failure and is re-raised.
2026-08-02 20:45:05 +05:30
Mihir Kandoi
1a83fc516e ci(patch): fall back to develop when the base ref has no frappe branch
The Patch Test fetches the frappe repo using this erpnext PR's base branch
name. For an ordinary PR that is develop, which exists in frappe/frappe. For a
stacked PR the base is an erpnext feature branch with no counterpart there, so
the fetch fails and the step exits 128 before any patch runs:

    fatal: couldn't find remote ref pg-audit/bom-amount-per-line

This affects every stacked PR. It has been latent rather than absent: earlier
stacks passed only because their Patch Test ran while they still targeted
develop, before being retargeted onto the layer below.

Fall back to develop when the base ref does not resolve. Ordinary PRs and
version-branch PRs are unaffected -- their base exists in frappe, so the first
fetch succeeds and the fallback never runs.
2026-08-02 20:26:47 +05:30
MochaMind
78f9be257b chore: update POT file (#57707) 2026-08-02 14:31:32 +02:00
Shllokkk
61b80050d1 Merge pull request #57703 from Shllokkk/create-payment-entries-from-payable-report
feat: validate selection and improve Create Payment Entries dialog
2026-08-02 17:43:17 +05:30
Shllokkk
bb5b71643b feat: show PE count, grand total and draft note in payment dialog 2026-08-02 17:28:51 +05:30
Mihir Kandoi
0b9dd11115 Merge pull request #57699 from mihir-kandoi/codex/fix-shipping-rule-duplicate-taxes
fix: prevent duplicate shipping charges without cost center
2026-08-02 12:18:17 +05:30
Mihir Kandoi
106ecd7120 chore: remove shipping rule comments 2026-08-02 12:03:14 +05:30
Mihir Kandoi
a4134af30b fix: prevent duplicate shipping charges without cost center 2026-08-02 12:01:35 +05:30
Mihir Kandoi
c3cd4f18f2 Merge pull request #57676 from mihir-kandoi/feat/mr-supplier-selection-dialog
feat: select a supplier per item when creating Purchase Orders from a Material Request
2026-08-02 11:55:49 +05:30
Mihir Kandoi
6477709f7c Merge pull request #57674 from mihir-kandoi/fix/uom-conversion-factor-precision
fix: preserve UOM conversion factor precision in transactions
2026-08-02 11:55:13 +05:30
Shllokkk
7fdb768259 feat: validate selection and create draft payment entries synchronously 2026-08-01 19:40:39 +05:30
Mihir Kandoi
07ac4d83ef feat(job_card): print quantities with their stock uom (#57689)
* feat(job_card): carry the stock uom on the job card

Every quantity the job card reports belongs to the item it produces, but the
document had no unit of its own, so messages could only print bare numbers.

Add the Stock UOM field, set from the finished good or the final product, and
backfill the job cards that already exist.

* fix(job_card): print quantities with their unit

A bare 5 in an error says nothing about what was counted. Every message that
reports a quantity now names its unit, taking it from the job card's stock uom,
from the previous operation's finished good when the message compares two
operations, and from the item itself for a raw material transfer.

The completion dialogs read the same unit off the job card.

* refactor(job_card): move the stock uom next to the qty it measures

* fix(job_card): keep the stock uom backfill atomic

Drop the auto commit toggle so the backfill is a single transaction with no
connection flag left behind when it raises, and select the job cards to fill
with an explicit unset filter instead of a value list.
2026-08-01 18:34:31 +05:30
Mihir Kandoi
0ddf72dae9 refactor(job_card): make the completion dialog say what it asks for (#57688)
* refactor(job_card): drop the unused make_finished_good handler

Nothing triggered it and Job Card has no make_finished_good method to call.

* refactor(job_card): make the completion dialog say what it asks for

The dialog qty shares the Qty to Manufacture label with the field on the form
while it means the current cycle only, its title fell back to the generic Enter
Value because frappe.prompt takes four arguments and it was passed five, and
nothing on it stated that the three quantities have to add up.

Name the cycle in the label, title the dialog after the button that opens it,
and describe the split on the fields. Same wording in the shop floor dialog.
2026-08-01 18:34:31 +05:30
Mihir Kandoi
7bffd84482 fix(job_card): reject a completion split that cannot add up (#57687)
* fix(job_card): reject a completion split that cannot add up

The completion dialogs silently dropped a recalculation whose result went
negative, so entering a pending qty larger than what is left of the qty to
manufacture kept the contradiction (3 to manufacture, 3 completed, 2 pending)
and the job card only failed much later, on submission.

Keep the split consistent while it is entered: reset the pending qty when the
qty to manufacture changes, and refuse a completed, pending or process loss qty
that leaves the others negative. complete_job_card validates the same rule, so
the shop floor and the API cannot store a split that will never submit.

Also name the three parts in the submission error instead of calling their sum
the Total Completed Qty, which read as a contradiction of the field itself.

* test(job_card): cover the completion qty split guard
2026-08-01 18:34:30 +05:30
Mihir Kandoi
970039d8ec fix(job_card): leave the pending qty out of the job card's own output (#57686)
* fix(job_card): leave the pending qty out of the job card's own output

Pending qty is the part of a job card handed over to another job card, but the
status and the manufacturing entry still measured the card against its full
for_quantity. A card submitted with 3 completed and 2 pending was stuck at Work
In Progress with no way to change it, and its manufacturing entry was built for
the full 5.

Measure both against for_quantity minus pending qty, so the card reaches To
Manufacture on submission, its manufacturing entry covers the completed qty, and
it is Completed once that qty is manufactured.

* test(job_card): cover a job card completed with a pending qty
2026-08-01 18:34:30 +05:30
Mihir Kandoi
0e1bc58b2e fix(job_card): apply the completion dialog's qty to manufacture (#57685)
* fix(job_card): apply the completion dialog's qty to manufacture

Both the desk dialog and the shop floor session dialog send for_quantity when
completing a job card, but complete_job_card dropped it. Reducing Qty to
Manufacture to 3 on a job card of 5 left for_quantity at 5, so set_process_loss
turned the untouched 2 into process loss on the next save.

The dialog qty covers the current cycle, so add it to the qty already completed
by the earlier cycles of the job card instead of overwriting for_quantity, and
validate the pending qty against the result.

* test(job_card): cover qty to manufacture from the completion dialog

Reducing the dialog qty resizes the job card without inventing process loss, and
a pending qty split across two cycles leaves for_quantity untouched.
2026-08-01 18:34:30 +05:30
Mihir Kandoi
3bd3354152 fix(job_card): require the previous operation to be manufactured (#57684)
* fix(job_card): block next operation until previous operation is manufactured

With track semi finished goods, Work Order Operation completed_qty is set from
the submitted job cards' total completed qty, so a job card of the next
operation could be started and completed even when no Manufacture entry existed
for the previous operation. The semi-finished goods it consumes were never
produced.

Validate the sequence against the qty actually manufactured against the previous
operations' job cards (Manufacture entries / Subcontracting Receipts) when the
work order tracks semi finished goods.

* test(job_card): cover manufactured qty check across previous operations

Work order with operations A and B at sequence 1 and C at sequence 2, tracking
semi finished goods. C stays blocked while A's job card is submitted but its
Manufacture entry is missing, and once A is manufactured for 3, C can only be
completed for 3.
2026-08-01 18:34:29 +05:30
Mihir Kandoi
1a49e73c85 Merge pull request #57681 from Shllokkk/sre-voucher-qty-use-demand
fix: set reservation voucher_qty to voucher demand not reserved qty
2026-08-01 15:42:12 +05:30
Shllokkk
7a97dc3361 test: partial work order reservation records full voucher_qty 2026-08-01 15:29:20 +05:30
Shllokkk
7995bb9960 fix: set reservation voucher_qty to voucher demand not reserved qty 2026-08-01 15:29:20 +05:30
Mihir Kandoi
2e72846670 fix: label the items table in the supplier selection dialog
The grid template always renders its label line, so leaving the table unlabelled
left an empty line hanging above the description.
2026-08-01 09:23:09 +05:30
Mihir Kandoi
44fdf7bea9 fix: keep the bulk supplier field to half the supplier selection dialog
A lone Link field stretched the full width of the dialog, which reads as a
search bar rather than a field. A column break holds it to half.
2026-08-01 09:21:16 +05:30
Mihir Kandoi
e84bf44e51 feat: set one supplier across every item in the supplier selection dialog
A Material Request where few items carry a default supplier meant picking the
same supplier row by row. A Supplier field above the table copies its value
into every row, leaving the exceptions to be corrected by hand.

Both pickers skip suppliers that are disabled or barred from Purchase Orders by
their scorecard standing.
2026-08-01 09:19:49 +05:30
Mihir Kandoi
f0bb70539d fix: warn about existing draft orders before the supplier selection creates more
Creating through the dialog calls the endpoint directly instead of going
through open_mapped_doc, so the draft link guard that every other Create action
runs never fired, and a repeated dialog quietly produced a second set of draft
orders for the same quantity.
2026-08-01 09:16:13 +05:30
Mihir Kandoi
8ffe5ba420 test: reject the same Material Request item twice in one supplier selection 2026-08-01 09:11:37 +05:30
Mihir Kandoi
99d56cc850 fix: reject the same Material Request item twice in one supplier selection
Each row was checked against the pending quantity on its own, so a payload that
listed one item under two suppliers passed both checks and ordered the pending
quantity twice. The dialog cannot produce that, a direct call to the endpoint
can.
2026-08-01 09:11:37 +05:30
Mihir Kandoi
21c6d10ad3 fix: escape item code and UOM in the supplier dialog errors
Desk renders a client side message as HTML, so an Item or UOM whose name holds
markup ran as markup in the buyer's session.
2026-08-01 09:11:37 +05:30
Mihir Kandoi
3856eaa35e fix: open the Purchase Order when the supplier selection creates only one
Naming a single order in a message and leaving the buyer to click it is a step
for nothing. The form opens directly when there is one order; the message stays
for the case it was meant for, several orders at once.
2026-08-01 09:02:05 +05:30
Mihir Kandoi
d233fdf198 test: reject a supplier selection without items 2026-08-01 09:00:12 +05:30
Mihir Kandoi
07445b3675 feat: order only the items ticked in the supplier selection dialog
Every row is ticked when the dialog opens, so the common case of ordering
everything is unchanged, and a buyer who wants a partial order unticks what
should wait. Creating with nothing ticked is rejected.
2026-08-01 09:00:12 +05:30
Mihir Kandoi
5a78e2290a fix: link the item and spell out the unit in the supplier dialog errors
A bare item code left the buyer to find the item themselves, and a bare number
gave no clue what the limit was counted in. Both messages now link the item and
state the pending quantity in bold with its UOM.
2026-08-01 08:57:04 +05:30
Mihir Kandoi
671c289303 test: alert when Required By falls back to today 2026-08-01 08:52:23 +05:30
Mihir Kandoi
53e09dfdd6 feat: alert when Required By falls back to today
Items whose requested date has passed silently got today as Required By, which
is a date the buyer never asked for. A toast now says so.
2026-08-01 08:52:23 +05:30
Mihir Kandoi
d0cae2eb9c feat: show the UOM alongside the quantity in the supplier selection dialog
The quantity is meaningless without the unit it is counted in, which the buyer
had to look up on the Material Request itself.
2026-08-01 08:52:23 +05:30
Mihir Kandoi
6f22551aae fix: list the Purchase Orders created per supplier instead of opening one
Opening one of several created orders hid the rest and moved the buyer off the
Material Request. The created orders are now reported the way Production Plan
reports its documents, as links in a message, and the form stays put.
2026-08-01 08:39:03 +05:30
Mihir Kandoi
15d10bbaf1 test: Required By on Purchase Orders created per supplier
Backdates the Material Request item so the mapper drops its schedule date, and
asserts the created order still saves with today as Required By.
2026-08-01 08:38:42 +05:30
Mihir Kandoi
d05bd80b1e fix: set Required By on Purchase Orders created per supplier
Mapping drops a schedule date that already passed, leaving the buyer to pick a
new one on the Purchase Order form. Nothing fills it in when the orders are
created straight from the supplier selection dialog, so a Material Request
whose required date has gone by failed to save with "Please enter the Required
By".

Items that lose their date now fall back to today, which is the earliest date a
Purchase Order raised today accepts.
2026-08-01 08:38:26 +05:30
Mihir Kandoi
09cfd1fe91 test: quantity handling in the supplier selection dialog
Asserts the requested quantity reaches the Purchase Order item and that rows
without a supplier, or with a quantity that is zero, negative or beyond the
pending quantity, are rejected.
2026-08-01 08:38:15 +05:30
Mihir Kandoi
da83370c5c feat: adjust the ordered quantity in the supplier selection dialog
The dialog prefilled the pending quantity of each Material Request item but
kept it read only, so ordering less than what was requested meant editing the
Purchase Order afterwards.

The quantity is now editable and is validated against the pending quantity of
its Material Request item, both in the dialog and on the server. The requested
quantity is handed to the mapper as the pending quantity of the source row, so
the existing mapping - including the subcontracting conversions - derives the
Purchase Order quantities from it unchanged.
2026-08-01 08:38:10 +05:30
Mihir Kandoi
65be201ed6 test: supplier selection when creating Purchase Orders from Material Request
Covers the default supplier lookup for pending items, the supplier passed
through to a single mapped order, the grouping of items into one order per
supplier, and the failure when an item is sent without a supplier.
2026-07-31 22:22:55 +05:30
Mihir Kandoi
e8df7b4a90 feat: select a supplier per item when creating Purchase Orders from Material Request
Creating a Purchase Order from a Material Request mapped every pending item
into a single order, leaving the buyer to split it by hand whenever the items
came from different vendors.

The Create action now reads the default supplier of each pending item (item,
item group, then brand defaults). When the items resolve to more than one
distinct supplier - including the case where only some of them have a default -
a dialog lists the items with their default supplier prefilled and editable.
Submitting it groups the items by the chosen supplier and creates one draft
Purchase Order per group.

When every item resolves to the same supplier the order is mapped straight
away with that supplier set, and when none of them has a default supplier the
previous behaviour is unchanged.
2026-07-31 22:22:49 +05:30
Mihir Kandoi
f4d70c2d60 test: fractional conversion factor survives Material Request to Purchase Order
Fails before the fix with 0.45 != 0.453592292 on a site with Float
Precision 2, and 0.454 on the default of 3.
2026-07-31 21:54:05 +05:30
Mihir Kandoi
269cc6ee3b fix: preserve UOM conversion factor precision in transactions
calculate_item_values rounds every Float field on an item row to the
site's Float Precision (3 by default), and conversion_factor was one of
them. The factor is a ratio, not a rate: UOM Conversion Factor.value is
stored at precision 9, and Material Request keeps the full value because
it has no currency field and so never runs the calculation.

Mapping a Material Request to a Purchase Order therefore truncated the
factor - 0.453592292 for Pound -> Kg became 0.454 - and stock_qty, which
is recomputed as qty * conversion_factor, drifted from the quantity that
was requested, leaving the Material Request unable to close.

Exclude conversion_factor from the rounded fields on the server and on
the client. Factors below the site precision would otherwise round to
zero outright.
2026-07-31 21:53:59 +05:30
R-Jayaraman
cde2963da1 test(purchase): add coverage for zero-qty return rejection 2026-07-31 13:31:10 +05:30
R-Jayaraman
b63066ed44 fix(purchase): reject purchase returns where every item has zero quantity
validate_returned_items() set items_returned=True whenever a row matched
a valid item from the original document, even if its qty was 0. This let
a Purchase Invoice, Purchase Receipt, or Subcontracting Receipt return be
submitted with every line at qty=0 - a no-op document with no stock or
financial effect that still consumed a document number and linked back
to the original transaction.

Scoped to the Purchase side only: items_returned now flips to True for
Purchase Invoice/Purchase Receipt/Subcontracting Receipt only when qty
(or received_qty) is actually negative, so an all-zero purchase return
correctly hits the existing "At least one item should be entered with
negative quantity" check. Sales Invoice, Delivery Note, and POS Invoice
are unchanged.

Also applies a corresponding check to the item_name-only fallback branch
(for rows without an item_code - Item Code is not mandatory on Purchase
Invoice Item), which previously bypassed this fix entirely and still set
items_returned=True unconditionally regardless of quantity. For that
branch specifically, only qty is checked (not received_qty): with no
linked Item there's no accepted/rejected split, so received_qty carries
no independent meaning and a qty=0 row must be rejected regardless of
its value.
2026-07-31 13:31:01 +05:30
nishkagosalia
136f92db04 fix: handling negative grand total 2026-07-29 14:31:33 +05:30
khushi8112
db7b7bb106 refactor: split make_depreciation_entry into public and internal helpers 2026-07-28 17:52:07 +05:30
Mohd Haris
06bfc23436 fix: prevent TimestampMismatchError resolving Dunning with multiple overdue installments
`get_linked_dunnings_as_per_state` joins Dunning to its Overdue Payment child
table without DISTINCT. When a Sales Invoice has more than one overdue
installment, its Dunning holds one Overdue Payment row per installment, so the
query returns the same Dunning name once per row.

`update_linked_dunnings` then loads that Dunning name into a separate document
object for each duplicate row and saves each one. The first save bumps the
`modified` timestamp, so the second (now stale) save fails with
`TimestampMismatchError` ("Document has been modified after you have opened
it"). The error is raised on the Dunning while the user is submitting a Payment
Entry, making it confusing, and payments for such invoices cannot be posted at
all.

Add DISTINCT so each linked Dunning is returned (and saved) exactly once.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-28 13:04:31 +05:30
574 changed files with 417263 additions and 167743 deletions

View File

@@ -170,6 +170,13 @@ audit of these fixes found four recurring mistakes:
- **Fabricated arithmetic** — `Sum(x) * Max(y)` where `y` varies within the group invents a
number no row ever had (and `Max` biases it upward) — poisonous when it feeds validation,
budgets, valuation, or GL/stock values. Fix per-row: `Sum(x * y)`.
- **Collation-dependent pick (text columns)** — `Max()`/`Min()` over text is a *sort*, and the two
engines sort text differently: MariaDB's `utf8mb4` collations fold case, PostgreSQL (as CI runs
it) orders by byte value. `MAX('abc', 'ABD')` is `ABD` on MariaDB and `abc` on PostgreSQL. So a
`Max()` over a text column that varies **in case** within its group is a live P2 divergence, not
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.
- **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

@@ -0,0 +1,51 @@
name: Download translations from Crowdin
on:
schedule:
- cron: "0 4 * * 1"
workflow_dispatch:
concurrency:
group: crowdin-download
cancel-in-progress: false
permissions:
contents: read
jobs:
download-translations:
name: Download translations into ${{ matrix.branch }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
branch: ["develop", "version-16-hotfix"]
steps:
- name: Checkout ${{ matrix.branch }}
uses: actions/checkout@v6
with:
ref: ${{ matrix.branch }}
fetch-depth: 0
persist-credentials: false
- name: Download translations and open PR
uses: crowdin/github-action@8f01d54f70f1713ee3f09d82c2bbb2daeac28689 # v2.17.1
with:
config: crowdin.yml
upload_sources: false
upload_translations: false
download_translations: true
crowdin_branch_name: "[frappe.erpnext] ${{ matrix.branch }}"
skip_ref_checkout: true
localization_branch_name: l10n_crowdin_${{ matrix.branch }}
create_pull_request: true
pull_request_base_branch_name: ${{ matrix.branch }}
commit_message: "fix: sync translations from crowdin"
pull_request_title: "fix: sync translations from crowdin (${{ matrix.branch }})"
pull_request_labels: "translation, skip-release-notes"
pull_request_reviewers: barredterra
env:
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }}
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}

View File

@@ -0,0 +1,54 @@
name: Upload main.pot to Crowdin
on:
push:
branches:
- develop
- version-16-hotfix
paths:
- "erpnext/locale/main.pot"
workflow_dispatch:
concurrency:
group: crowdin-upload-${{ github.ref_name }}
cancel-in-progress: true
permissions:
contents: read
jobs:
upload-sources:
name: Upload sources from ${{ github.ref_name }}
runs-on: ubuntu-latest
steps:
- name: Checkout ${{ github.ref_name }}
uses: actions/checkout@v6
- name: Restore Crowdin cache
uses: actions/cache/restore@v6
with:
path: .crowdin
key: crowdin-${{ github.ref_name }}
restore-keys: crowdin-${{ github.ref_name }}-
- name: Upload main.pot to Crowdin
uses: crowdin/github-action@8f01d54f70f1713ee3f09d82c2bbb2daeac28689 # v2.17.1
with:
config: crowdin.yml
upload_sources: true
upload_translations: false
download_translations: false
create_pull_request: false
crowdin_branch_name: "[frappe.erpnext] ${{ github.ref_name }}"
upload_sources_args: "--cache"
env:
CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }}
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
- name: Save Crowdin cache
uses: actions/cache/save@v6
if: always()
with:
path: .crowdin
key: crowdin-${{ github.ref_name }}-${{ github.run_id }}

View File

@@ -0,0 +1,45 @@
name: Notify Support on PR release
on:
issue_comment:
types: [created]
permissions: {}
jobs:
notify-support:
if: >-
github.event.issue.pull_request
&& github.event.comment.user.id == 28699486
&& contains(github.event.comment.body, 'This PR is included in version')
runs-on: ubuntu-latest
timeout-minutes: 2
steps:
- name: Notify support.frappe.io
env:
COMMENT_ID: ${{ github.event.comment.id }}
PR_NUMBER: ${{ github.event.issue.number }}
REPOSITORY: ${{ github.repository }}
SUPPORT_FRAPPE_AUTH: ${{ secrets.SUPPORT_FRAPPE_AUTH }}
run: |
payload="$(
jq -n \
--arg repository "$REPOSITORY" \
--argjson pr_number "$PR_NUMBER" \
--argjson comment_id "$COMMENT_ID" \
'{
repository: $repository,
pr_number: $pr_number,
comment_id: $comment_id
}'
)"
curl --fail-with-body \
--retry 3 \
--retry-all-errors \
--request POST \
--header "Authorization: $SUPPORT_FRAPPE_AUTH" \
--header "Content-Type: application/json" \
--data "$payload" \
"https://support.frappe.io/api/method/notify_pr_release"

View File

@@ -171,7 +171,30 @@ jobs:
update_to_version 16 3.14
echo "Updating to latest version"
git -C "apps/frappe" fetch --depth 1 upstream "${GITHUB_BASE_REF:-${GITHUB_REF##*/}}"
fallback_to_develop=0
if [ -n "${GITHUB_BASE_REF:-}" ]; then
frappe_ref="refs/heads/$GITHUB_BASE_REF"
fallback_to_develop=1
elif [ "${GITHUB_REF_TYPE:-}" = "branch" ]; then
frappe_ref="$GITHUB_REF"
fallback_to_develop=1
elif [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
frappe_ref="$GITHUB_REF"
else
echo "Unsupported GitHub ref type: '${GITHUB_REF_TYPE:-unset}'"
exit 1
fi
ls_remote_status=0
git -C "apps/frappe" ls-remote --exit-code upstream "$frappe_ref" >/dev/null \
|| ls_remote_status=$?
if [ "$ls_remote_status" -eq 2 ] && [ "$fallback_to_develop" -eq 1 ]; then
echo "frappe has no '$frappe_ref'; falling back to develop"
frappe_ref=refs/heads/develop
elif [ "$ls_remote_status" -ne 0 ]; then
exit "$ls_remote_status"
fi
git -C "apps/frappe" fetch --depth 1 upstream "$frappe_ref"
git -C "apps/frappe" checkout -q -f FETCH_HEAD
git -C "apps/erpnext" checkout -q -f "$GITHUB_SHA"

View File

@@ -22,4 +22,6 @@ jobs:
pull-requests: write
steps:
- uses: alyf-de/po-review-action@v1.1.0
- uses: alyf-de/po-review-action@5928f84d6bc9094f9ad6e2c5780f01c0044b800e # v1.1.1
with:
hidden-po-files: eo.po

View File

@@ -13,6 +13,7 @@ on:
- 'crowdin.yml'
- '.coderabbit.yml'
- '.mergify.yml'
- '**.po'
permissions:
contents: read

View File

@@ -13,6 +13,7 @@ on:
- 'crowdin.yml'
- '.coderabbit.yml'
- '.mergify.yml'
- '**.po'
schedule:
# Run everday at midnight UTC / 5:30 IST
- cron: "0 0 * * *"

File diff suppressed because one or more lines are too long

View File

@@ -91,3 +91,5 @@ pull_request_rules:
commit_message_format:
title: pr-title
body: pr-body
merge_queue:
queue_controls_comment: false

View File

@@ -7,6 +7,7 @@ erpnext/accounts/ @ruthra-kumar
erpnext/assets/ @khushi8112
erpnext/regional @ruthra-kumar
erpnext/selling @ruthra-kumar
banking/ @nikkothari22
erpnext/buying/ @rohitwaghchaure @mihir-kandoi
erpnext/maintenance/ @rohitwaghchaure @mihir-kandoi

View File

@@ -24,10 +24,10 @@
"cmdk": "^1.1.1",
"date-fns": "^4.1.0",
"dayjs": "^1.11.20",
"frappe-react-sdk": "^1.17.0",
"frappe-react-sdk": "^1.17.1",
"fuse.js": "^7.3.0",
"jotai": "^2.20.1",
"jotai-family": "^1.0.2",
"jotai": "^2.20.2",
"jotai-family": "^1.1.0",
"lodash.isplainobject": "^4.0.6",
"lucide-react": "^1.14.0",
"radix-ui": "^1.6.1",
@@ -39,7 +39,7 @@
"react-hook-form": "^7.75.0",
"react-hotkeys-hook": "^5.3.2",
"react-markdown": "^10.1.0",
"react-router": "^8.1.0",
"react-router": "^8.3.0",
"rehype-raw": "^7.0.0",
"remark-gfm": "^4.0.1",
"safe-expr-eval": "^1.0.4",
@@ -48,18 +48,18 @@
"tailwindcss": "^4.3.0",
"tw-animate-css": "^1.4.0",
"usehooks-ts": "^3.1.1",
"vite": "^8.0.16"
"vite": "^8.2.1"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@eslint/js": "^9.39.5",
"@types/node": "^25.3.0",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"eslint": "^9.39.1",
"eslint": "^10.8.1",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.3",
"globals": "^16.5.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.62.1"
"typescript-eslint": "^8.67.0"
}
}

View File

@@ -19,13 +19,22 @@ import {
import { cn } from "@/lib/utils"
import _ from "@/lib/translate"
import { selectedBankAccountAtom } from "./bankRecAtoms"
import { useFrappeGetDocList } from "frappe-react-sdk"
import ErrorBanner from "@/components/ui/error-banner"
const CompanySelector = ({ onChange }: { onChange?: (company: string) => void }) => {
const [open, setOpen] = useState(false)
const [searchQuery, setSearchQuery] = useState("")
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const options = window.frappe?.boot?.docs?.filter((doc: Record<string, any>) => doc.doctype === ":Company").map((company: Record<string, any>) => company.name) || []
const { data: companies, error } = useFrappeGetDocList("Company", {
limit: 0,
fields: ["name"],
}, 'company_list', {
revalidateOnFocus: false,
revalidateOnReconnect: false,
})
const options = companies?.map((company: { name: string }) => company.name) || []
const setSelectedCompany = useSetAtom(selectedCompanyAtom)
const setSelectedBankAccount = useSetAtom(selectedBankAccountAtom)
@@ -42,6 +51,10 @@ const CompanySelector = ({ onChange }: { onChange?: (company: string) => void })
}
}
if (error) {
return <ErrorBanner error={error} />
}
return (<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button

View File

@@ -1,7 +1,9 @@
import { useAtomValue } from "jotai"
import { atomWithStorage } from "jotai/utils"
export const selectedCompanyAtom = atomWithStorage<string>('bank-rec-selected-company', window.frappe?.boot?.user?.defaults?.company || '')
export const selectedCompanyAtom = atomWithStorage<string>('bank-rec-selected-company', window.frappe?.boot?.user?.defaults?.company || '', undefined, {
getOnInit: true,
})
export const useCurrentCompany = () => {
const selectedCompany = useAtomValue(selectedCompanyAtom)

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,5 @@
preserve_hierarchy: true
files:
- source: /erpnext/locale/main.pot
translation: /erpnext/locale/%two_letters_code%.po
pull_request_title: "fix: sync translations from crowdin"
pull_request_labels:
- translation
- skip-release-notes
pull_request_reviewers:
- barredterra # change to your GitHub username if you copied this file
commit_message: "fix: %language% translations"
append_commit_message: false
languages_mapping:
two_letters_code:
pt-BR: pt_BR
zh-CN: zh
zh-TW: zh_TW

View File

@@ -6,88 +6,148 @@ from erpnext.accounts.doctype.payment_entry.payment_entry import (
get_outstanding_reference_documents,
get_payment_entry,
)
from erpnext.utilities.bulk_transaction import transaction_processing
@frappe.whitelist(methods=["POST"])
def create_payment_entries(
grouped_invoices: str | list | None = None,
ungrouped_invoices: str | list | None = None,
):
def create_payment_entries(invoices: str | list | None = None):
"""Create draft Payment Entries from AP report invoice selection."""
frappe.has_permission("Payment Entry", "create", throw=True)
grouped_invoices = [d for d in frappe.parse_json(grouped_invoices or "[]") if d.get("voucher_no")]
ungrouped_invoices = [d for d in frappe.parse_json(ungrouped_invoices or "[]") if d.get("voucher_no")]
if not grouped_invoices and not ungrouped_invoices:
names = [d["voucher_no"] for d in frappe.parse_json(invoices or "[]") if d.get("voucher_no")]
if not names:
frappe.throw(_("No Purchase Invoices selected"))
if ungrouped_invoices:
data = [{"name": d["voucher_no"]} for d in ungrouped_invoices]
transaction_processing(data, "Purchase Invoice", "Payment Entry")
payable, excluded = _partition_payable_invoices(names)
if not payable:
frappe.throw(_("None of the selected invoices are payable"))
if grouped_invoices:
groups = {}
for d in grouped_invoices:
key = (d["supplier"], d["party_account"])
groups.setdefault(
key, {"supplier": d["supplier"], "party_account": d["party_account"], "vouchers": []}
)["vouchers"].append(d["voucher_no"])
# invoices sharing a (supplier, payable account) are combined into one Payment Entry
groups = {}
for d in payable:
key = (d["supplier"], d["party_account"])
groups.setdefault(
key, {"supplier": d["supplier"], "party_account": d["party_account"], "vouchers": []}
)["vouchers"].append(d["voucher_no"])
frappe.msgprint(
_("Started a background job to create {0} Grouped Payment Entries").format(len(groups))
)
frappe.enqueue(
make_grouped_payment_entries,
queue="long",
timeout=1500,
groups=list(groups.values()),
)
def make_grouped_payment_entries(groups):
created, failed = 0, 0
for group in groups:
supplier = group["supplier"]
try:
frappe.db.savepoint("bulk_pe")
pe = _build_grouped_payment_entry(supplier, group["party_account"], group["vouchers"])
if not pe:
frappe.db.rollback(save_point="bulk_pe")
failed += 1
frappe.log_error(
title=_("Bulk Payment Entry skipped for {0}").format(supplier),
message=_(
"No outstanding invoices found for the selected vouchers in account {0}"
).format(group["party_account"]),
)
continue
pe.flags.ignore_validate = True
pe.set_title_field()
pe.insert(ignore_mandatory=True)
for group in groups.values():
if _create_payment_entry(group):
created += 1
except Exception:
frappe.db.rollback(save_point="bulk_pe")
else:
failed += 1
frappe.log_error(title=_("Bulk Payment Entry creation failed for {0}").format(supplier))
message = _("Created {0} draft Grouped Payment Entries").format(created)
message = _("Created {0} draft Payment Entries").format(created)
if excluded:
message += "" + _("{0} excluded (not payable)").format(len(excluded))
if failed:
message += "" + _("{0} skipped (see Error Log)").format(failed)
message += "" + _("{0} failed (see Error Log)").format(failed)
frappe.msgprint(message, title=_("Bulk Payment Entries"), indicator="green")
frappe.publish_realtime(
"msgprint",
{"message": message, "title": _("Bulk Payment Entries"), "indicator": "green"},
user=frappe.session.user,
after_commit=True,
@frappe.whitelist()
def get_payable_invoices(invoices: str | list | None = None):
"""Return the live payable subset of the selected invoices for the report dialog."""
frappe.has_permission("Payment Entry", "create", throw=True)
names = [d["voucher_no"] for d in frappe.parse_json(invoices or "[]") if d.get("voucher_no")]
payable, excluded = _partition_payable_invoices(names)
currency = None
if payable:
company = frappe.get_cached_value("Purchase Invoice", payable[0]["voucher_no"], "company")
currency = frappe.get_cached_value("Company", company, "default_currency")
return {"payable": payable, "excluded": excluded, "currency": currency}
def _partition_payable_invoices(names):
"""Split submitted Purchase Invoices into payable ones and excluded ones (with reason).
Returns are debit notes, internal transfers are inter-company, and non-positive
outstanding means already settled — none are valid targets for a supplier payment.
"""
if not names:
return [], []
rows = frappe.get_list(
"Purchase Invoice",
filters={"name": ["in", names], "docstatus": 1},
fields=[
"name",
"supplier",
"credit_to",
"outstanding_amount",
"conversion_rate",
"is_return",
"is_internal_supplier",
],
limit_page_length=0,
)
payable, excluded = [], []
for r in rows:
if r.is_return:
excluded.append({"voucher_no": r.name, "reason": _("Debit Note")})
elif r.is_internal_supplier:
excluded.append({"voucher_no": r.name, "reason": _("Internal Transfer")})
elif flt(r.outstanding_amount) <= 0:
excluded.append({"voucher_no": r.name, "reason": _("Already Paid")})
else:
payable.append(
{
"voucher_no": r.name,
"supplier": r.supplier,
"party_account": r.credit_to,
"outstanding": flt(r.outstanding_amount) * flt(r.conversion_rate or 1),
}
)
# names not returned were cancelled/deleted or no longer readable after the report loaded
found = {r.name for r in rows}
for name in names:
if name not in found:
excluded.append({"voucher_no": name, "reason": _("Not available")})
return payable, excluded
def _create_payment_entry(group):
supplier = group["supplier"]
try:
frappe.db.savepoint("bulk_pe")
if len(group["vouchers"]) == 1:
pe = _build_single_payment_entry(group["vouchers"][0])
else:
pe = _build_grouped_payment_entry(supplier, group["party_account"], group["vouchers"])
if not pe:
frappe.db.rollback(save_point="bulk_pe")
frappe.log_error(
title=_("Bulk Payment Entry skipped for {0}").format(supplier),
message=_("No outstanding amount for the selected invoice(s)."),
)
return False
pe.flags.ignore_validate = True
pe.set_title_field()
pe.insert(ignore_mandatory=True)
return True
except Exception:
frappe.db.rollback(save_point="bulk_pe")
frappe.log_error(title=_("Bulk Payment Entry creation failed for {0}").format(supplier))
return False
def _build_single_payment_entry(name):
pe = get_payment_entry("Purchase Invoice", name)
# guard against a stale report row: nothing to allocate means the invoice is already settled
if not pe.references or not any(flt(r.allocated_amount) for r in pe.references):
return None
return pe
def _build_grouped_payment_entry(supplier, party_account, names):
name_set = set(names)
pe = get_payment_entry("Purchase Invoice", names[0])
pe.set("references", [])
@@ -101,8 +161,9 @@ def _build_grouped_payment_entry(supplier, party_account, names):
}
)
# get_negative_outstanding_invoices ignores the vouchers filter, so bound refs to the selection
for r in refs:
if r.voucher_type != "Purchase Invoice":
if r.voucher_type != "Purchase Invoice" or r.voucher_no not in name_set:
continue
pe.append(
"references",

View File

@@ -71,4 +71,6 @@ def get_shipping_address(company: str, address: str | None = None):
if address:
address_as_dict = address[0]
name, address_template = get_address_templates(address_as_dict)
return address_as_dict.get("name"), frappe.render_template(address_template, address_as_dict)
return address_as_dict.get("name"), frappe.render_template(
address_template, address_as_dict, restrict_globals=True
)

View File

@@ -203,7 +203,7 @@
"idx": 1,
"is_tree": 1,
"links": [],
"modified": "2026-04-14 18:14:42.202065",
"modified": "2026-08-21 23:11:37.851001",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Account",
@@ -264,6 +264,46 @@
{
"role": "HR Manager",
"select": 1
},
{
"role": "Delivery Manager",
"select": 1
},
{
"role": "Delivery User",
"select": 1
},
{
"role": "Maintenance Manager",
"select": 1
},
{
"role": "Maintenance User",
"select": 1
},
{
"role": "Manufacturing Manager",
"select": 1
},
{
"role": "Manufacturing User",
"select": 1
},
{
"role": "Purchase Master Manager",
"select": 1
},
{
"role": "Quality Manager",
"select": 1
},
{
"role": "Sales Master Manager",
"select": 1
},
{
"role": "Stock Manager",
"select": 1
}
],
"row_format": "Dynamic",

View File

@@ -727,9 +727,12 @@ def get_company_default_account_fields():
"stock_delivered_but_not_billed": "Stock Delivered But Not Billed Account",
"stock_adjustment_account": "Stock Adjustment Account",
"write_off_account": "Write Off Account",
"bank_charges_account": "Bank Charges Account",
"default_discount_account": "Default Payment Discount Account",
"unrealized_profit_loss_account": "Unrealized Profit / Loss Account",
"exchange_gain_loss_account": "Exchange Gain / Loss Account",
"exchange_gain_account": "Exchange Gain Account",
"exchange_loss_account": "Exchange Loss Account",
"unrealized_exchange_gain_loss_account": "Unrealized Exchange Gain / Loss Account",
"round_off_account": "Round Off Account",
"default_deferred_revenue_account": "Default Deferred Revenue Account",

View File

@@ -179,6 +179,9 @@
},
"Impairment": {
"account_category": "Operating Expenses"
},
"Exchange Loss": {
"account_category": "Operating Expenses"
}
},
"root_type": "Expense"
@@ -196,6 +199,10 @@
"account_type": "Income Account"
},
"Indirect Income": {
"Exchange Gain": {
"account_type": "Income Account",
"account_category": "Other Operating Income"
},
"account_type": "Income Account",
"is_group": 1
},

View File

@@ -138,6 +138,7 @@ def get():
_("Gain/Loss on Asset Disposal"): {"account_category": "Other Operating Income"},
_("Impairment"): {"account_category": "Operating Expenses"},
_("Tax Expense"): {"account_category": "Tax Expense"},
_("Exchange Loss"): {"account_category": "Operating Expenses"},
},
"root_type": "Expense",
},
@@ -149,6 +150,7 @@ def get():
_("Indirect Income"): {
_("Interest Income"): {"account_category": "Investment Income"},
_("Interest on Fixed Deposits"): {"account_category": "Investment Income"},
_("Exchange Gain"): {"account_category": "Other Operating Income"},
"is_group": 1,
},
"root_type": "Income",

View File

@@ -233,6 +233,7 @@ def get():
},
_("Impairment"): {"account_number": "5224", "account_category": "Operating Expenses"},
_("Tax Expense"): {"account_number": "5225", "account_category": "Tax Expense"},
_("Exchange Loss"): {"account_number": "5226", "account_category": "Operating Expenses"},
"account_number": "5200",
},
"root_type": "Expense",
@@ -250,6 +251,10 @@ def get():
"account_number": "4220",
"account_category": "Investment Income",
},
_("Exchange Gain"): {
"account_number": "4230",
"account_category": "Other Operating Income",
},
"is_group": 1,
"account_number": "4200",
},

View File

@@ -16,6 +16,8 @@ frappe.ui.form.on("Accounting Dimension", {
return {
filters: {
name: ["not in", invalid_doctypes],
istable: 0,
issingle: 0,
},
};
});

View File

@@ -60,6 +60,14 @@ class AccountingDimension(Document):
msg = _("Not allowed to create accounting dimension for {0}").format(self.document_type)
frappe.throw(msg)
meta = frappe.get_meta(self.document_type)
if meta.istable or meta.issingle:
frappe.throw(
_(
"{0} cannot be used as an accounting dimension as it is not a standalone document type."
).format(frappe.bold(self.document_type))
)
exists = frappe.db.get_value("Accounting Dimension", {"document_type": self.document_type}, ["name"])
if exists and self.is_new():

View File

@@ -51,6 +51,23 @@ class TestAccountingDimension(ERPNextTestSuite):
self.assertEqual(gle.get("department"), "_Test Department - _TC")
self.assertEqual(gle1.get("department"), "_Test Department - _TC")
def test_child_table_not_allowed_as_dimension(self):
dimension = frappe.get_doc({"doctype": "Accounting Dimension", "document_type": "Sales Team"})
self.assertRaises(frappe.ValidationError, dimension.insert)
def test_single_doctype_not_allowed_as_dimension(self):
dimension = frappe.get_doc({"doctype": "Accounting Dimension", "document_type": "Selling Settings"})
self.assertRaises(frappe.ValidationError, dimension.insert)
def test_non_scalar_dimension_value_skipped_in_gl_dict(self):
si = create_sales_invoice(do_not_save=1)
si.department = "_Test Department - _TC"
self.assertEqual(si.get_gl_dict({}).get("department"), "_Test Department - _TC")
si.department = ["_Test Department - _TC"]
self.assertNotIn("department", si.get_gl_dict({}))
def test_mandatory(self):
location = frappe.get_doc("Accounting Dimension", "Location")
location.dimension_defaults[0].mandatory_for_bs = True

View File

@@ -95,13 +95,14 @@
"column_break_25",
"reports_tab",
"remarks_section",
"general_ledger_remarks_length",
"receivable_payable_remarks_length",
"disable_include_dimensions",
"column_break_lvjk",
"general_ledger_remarks_length",
"accounts_receivable_payable_tuning_section",
"receivable_payable_fetch_method",
"default_ageing_range",
"column_break_ntmi",
"receivable_payable_remarks_length",
"legacy_section",
"ignore_is_opening_check_for_reporting",
"tab_break_dpet",
@@ -199,10 +200,12 @@
},
{
"default": "1",
"description": "System will use the latest saved Currency Exchange rate on or before the transaction date, however old it is. <br>\nUncheck to ignore rates older than Stale Days and fetch a fresh rate from the exchange rate provider instead.",
"fieldname": "allow_stale",
"fieldtype": "Check",
"in_list_view": 1,
"label": "Allow Stale Exchange Rates"
"label": "Allow Stale Exchange Rates",
"show_description_on_click": 1
},
{
"default": "1",
@@ -278,10 +281,10 @@
},
{
"default": "0",
"description": "Block a new Sales Invoice when the customer's overdue amount exceeds the Overdue Limit set on the customer.",
"description": "Enabling this option prevents the creation of a new Sales Invoice when the customer has an overdue limit set and their outstanding overdue amount exceeds that limit.",
"fieldname": "enable_overdue_billing_threshold",
"fieldtype": "Check",
"label": "Restrict Customer Over Billing"
"label": "Prevent Sales Invoice when Customer is Overdue"
},
{
"depends_on": "eval:doc.enable_overdue_billing_threshold",
@@ -475,7 +478,7 @@
{
"fieldname": "remarks_section",
"fieldtype": "Section Break",
"label": "Remarks Column Length"
"label": "General Ledger Report"
},
{
"default": "0",
@@ -549,7 +552,7 @@
{
"fieldname": "accounts_receivable_payable_tuning_section",
"fieldtype": "Section Break",
"label": "Accounts Receivable / Payable Tuning"
"label": "Accounts Receivable / Payable Report"
},
{
"fieldname": "legacy_section",
@@ -788,6 +791,12 @@
"fieldname": "book_stock_expense_gl_entries",
"fieldtype": "Check",
"label": "Book Stock Expense GL Entries"
},
{
"default": "0",
"fieldname": "disable_include_dimensions",
"fieldtype": "Check",
"label": "Disable \"Consider Accounting Dimension\" Filter"
}
],
"grid_page_length": 50,
@@ -796,7 +805,7 @@
"index_web_pages_for_search": 1,
"issingle": 1,
"links": [],
"modified": "2026-07-15 17:00:00.000000",
"modified": "2026-08-14 15:26:49.070889",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Accounts Settings",

View File

@@ -72,6 +72,7 @@ class AccountsSettings(Document):
default_ageing_range: DF.Data | None
delete_linked_ledger_entries: DF.Check
determine_address_tax_category_from: DF.Literal["Billing Address", "Shipping Address"]
disable_include_dimensions: DF.Check
enable_accounting_dimensions: DF.Check
enable_common_party_accounting: DF.Check
enable_discounts_and_margin: DF.Check
@@ -203,8 +204,8 @@ class AccountsSettings(Document):
if self.add_taxes_from_item_tax_template and self.add_taxes_from_taxes_and_charges_template:
frappe.throw(
_("You cannot enable both the settings '{0}' and '{1}'.").format(
frappe.bold(_(self.meta.get_label("add_taxes_from_item_tax_template"))),
frappe.bold(_(self.meta.get_label("add_taxes_from_taxes_and_charges_template"))),
frappe.bold(self.meta.get_translated_label("add_taxes_from_item_tax_template")),
frappe.bold(self.meta.get_translated_label("add_taxes_from_taxes_and_charges_template")),
),
title=_("Auto Tax Settings Error"),
)

View File

@@ -101,7 +101,7 @@
}
],
"links": [],
"modified": "2024-03-27 13:06:36.896195",
"modified": "2026-08-21 23:11:39.423431",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Bank",
@@ -118,11 +118,20 @@
"role": "System Manager",
"share": 1,
"write": 1
},
{
"role": "Accounts Manager",
"select": 1
},
{
"role": "Accounts User",
"select": 1
}
],
"quick_entry": 1,
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"track_changes": 1
}
}

View File

@@ -269,7 +269,7 @@
"link_fieldname": "default_bank_account"
}
],
"modified": "2026-04-11 19:46:27.609994",
"modified": "2026-08-21 23:11:39.585456",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Bank Account",
@@ -299,6 +299,22 @@
"role": "Accounts User",
"share": 1,
"write": 1
},
{
"role": "Purchase Manager",
"select": 1
},
{
"role": "Purchase Master Manager",
"select": 1
},
{
"role": "Sales Master Manager",
"select": 1
},
{
"role": "Sales User",
"select": 1
}
],
"row_format": "Dynamic",

View File

@@ -166,9 +166,10 @@ def get_transaction_reference(txn_data: dict) -> str:
).strip()
@frappe.whitelist()
@frappe.whitelist(methods=["POST"])
def convert_mt940_to_csv(data_import: str, mt940_file_path: str):
doc = frappe.get_doc("Bank Statement Import", data_import)
doc.check_permission("write")
_file_doc, content = get_file(mt940_file_path)
@@ -235,26 +236,30 @@ def convert_mt940_to_csv(data_import: str, mt940_file_path: str):
def get_preview_from_template(
data_import: str, import_file: str | None = None, google_sheets_url: str | None = None
):
return frappe.get_doc("Bank Statement Import", data_import).get_preview_from_template(
import_file, google_sheets_url
)
bsi = frappe.get_doc("Bank Statement Import", data_import)
bsi.check_permission()
return bsi.get_preview_from_template(import_file, google_sheets_url)
@frappe.whitelist()
def form_start_import(data_import: str):
job_id = frappe.get_doc("Bank Statement Import", data_import).start_import()
return job_id is not None
bsi = frappe.get_doc("Bank Statement Import", data_import)
bsi.check_permission("write")
return bsi.start_import()
@frappe.whitelist()
def download_errored_template(data_import_name: str):
data_import = frappe.get_doc("Bank Statement Import", data_import_name)
data_import.check_permission()
data_import.export_errored_rows()
@frappe.whitelist()
def download_import_log(data_import_name: str):
return frappe.get_doc("Bank Statement Import", data_import_name).download_import_log()
bsi = frappe.get_doc("Bank Statement Import", data_import_name)
bsi.check_permission()
return bsi.download_import_log()
def is_mt940_format(content: str) -> bool:
@@ -393,6 +398,7 @@ def get_import_status(docname: str):
import_status = {}
data_import = frappe.get_doc("Bank Statement Import", docname)
data_import.check_permission()
import_status["status"] = data_import.status
logs = frappe.get_all(

View File

@@ -110,18 +110,6 @@ frappe.ui.form.on("Chart of Accounts Importer", {
args: {
company: frm.doc.company,
},
callback: function (r) {
if (r.message === false) {
frm.set_value("company", "");
frappe.throw(
__(
"Transactions against the Company already exist! Chart of Accounts can only be imported for a Company with no transactions."
)
);
} else {
frm.trigger("refresh");
}
},
});
}
},

View File

@@ -70,7 +70,13 @@ def validate_company(company: str):
frappe.throw(msg, title=_("Wrong Company"))
if frappe.db.get_all("GL Entry", {"company": company}, "name", limit=1):
return False
frappe.throw(
_(
"Transactions against the Company already exist! Chart of Accounts can only be imported for a Company with no transactions."
)
)
validate_user_perms(company)
@frappe.whitelist()
@@ -79,16 +85,22 @@ def import_coa(file_name: str, company: str):
# delete existing data for accounts
frappe.has_permission("Company", "write", company, throw=True)
unset_existing_data(company)
# create accounts
file_doc, extension = get_file(file_name)
validate_accounts(file_doc, extension)
if extension == "csv":
data = generate_data_from_csv(file_doc)
else:
data = generate_data_from_excel(file_doc, extension)
validate_columns(data)
validate_company(company)
unset_existing_data(company)
frappe.local.flags.ignore_root_company_validation = True
forest = build_forest(data)
create_charts(company, custom_chart=forest, from_coa_importer=True)
@@ -453,7 +465,6 @@ def get_mandatory_account_types():
def unset_existing_data(company):
# remove accounts data from company
fieldnames = get_linked_fields("Account").get("Company", {}).get("fieldname", [])
linked = [{"fieldname": name} for name in fieldnames]
update_values = {d.get("fieldname"): "" for d in linked}
@@ -463,13 +474,30 @@ def unset_existing_data(company):
# remove accounts data from various doctypes
for doctype in [
"Account",
"Sales Taxes and Charges Template",
"Purchase Taxes and Charges Template",
"Party Account",
"Mode of Payment Account",
"Tax Withholding Account",
"Sales Taxes and Charges Template",
"Purchase Taxes and Charges Template",
]:
frappe.get_query(doctype, delete=True, filters={"company": company}, ignore_permissions=False).run()
frappe.get_query(doctype, delete=True, filters={"company": company}).run()
def validate_user_perms(company):
# User Permission Check for Account Deletion
company_accounts_count = frappe.get_query(
"Account", fields=[{"COUNT": "name"}], filters={"company": company}
).run()[0][0]
company_accounts_user_has_access_to = frappe.get_query(
"Account", fields=[{"COUNT": "name"}], filters={"company": company}, ignore_permissions=False
).run()[0][0]
if company_accounts_count != company_accounts_user_has_access_to:
frappe.throw(
_("Accounts cannot be removed, as user doesn't have access to all the accounts of {0}").format(
frappe.bold(company)
)
)
def set_default_accounts(company):

View File

@@ -126,7 +126,7 @@
"idx": 1,
"is_tree": 1,
"links": [],
"modified": "2026-04-14 18:15:27.367298",
"modified": "2026-08-21 23:11:40.799391",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Cost Center",
@@ -181,6 +181,54 @@
{
"role": "HR Manager",
"select": 1
},
{
"role": "Delivery Manager",
"select": 1
},
{
"role": "Delivery User",
"select": 1
},
{
"role": "Maintenance Manager",
"select": 1
},
{
"role": "Maintenance User",
"select": 1
},
{
"role": "Manufacturing Manager",
"select": 1
},
{
"role": "Manufacturing User",
"select": 1
},
{
"role": "Projects Manager",
"select": 1
},
{
"role": "Projects User",
"select": 1
},
{
"role": "Purchase Master Manager",
"select": 1
},
{
"role": "Quality Manager",
"select": 1
},
{
"role": "Sales Master Manager",
"select": 1
},
{
"role": "Stock Manager",
"select": 1
}
],
"row_format": "Dynamic",

View File

@@ -125,7 +125,7 @@
}
],
"links": [],
"modified": "2024-11-19 16:35:11.836441",
"modified": "2026-08-21 23:11:41.010871",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Coupon Code",
@@ -179,11 +179,20 @@
"role": "Website Manager",
"share": 1,
"write": 1
},
{
"role": "Maintenance Manager",
"select": 1
},
{
"role": "Maintenance User",
"select": 1
}
],
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"title_field": "coupon_name",
"track_changes": 1
}
}

View File

@@ -275,6 +275,7 @@ def get_linked_dunnings_as_per_state(sales_invoice, state):
.join(overdue_payment)
.on(overdue_payment.parent == dunning.name)
.select(dunning.name)
.distinct()
.where(
(dunning.status == state)
& (dunning.docstatus != 2)

View File

@@ -123,6 +123,41 @@ class TestDunning(ERPNextTestSuite):
self.assertEqual(sales_invoice.status, "Overdue")
self.assertEqual(dunning.status, "Unresolved")
def test_payment_against_invoice_with_multiple_overdue_installments_in_dunning(self):
"""
When an invoice has more than one overdue installment, its Dunning holds one
Overdue Payment row per installment. Submitting a Payment Entry for the invoice
must resolve the Dunning without raising a TimestampMismatchError caused by the
same Dunning being loaded and saved more than once.
"""
create_payment_terms_template_for_dunning()
# Post far enough in the past that BOTH installments (5 and 10 credit days) are overdue.
sales_invoice = create_sales_invoice_against_cost_center(
posting_date=add_days(today(), -15),
qty=1,
rate=100,
do_not_submit=True,
)
sales_invoice.payment_terms_template = "_Test 50-50 for Dunning"
sales_invoice.submit()
dunning = create_dunning_from_sales_invoice(sales_invoice.name)
# Two overdue installments -> two overdue payment rows for the same invoice.
self.assertEqual(len(dunning.overdue_payments), 2)
dunning.submit()
self.assertEqual(dunning.status, "Unresolved")
# Pay the invoice in full. This previously raised TimestampMismatchError on the Dunning.
pe = get_payment_entry("Sales Invoice", sales_invoice.name)
pe.reference_no, pe.reference_date = "3", nowdate()
pe.insert()
pe.submit()
sales_invoice.reload()
dunning.reload()
self.assertEqual(sales_invoice.outstanding_amount, 0)
self.assertEqual(dunning.status, "Resolved")
def test_dunning_resolution_from_credit_note(self):
"""
Test that dunning is resolved when a credit note is issued against the original invoice.

View File

@@ -20,7 +20,7 @@
],
"icon": "fa fa-book",
"links": [],
"modified": "2024-03-27 13:09:44.514241",
"modified": "2026-08-21 23:11:42.386104",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Finance Book",
@@ -55,13 +55,26 @@
"report": 1,
"role": "Auditor",
"share": 1
},
{
"role": "HR Manager",
"select": 1
},
{
"role": "Manufacturing Manager",
"select": 1
},
{
"role": "Quality Manager",
"select": 1
}
],
"quick_entry": 1,
"row_format": "Dynamic",
"search_fields": "finance_book_name",
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"track_changes": 1,
"track_seen": 1
}
}

View File

@@ -163,7 +163,7 @@ function show_accounts_tree(template_rows, has_selection) {
fieldname: "company",
fieldtype: "Link",
options: "Company",
label: "Company",
label: __("Company"),
reqd: 1,
default: frappe.defaults.get_user_default("Company"),
onchange: () => {
@@ -176,7 +176,7 @@ function show_accounts_tree(template_rows, has_selection) {
fieldname: "view_type",
fieldtype: "Select",
options: ["Missing Accounts", "Filtered Accounts"],
label: "View",
label: __("View"),
default: has_selection ? "Filtered Accounts" : "Missing Accounts",
reqd: 1,
onchange: () => {
@@ -192,10 +192,10 @@ function show_accounts_tree(template_rows, has_selection) {
{
fieldname: "tip",
fieldtype: "HTML",
label: "Tip",
label: __("Tip"),
options: `
<div class="alert alert-success" role="alert">
Tip: Select report lines to view their accounts
${__("Tip: Select report lines to view their accounts")}
</div>
`,
depends_on: has_selection ? "eval: false" : "eval: true",
@@ -203,7 +203,7 @@ function show_accounts_tree(template_rows, has_selection) {
{
fieldname: "tree_area",
fieldtype: "HTML",
label: "Chart of Accounts",
label: __("Chart of Accounts"),
read_only: 1,
depends_on: "eval: doc.company",
},
@@ -288,14 +288,14 @@ function update_formula_label(frm, data_source) {
if (!field) return;
const labels = {
"Account Data": "Account Filter",
"Custom API": "API Method Path",
"Account Data": __("Account Filter"),
"Custom API": __("API Method Path"),
};
grid.update_docfield_property(
"calculation_formula",
"label",
labels[data_source] || "Calculation Formula"
labels[data_source] || __("Calculation Formula")
);
}

View File

@@ -12,13 +12,21 @@ from frappe import _
from frappe.database.operator_map import OPERATOR_MAP
def get_formula_field_label(data_source: str) -> str:
# Must mirror the `labels` map in financial_report_template.js (update_formula_label),
labels = {
"Account Data": _("Account Filter"),
"Custom API": _("API Method Path"),
}
return labels.get(data_source, _("Calculation Formula"))
@dataclass
class ValidationIssue:
"""Represents a single validation issue"""
message: str
row_idx: int | None = None
field: str | None = None
details: dict[str, Any] = None
def __post_init__(self):
@@ -26,10 +34,9 @@ class ValidationIssue:
self.details = {}
def __str__(self) -> str:
prefix = f"Row {self.row_idx}: " if self.row_idx else ""
field_info = f"[{self.field}] " if self.field else ""
message = f"{prefix}{field_info}{self.message}"
return _(message)
if self.row_idx:
return _("Row {0}: {1}", context="Financial Report Template").format(self.row_idx, self.message)
return self.message
@dataclass
@@ -131,7 +138,9 @@ class TemplateStructureValidator(Validator):
if not re.match(r"^[A-Za-z][A-Za-z0-9_-]*$", ref_code):
result.add_error(
ValidationIssue(
message=f"Invalid line reference format: '{ref_code}'. Must start with letter and contain only letters, numbers, underscores, and hyphens",
message=_(
"Invalid line reference format: '{0}'. Must start with letter and contain only letters, numbers, underscores, and hyphens"
).format(ref_code),
row_idx=row.idx,
)
)
@@ -140,7 +149,7 @@ class TemplateStructureValidator(Validator):
if ref_code in used_codes:
result.add_error(
ValidationIssue(
message=f"Duplicate line reference: '{ref_code}'",
message=_("Duplicate line reference: '{0}'").format(ref_code),
row_idx=row.idx,
)
)
@@ -156,7 +165,7 @@ class TemplateStructureValidator(Validator):
if row.data_source == "Account Data" and not row.balance_type:
result.add_error(
ValidationIssue(
message="Balance Type is required for Account Data",
message=_("Balance Type is required for Account Data"),
row_idx=row.idx,
)
)
@@ -166,7 +175,9 @@ class TemplateStructureValidator(Validator):
if not row.calculation_formula:
result.add_error(
ValidationIssue(
message=f"Formula is required for {row.data_source}",
message=_("{0} is required for {1}").format(
get_formula_field_label(row.data_source), row.data_source
),
row_idx=row.idx,
)
)
@@ -223,7 +234,7 @@ class DependencyValidator(Validator):
cycle = [*path[cycle_start:], node]
result.add_error(
ValidationIssue(
message=f"Circular dependency detected: {''.join(cycle)}",
message=_("Circular dependency detected: {0}").format("".join(cycle)),
)
)
return
@@ -255,7 +266,7 @@ class DependencyValidator(Validator):
row_idx = self._get_row_idx(ref_code)
result.add_error(
ValidationIssue(
message=f"Line References undefined in Formula: {', '.join(undefined)}",
message=_("Line References undefined in Formula: {0}").format(", ".join(undefined)),
row_idx=row_idx,
)
)
@@ -285,9 +296,10 @@ class CalculationFormulaValidator(Validator):
if not row.calculation_formula:
result.add_error(
ValidationIssue(
message="Formula is required for Calculated Amount",
message=_("{0} is required for Calculated Amount").format(
get_formula_field_label(row.data_source)
),
row_idx=row.idx,
field="Formula",
)
)
return result
@@ -299,7 +311,7 @@ class CalculationFormulaValidator(Validator):
if not self._are_parentheses_balanced(formula):
result.add_error(
ValidationIssue(
message="Formula has unbalanced parentheses",
message=_("Formula has unbalanced parentheses"),
row_idx=row.idx,
)
)
@@ -311,7 +323,7 @@ class CalculationFormulaValidator(Validator):
if row.reference_code and row.reference_code in refs:
result.add_error(
ValidationIssue(
message=f"Formula references itself ('{row.reference_code}')",
message=_("Formula references itself ('{0}')").format(row.reference_code),
row_idx=row.idx,
)
)
@@ -321,7 +333,7 @@ class CalculationFormulaValidator(Validator):
if undefined:
result.add_error(
ValidationIssue(
message=f"Formula references undefined codes: {', '.join(undefined)}",
message=_("Formula references undefined codes: {0}").format(", ".join(undefined)),
row_idx=row.idx,
)
)
@@ -331,7 +343,7 @@ class CalculationFormulaValidator(Validator):
if eval_error:
result.add_error(
ValidationIssue(
message=f"Formula evaluation error: {eval_error}",
message=_("Formula evaluation error: {0}").format(eval_error),
row_idx=row.idx,
)
)
@@ -368,7 +380,7 @@ class CalculationFormulaValidator(Validator):
result = frappe.safe_eval(formula, eval_globals=None, eval_locals=context)
if not isinstance(result, (int, float)): # noqa: UP038
return f"Formula must return a numeric value, got {type(result).__name__}"
return _("Formula must return a numeric value, got {0}").format(type(result).__name__)
return None
except Exception as e:
@@ -391,9 +403,10 @@ class AccountFilterValidator(Validator):
if not row.calculation_formula:
result.add_error(
ValidationIssue(
message="Account filter is required for Account Data",
message=_("{0} is required for Account Data").format(
get_formula_field_label(row.data_source)
),
row_idx=row.idx,
field="Formula",
)
)
return result
@@ -409,18 +422,18 @@ class AccountFilterValidator(Validator):
if error:
result.add_error(
ValidationIssue(
message=error,
message=_("{0}: {1}").format(get_formula_field_label(row.data_source), error),
row_idx=row.idx,
field="Account Filter",
)
)
except json.JSONDecodeError as e:
result.add_error(
ValidationIssue(
message=f"Invalid JSON format: {e!s}",
message=_("{0}: Invalid JSON format: {1}").format(
get_formula_field_label(row.data_source), str(e)
),
row_idx=row.idx,
field="Account Filter",
)
)
@@ -435,36 +448,38 @@ class AccountFilterValidator(Validator):
# simple condition: [field, operator, value]
if isinstance(filter_config, list):
if len(filter_config) != 3:
return "Filter must be [field, operator, value]"
return _("Filter must be [field, operator, value]")
field, operator, value = filter_config
if not isinstance(field, str) or not isinstance(operator, str):
return "Field and operator must be strings"
return _("Field and operator must be strings")
display = (field if advanced_filtering else self.account_meta.get_label(field)) or field
display = (
field if advanced_filtering else self.account_meta.get_translated_label(field)
) or field
if field not in account_fields:
return f"Field '{display}' is not a valid Account field"
return _("Field '{0}' is not a valid Account field").format(display)
if operator.casefold() not in OPERATOR_MAP:
return f"Invalid operator '{operator}'"
return _("Invalid operator '{0}'").format(operator)
if operator in ["in", "not in"] and not isinstance(value, list):
return f"Operator '{operator}' requires a list value"
return _("Operator '{0}' requires a list value").format(operator)
# logical condition: {"and": [condition1, condition2]}
elif isinstance(filter_config, dict):
if len(filter_config) != 1:
return "Logical condition must have exactly one operator"
return _("Logical condition must have exactly one operator")
op = next(iter(filter_config.keys())).lower()
if op not in ["and", "or"]:
return "Logical operators must be 'and' or 'or'"
return _("Logical operators must be 'and' or 'or'")
conditions = filter_config[next(iter(filter_config.keys()))]
if not isinstance(conditions, list) or len(conditions) < 1:
return "Logical conditions need at least 1 sub-condition"
return _("Logical conditions need at least 1 sub-condition")
# recursive
for condition in conditions:
@@ -472,7 +487,7 @@ class AccountFilterValidator(Validator):
if error:
return error
else:
return "Filter must be a list or dict"
return _("Filter must be a list or dict")
return None
@@ -508,9 +523,10 @@ class FormulaValidator(Validator):
if "." not in api_path:
result.add_error(
ValidationIssue(
message="Custom API path should be in format: app.module.method",
message=_("{0} should be in format: app.module.method").format(
get_formula_field_label(row.data_source)
),
row_idx=row.idx,
field="Formula",
)
)
return result
@@ -523,17 +539,19 @@ class FormulaValidator(Validator):
if not hasattr(module, method_name):
result.add_error(
ValidationIssue(
message=f"Method '{method_name}' not found in module '{module_path}' (might be environment-specific)",
message=_(
"{0}: Method '{1}' not found in module '{2}' (might be environment-specific)"
).format(get_formula_field_label(row.data_source), method_name, module_path),
row_idx=row.idx,
field="Formula",
)
)
except Exception as e:
result.add_error(
ValidationIssue(
message=f"Could not validate API path: {e!s}",
message=_("Could not validate {0}: {1}").format(
get_formula_field_label(row.data_source), str(e)
),
row_idx=row.idx,
field="Formula",
)
)

View File

@@ -82,7 +82,7 @@
"icon": "fa fa-calendar",
"idx": 1,
"links": [],
"modified": "2024-05-27 17:29:55.560840",
"modified": "2026-08-21 23:11:42.509102",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Fiscal Year",
@@ -131,10 +131,15 @@
{
"read": 1,
"role": "Auditor"
},
{
"role": "Sales Master Manager",
"select": 1
}
],
"row_format": "Dynamic",
"show_name_in_global_search": 1,
"sort_field": "name",
"sort_order": "DESC",
"states": []
}
}

View File

@@ -134,7 +134,7 @@ class GLEntry(Document):
mandatory = ["account", "voucher_type", "voucher_no", "company"]
for k in mandatory:
if not self.get(k):
frappe.throw(_("{0} is required").format(_(self.meta.get_label(k))))
frappe.throw(_("{0} is required").format(self.meta.get_translated_label(k)))
if not self.is_cancelled and not (self.party_type and self.party):
account_type = frappe.get_cached_value("Account", self.account, "account_type")

View File

@@ -57,7 +57,7 @@
}
],
"links": [],
"modified": "2024-03-27 13:09:55.573483",
"modified": "2026-08-21 23:11:43.571355",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Item Tax Template",
@@ -95,12 +95,61 @@
"report": 1,
"role": "Accounts User",
"share": 1
},
{
"role": "Delivery Manager",
"select": 1
},
{
"role": "Delivery User",
"select": 1
},
{
"role": "Item Manager",
"select": 1
},
{
"role": "Maintenance Manager",
"select": 1
},
{
"role": "Maintenance User",
"select": 1
},
{
"role": "Manufacturing Manager",
"select": 1
},
{
"role": "Purchase Manager",
"select": 1
},
{
"role": "Purchase User",
"select": 1
},
{
"role": "Sales Manager",
"select": 1
},
{
"role": "Sales User",
"select": 1
},
{
"role": "Stock Manager",
"select": 1
},
{
"role": "Stock User",
"select": 1
}
],
"row_format": "Dynamic",
"show_name_in_global_search": 1,
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"title_field": "title",
"track_changes": 1
}
}

View File

@@ -8,6 +8,6 @@ def get_data():
{"label": _("Pre Sales"), "items": ["Quotation", "Supplier Quotation"]},
{"label": _("Sales"), "items": ["Sales Invoice", "Sales Order", "Delivery Note"]},
{"label": _("Purchase"), "items": ["Purchase Invoice", "Purchase Order", "Purchase Receipt"]},
{"label": _("Stock"), "items": ["Item Groups", "Item"]},
{"label": _("Stock"), "items": ["Item Group", "Item"]},
],
}

View File

@@ -235,7 +235,7 @@ Object.assign(erpnext.journal_entry, {
lock_reversal_entry(frm) {
frm.fields
.filter((field) => field.has_input)
.filter((field) => field.df.fieldname != "posting_date")
.filter((field) => !["posting_date", "custom_remark", "remark"].includes(field.df.fieldname))
.forEach((field) => frm.set_df_property(field.df.fieldname, "read_only", 1));
frm.set_df_property("accounts", "read_only", 1);
},
@@ -249,7 +249,7 @@ Object.assign(erpnext.journal_entry, {
);
}
if (frm.doc.docstatus == 1) {
if (frm.doc.docstatus == 1 && !frm.doc.reversal_of) {
frm.add_custom_button(
__("Reverse Journal Entry"),
() => erpnext.journal_entry.reverse_journal_entry(frm),
@@ -677,6 +677,6 @@ Object.assign(erpnext.journal_entry, {
} else {
erpnext.journal_entry.set_debit_credit_in_company_currency(frm, cdt, cdn);
}
frm.refresh_field("accounts");
frm.get_field("accounts").grid.refresh_row(cdn);
},
});

View File

@@ -180,7 +180,7 @@ class JournalEntry(AccountsController):
JournalTaxWithholding(self).on_validate()
if self.is_new() or not self.title:
if not self.title or (self.is_new() and self.amended_from):
self.title = self.get_title()
def validate_advance_accounts(self):

View File

@@ -222,6 +222,20 @@ def make_inter_company_journal_entry(name: str, voucher_type: str, company: str)
@frappe.whitelist()
def make_reverse_journal_entry(source_name: str, target_doc: str | dict | Document | None = None) -> Document:
"""Map a submitted Journal Entry to a reversing one (debits and credits swapped)."""
# `get_mapped_doc` checks this as well, but the guards below disclose which entry
# reverses which, so read access has to be settled before they run
if not frappe.has_permission("Journal Entry", doc=source_name):
frappe.throw(_("Not permitted"), frappe.PermissionError)
reversal_of = frappe.db.get_value("Journal Entry", source_name, "reversal_of")
if reversal_of:
frappe.throw(
_("{0} is already a Reverse Journal Entry of {1}. Cancel it instead of reversing it.").format(
get_link_to_form("Journal Entry", source_name),
get_link_to_form("Journal Entry", reversal_of),
)
)
existing_reverse = frappe.db.exists("Journal Entry", {"reversal_of": source_name, "docstatus": 1})
if existing_reverse:
frappe.throw(

View File

@@ -184,6 +184,7 @@ class JournalEntryReferenceValidator:
continue
invoice = frappe.get_doc(reference_type, reference_name)
self._validate_invoice_outstanding(invoice, total, reference_type, reference_name)
self._validate_block_invoice(invoice)
def _validate_invoice_outstanding(self, invoice, total, reference_type, reference_name) -> None:
"""Payment booked against an invoice cannot exceed its outstanding amount."""
@@ -197,3 +198,15 @@ class JournalEntryReferenceValidator:
reference_type, reference_name, invoice.outstanding_amount
)
)
def _validate_block_invoice(self, invoice):
"""Payment cannnot be booked against blocked Purchase Invoices"""
if invoice.doctype != "Purchase Invoice":
return
if invoice.invoice_is_blocked():
frappe.throw(
_("{0} {1} is blocked and on hold until {2}.").format(
invoice.doctype, invoice.name, invoice.release_date
)
)

View File

@@ -2,7 +2,7 @@
# License: GNU General Public License v3. See license.txt
import frappe
from frappe.utils import flt, nowdate
from frappe.utils import add_days, flt, nowdate
from erpnext.accounts.doctype.account.test_account import get_inventory_account
from erpnext.accounts.doctype.journal_entry.journal_entry import StockAccountInvalidTransaction
@@ -301,6 +301,27 @@ class TestJournalEntry(ERPNextTestSuite):
self.check_gl_entries()
def test_disallow_reversal_of_a_reversal_journal_entry(self):
from erpnext.accounts.doctype.journal_entry.mapper import make_reverse_journal_entry
jv = make_journal_entry("_Test Bank - _TC", "Sales - _TC", 100, submit=True)
rjv = make_reverse_journal_entry(jv.name)
rjv.posting_date = nowdate()
rjv.submit()
self.assertRaisesRegex(
frappe.ValidationError,
"is already a Reverse Journal Entry",
make_reverse_journal_entry,
rjv.name,
)
# the guard must not disclose the reversal to a user who cannot read the entry
frappe.set_user("Guest")
self.addCleanup(frappe.set_user, "Administrator")
self.assertRaises(frappe.PermissionError, make_reverse_journal_entry, rjv.name)
def test_disallow_change_in_account_currency_for_a_party(self):
# create jv in USD
jv = make_journal_entry("_Test Bank USD - _TC", "_Test Receivable USD - _TC", 100, save=False)
@@ -748,6 +769,69 @@ class TestJournalEntry(ERPNextTestSuite):
self.assertEqual(jv.reference_types[invoice.name], "Sales Invoice")
self.assertEqual(jv.reference_accounts[invoice.name], "Debtors - _TC")
def make_jv_against_purchase_invoice(self, invoice, amount=100):
jv = make_journal_entry("Creditors - _TC", "_Test Cash - _TC", amount, save=False)
jv.accounts[0].party_type = "Supplier"
jv.accounts[0].party = invoice.supplier
jv.accounts[0].reference_type = "Purchase Invoice"
jv.accounts[0].reference_name = invoice.name
return jv
def test_jv_against_purchase_invoice_respects_hold_state(self):
"""Payment can be booked against a Purchase Invoice only while it is not on hold."""
from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice
release_date = add_days(nowdate(), 10)
def never_held():
return make_purchase_invoice()
def held_until_a_future_date():
invoice = make_purchase_invoice()
invoice.block_invoice(hold_comment="Waiting for the goods", release_date=release_date)
return invoice
def held_without_a_release_date():
invoice = make_purchase_invoice()
invoice.block_invoice(hold_comment="Under dispute")
return invoice
def held_until_a_date_that_has_passed():
invoice = held_until_a_future_date()
frappe.db.set_value("Purchase Invoice", invoice.name, "release_date", add_days(nowdate(), -1))
return invoice
def unblocked_again():
invoice = held_until_a_future_date()
invoice.unblock_invoice()
return invoice
for build_invoice in (held_until_a_future_date, held_without_a_release_date):
with self.subTest(build_invoice.__name__):
jv = self.make_jv_against_purchase_invoice(build_invoice())
self.assertRaisesRegex(frappe.ValidationError, "is blocked and on hold until", jv.insert)
for build_invoice in (never_held, held_until_a_date_that_has_passed, unblocked_again):
with self.subTest(build_invoice.__name__):
invoice = build_invoice()
jv = self.make_jv_against_purchase_invoice(invoice)
jv.insert()
self.assertEqual(jv.reference_types[invoice.name], "Purchase Invoice")
def test_jv_against_blocked_sales_invoice_reference_is_not_checked(self):
"""A Sales Invoice has no hold state, so the check must skip it rather than fail."""
from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
invoice = create_sales_invoice(rate=500)
jv = make_journal_entry("_Test Cash - _TC", "Debtors - _TC", 100, save=False)
jv.accounts[1].party_type = "Customer"
jv.accounts[1].party = "_Test Customer"
jv.accounts[1].reference_type = "Sales Invoice"
jv.accounts[1].reference_name = invoice.name
jv.insert()
self.assertEqual(jv.reference_types[invoice.name], "Sales Invoice")
def test_get_balance_places_difference_on_blank_row(self):
"""Characterize: get_balance puts the unbalanced difference on an amountless row."""
jv = frappe.new_doc("Journal Entry")

View File

@@ -147,14 +147,14 @@
"fieldtype": "Column Break"
},
{
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
"fieldname": "project",
"fieldtype": "Link",
"label": "Project",
"options": "Project"
}
],
"links": [],
"modified": "2024-03-27 13:10:03.361383",
"modified": "2026-08-21 23:11:44.144864",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Loyalty Program",
@@ -171,11 +171,20 @@
"role": "System Manager",
"share": 1,
"write": 1
},
{
"role": "Sales Master Manager",
"select": 1
},
{
"role": "Sales User",
"select": 1
}
],
"quick_entry": 1,
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"track_changes": 1
}
}

View File

@@ -48,7 +48,7 @@
"idx": 1,
"index_web_pages_for_search": 1,
"links": [],
"modified": "2026-04-14 18:16:47.795986",
"modified": "2026-08-21 23:11:44.763131",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Mode of Payment",
@@ -76,6 +76,30 @@
{
"role": "HR Manager",
"select": 1
},
{
"role": "Maintenance Manager",
"select": 1
},
{
"role": "Maintenance User",
"select": 1
},
{
"role": "Purchase Manager",
"select": 1
},
{
"role": "Purchase User",
"select": 1
},
{
"role": "Sales Manager",
"select": 1
},
{
"role": "Sales User",
"select": 1
}
],
"quick_entry": 1,

View File

@@ -46,7 +46,7 @@
"icon": "fa fa-bar-chart",
"idx": 1,
"links": [],
"modified": "2024-03-27 13:10:05.873547",
"modified": "2026-08-21 23:11:44.908490",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Monthly Distribution",
@@ -69,9 +69,14 @@
"read": 1,
"report": 1,
"role": "Accounts Manager"
},
{
"role": "Sales Master Manager",
"select": 1
}
],
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "DESC",
"states": []
}
}

View File

@@ -476,6 +476,8 @@ frappe.ui.form.on("Payment Entry", {
return {
query: "erpnext.controllers.queries.employee_query",
};
} else if (["Customer", "Supplier"].includes(frm.doc.party_type)) {
return erpnext.queries.party(frm.doc);
} else if (frm.doc.party_type == "Shareholder") {
return {
filters: {
@@ -1277,8 +1279,14 @@ frappe.ui.form.on("Payment Entry", {
await frappe.after_ajax();
const base_paid_amount = frm.doc.base_paid_amount || 0;
const base_received_amount = frm.doc.base_received_amount || 0;
let other_deductions = 0;
if (frm.doc.payment_type === "Internal Transfer") {
other_deductions = (frm.doc.deductions || [])
.filter((row) => !row.is_exchange_gain_loss)
.reduce((sum, row) => sum + flt(row.amount), 0);
}
const exchange_gain_loss = flt(
base_paid_amount - base_received_amount,
base_paid_amount - base_received_amount - other_deductions,
get_deduction_amount_precision()
);
@@ -1292,7 +1300,10 @@ frappe.ui.form.on("Payment Entry", {
if (!row) {
const company_defaults = frappe.get_doc(":Company", frm.doc.company);
const is_single_currency =
frm.doc.paid_from_account_currency === frm.doc.paid_to_account_currency;
const account =
(is_single_currency && company_defaults?.bank_charges_account) ||
company_defaults?.[account_fieldname] ||
(await prompt_for_missing_account(frm, account_fieldname));
@@ -1847,16 +1858,24 @@ frappe.ui.form.on("Payment Entry Deduction", {
before_deductions_remove: function (doc, cdt, cdn) {
const row = frappe.get_doc(cdt, cdn);
if (row.is_exchange_gain_loss && row.amount) {
frappe.throw(__("Cannot delete Exchange Gain/Loss row"));
frappe.throw(__("Cannot delete a system-generated deduction row"));
}
},
amount: function (frm) {
frm.events.set_unallocated_amount(frm);
if (frm.doc.payment_type === "Internal Transfer") {
frm.events.set_exchange_gain_loss_deduction(frm);
} else {
frm.events.set_unallocated_amount(frm);
}
},
deductions_remove: function (frm) {
frm.events.set_unallocated_amount(frm);
if (frm.doc.payment_type === "Internal Transfer") {
frm.events.set_exchange_gain_loss_deduction(frm);
} else {
frm.events.set_unallocated_amount(frm);
}
},
});

View File

@@ -40,6 +40,7 @@ from erpnext.accounts.party import (
complete_contact_details,
get_default_contact,
get_party_account,
validate_party_company,
)
from erpnext.accounts.utils import (
cancel_exchange_gain_loss_journal,
@@ -277,7 +278,8 @@ class PaymentEntry(AccountsController):
if not liability_account:
throw(
_("Please set default {0} in Company {1}").format(
frappe.bold(frappe.get_meta("Company").get_label(fieldname)), frappe.bold(self.company)
frappe.bold(frappe.get_meta("Company").get_translated_label(fieldname)),
frappe.bold(self.company),
)
)
@@ -660,7 +662,7 @@ class PaymentEntry(AccountsController):
def validate_mandatory(self):
for field in ("paid_amount", "received_amount", "source_exchange_rate", "target_exchange_rate"):
if not self.get(field):
frappe.throw(_("{0} is mandatory").format(_(self.meta.get_label(field))))
frappe.throw(_("{0} is mandatory").format(self.meta.get_translated_label(field)))
def validate_reference_documents(self):
valid_reference_doctypes = self.get_valid_reference_doctypes()
@@ -1116,8 +1118,14 @@ class PaymentEntry(AccountsController):
)
def set_exchange_gain_loss(self):
other_deductions = 0
if self.payment_type == "Internal Transfer":
other_deductions = sum(
flt(row.amount) for row in self.get("deductions") if not row.is_exchange_gain_loss
)
exchange_gain_loss = flt(
self.base_paid_amount - self.base_received_amount,
self.base_paid_amount - self.base_received_amount - other_deductions,
self.precision("amount", "deductions"),
)
@@ -1135,14 +1143,22 @@ class PaymentEntry(AccountsController):
if not exchange_gain_loss_row:
values = frappe.get_cached_value(
"Company", self.company, ("exchange_gain_loss_account", "cost_center"), as_dict=True
"Company",
self.company,
("bank_charges_account", "exchange_gain_loss_account", "cost_center"),
as_dict=True,
)
is_single_currency = self.paid_from_account_currency == self.paid_to_account_currency
account = (
is_single_currency and values.bank_charges_account
) or values.exchange_gain_loss_account
for fieldname, value in values.items():
missing_fields = {"exchange_gain_loss_account": account, "cost_center": values.cost_center}
for fieldname, value in missing_fields.items():
if value:
continue
label = _(frappe.get_meta("Company").get_label(fieldname))
label = frappe.get_meta("Company").get_translated_label(fieldname)
return frappe.msgprint(
_("Please set {0} in Company {1} to account for Exchange Gain / Loss").format(
label, get_link_to_form("Company", self.company)
@@ -1155,7 +1171,7 @@ class PaymentEntry(AccountsController):
exchange_gain_loss_row = self.append(
"deductions",
{
"account": values.exchange_gain_loss_account,
"account": account,
"cost_center": values.cost_center,
"is_exchange_gain_loss": 1,
},
@@ -2426,6 +2442,7 @@ def get_party_details(company: str, party_type: str, party: str, date: str, cost
ptype = "select" if frappe.only_has_select_perm(party_type) else "read"
frappe.has_permission(party_type, ptype, party, throw=True)
validate_party_company(party_type, party, company)
party_account = get_party_account(party_type, party, company)
account_currency = get_account_currency(party_account)

View File

@@ -782,6 +782,152 @@ class TestPaymentEntry(ERPNextTestSuite):
self.validate_gl_entries(pe.name, expected_gle)
def test_bank_charges_deduction(self):
bank_charges_account = create_account(
parent_account="Indirect Expenses - _TC",
account_name="_Test Bank Charges",
company="_Test Company",
)
frappe.db.set_value("Company", "_Test Company", "bank_charges_account", bank_charges_account)
self.addCleanup(frappe.db.set_value, "Company", "_Test Company", "bank_charges_account", "")
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 Cash - _TC"
pe.paid_amount = 1000
pe.received_amount = 990
pe.reference_no = "4"
pe.reference_date = nowdate()
pe.setup_party_account_field()
pe.set_missing_values()
pe.set_exchange_rate()
pe.set_amounts()
self.assertEqual(pe.deductions[0].account, bank_charges_account)
self.assertEqual(pe.deductions[0].amount, 10)
pe.deductions[0].cost_center = "_Test Cost Center - _TC"
pe.insert()
pe.submit()
expected_gle = dict(
(d[0], d)
for d in [
["_Test Bank - _TC", 0, 1000, None],
["_Test Cash - _TC", 990, 0, None],
[bank_charges_account, 10, 0, None],
]
)
self.validate_gl_entries(pe.name, expected_gle)
def test_cross_currency_transfer_ignores_bank_charges_account(self):
exchange_gain_loss_account = frappe.db.get_value(
"Company", "_Test Company", "exchange_gain_loss_account"
)
bank_charges_account = create_account(
parent_account="Indirect Expenses - _TC",
account_name="_Test Bank Charges",
company="_Test Company",
)
frappe.db.set_value("Company", "_Test Company", "bank_charges_account", bank_charges_account)
self.addCleanup(frappe.db.set_value, "Company", "_Test Company", "bank_charges_account", "")
pe = frappe.new_doc("Payment Entry")
pe.payment_type = "Internal Transfer"
pe.company = "_Test Company"
pe.paid_from = "_Test Bank USD - _TC"
pe.paid_to = "_Test Bank - _TC"
pe.paid_amount = 100
pe.source_exchange_rate = 50
pe.received_amount = 4500
pe.reference_no = "5"
pe.reference_date = nowdate()
pe.setup_party_account_field()
pe.set_missing_values()
pe.set_exchange_rate()
pe.set_amounts()
self.assertEqual(pe.deductions[0].account, exchange_gain_loss_account)
self.assertEqual(pe.deductions[0].amount, 500)
pe.deductions[0].cost_center = "_Test Cost Center - _TC"
pe.insert()
pe.submit()
expected_gle = dict(
(d[0], d)
for d in [
["_Test Bank USD - _TC", 0, 5000, None],
["_Test Bank - _TC", 4500, 0, None],
[exchange_gain_loss_account, 500.0, 0, None],
]
)
self.validate_gl_entries(pe.name, expected_gle)
def test_cross_currency_transfer_splits_bank_charge_and_exchange_gain_loss(self):
exchange_gain_loss_account = frappe.db.get_value(
"Company", "_Test Company", "exchange_gain_loss_account"
)
bank_charges_account = create_account(
parent_account="Indirect Expenses - _TC",
account_name="_Test Bank Charges",
company="_Test Company",
)
pe = frappe.new_doc("Payment Entry")
pe.payment_type = "Internal Transfer"
pe.company = "_Test Company"
pe.paid_from = "_Test Bank USD - _TC"
pe.paid_to = "_Test Bank - _TC"
pe.paid_amount = 100
pe.source_exchange_rate = 50
pe.received_amount = 4500
pe.reference_no = "6"
pe.reference_date = nowdate()
pe.append(
"deductions",
{
"account": bank_charges_account,
"cost_center": "_Test Cost Center - _TC",
"amount": 100,
},
)
pe.setup_party_account_field()
pe.set_missing_values()
pe.set_exchange_rate()
pe.set_amounts()
deductions = {d.account: d for d in pe.deductions}
self.assertEqual(deductions[bank_charges_account].amount, 100)
self.assertEqual(deductions[exchange_gain_loss_account].amount, 400)
self.assertTrue(deductions[exchange_gain_loss_account].is_exchange_gain_loss)
self.assertEqual(pe.difference_amount, 0)
for d in pe.deductions:
d.cost_center = "_Test Cost Center - _TC"
pe.insert()
pe.submit()
expected_gle = dict(
(d[0], d)
for d in [
["_Test Bank USD - _TC", 0, 5000, None],
["_Test Bank - _TC", 4500, 0, None],
[exchange_gain_loss_account, 400.0, 0, None],
[bank_charges_account, 100.0, 0, None],
]
)
self.validate_gl_entries(pe.name, expected_gle)
def test_payment_against_negative_sales_invoice(self):
si1 = create_sales_invoice()
@@ -950,6 +1096,61 @@ class TestPaymentEntry(ERPNextTestSuite):
outstanding_amount = flt(frappe.db.get_value("Sales Invoice", si.name, "outstanding_amount"))
self.assertEqual(outstanding_amount, 0)
def test_exchange_gain_loss_split_accounts(self):
gain_account = create_account(
account_name="_Test Exchange Gain",
parent_account="Indirect Expenses - _TC",
company="_Test Company",
)
loss_account = create_account(
account_name="_Test Exchange Loss",
parent_account="Indirect Expenses - _TC",
company="_Test Company",
)
frappe.db.set_value("Company", "_Test Company", "exchange_gain_account", gain_account)
frappe.db.set_value("Company", "_Test Company", "exchange_loss_account", loss_account)
self.addCleanup(frappe.db.set_value, "Company", "_Test Company", "exchange_gain_account", "")
self.addCleanup(frappe.db.set_value, "Company", "_Test Company", "exchange_loss_account", "")
si_gain = create_sales_invoice(
customer="_Test Customer USD",
debit_to="_Test Receivable USD - _TC",
currency="USD",
conversion_rate=50,
)
pe_gain = get_payment_entry("Sales Invoice", si_gain.name, bank_account="_Test Bank USD - _TC")
pe_gain.reference_no = "1"
pe_gain.reference_date = "2016-01-01"
pe_gain.source_exchange_rate = 55
pe_gain.save()
self.assertEqual(pe_gain.references[0].exchange_gain_loss, 500)
pe_gain.submit()
self.assertEqual(self.get_gain_loss_journal_account(pe_gain.name), gain_account)
si_loss = create_sales_invoice(
customer="_Test Customer USD",
debit_to="_Test Receivable USD - _TC",
currency="USD",
conversion_rate=55,
)
pe_loss = get_payment_entry("Sales Invoice", si_loss.name, bank_account="_Test Bank USD - _TC")
pe_loss.reference_no = "2"
pe_loss.reference_date = "2016-01-01"
pe_loss.source_exchange_rate = 50
pe_loss.save()
self.assertEqual(pe_loss.references[0].exchange_gain_loss, -500)
pe_loss.submit()
self.assertEqual(self.get_gain_loss_journal_account(pe_loss.name), loss_account)
def get_gain_loss_journal_account(self, payment_entry_name: str) -> str | None:
return frappe.db.get_value(
"Journal Entry Account",
{"reference_type": "Payment Entry", "reference_name": payment_entry_name, "docstatus": 1},
"account",
)
def test_payment_entry_against_sales_invoice_with_cost_centre(self):
from erpnext.accounts.doctype.cost_center.test_cost_center import create_cost_center

View File

@@ -53,7 +53,7 @@
"depends_on": "eval:doc.is_exchange_gain_loss",
"fieldname": "is_exchange_gain_loss",
"fieldtype": "Check",
"label": "Is Exchange Gain / Loss?",
"label": "System Generated",
"read_only": 1
}
],

View File

@@ -18,6 +18,7 @@ from erpnext.accounts.doctype.process_payment_reconciliation.process_payment_rec
is_any_doc_running,
)
from erpnext.accounts.services.advances import get_advance_payment_entries_for_regional
from erpnext.accounts.services.exchange_gain_loss import get_exchange_gain_loss_account
from erpnext.accounts.utils import (
QueryPaymentLedger,
create_gain_loss_journal,
@@ -485,9 +486,6 @@ class PaymentReconciliation(Document):
"Accounts Settings", "exchange_gain_loss_posting_date", cache=True
)
invoice_exchange_map = self.get_invoice_exchange_map(args.get("invoices"), args.get("payments"))
default_exchange_gain_loss_account = frappe.get_cached_value(
"Company", self.company, "exchange_gain_loss_account"
)
entries = []
for pay in args.get("payments"):
@@ -507,7 +505,10 @@ class PaymentReconciliation(Document):
pay["exchange_rate"] = invoice_exchange_map.get(pay.get("reference_name"))
res.difference_amount = self.get_difference_amount(pay, inv, res["allocated_amount"])
res.difference_account = default_exchange_gain_loss_account
is_gain = (
res.difference_amount > 0 if self.party_type == "Customer" else res.difference_amount < 0
)
res.difference_account = get_exchange_gain_loss_account(self.company, is_gain)
res.exchange_rate = inv.get("exchange_rate")
res.update({"gain_loss_posting_date": pay.get("posting_date")})
if not pay.get("is_advance"):
@@ -646,7 +647,7 @@ class PaymentReconciliation(Document):
def check_mandatory_to_fetch(self):
for fieldname in ["company", "party_type", "party", "receivable_payable_account"]:
if not self.get(fieldname):
frappe.throw(_("Please select {0} first").format(_(self.meta.get_label(fieldname))))
frappe.throw(_("Please select {0} first").format(self.meta.get_translated_label(fieldname)))
def validate_entries(self):
if not self.get("invoices"):

View File

@@ -6,6 +6,7 @@ import frappe
from frappe.utils import add_days, add_years, cint, flt, getdate, nowdate, today
from frappe.utils.data import getdate as convert_to_date
from erpnext.accounts.doctype.account.test_account import create_account
from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
from erpnext.accounts.doctype.payment_entry.test_payment_entry import create_payment_entry
from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice
@@ -187,6 +188,150 @@ class TestPaymentReconciliation(ERPNextTestSuite):
)
return je
def setup_split_exchange_accounts(self):
gain_account = create_account(
account_name="_Test PR Split Exchange Gain",
parent_account="Indirect Expenses - _TC",
company=self.company,
)
loss_account = create_account(
account_name="_Test PR Split Exchange Loss",
parent_account="Indirect Expenses - _TC",
company=self.company,
)
frappe.db.set_value("Company", self.company, "exchange_gain_account", gain_account)
frappe.db.set_value("Company", self.company, "exchange_loss_account", loss_account)
self.addCleanup(frappe.db.set_value, "Company", self.company, "exchange_gain_account", "")
self.addCleanup(frappe.db.set_value, "Company", self.company, "exchange_loss_account", "")
return gain_account, loss_account
def create_foreign_currency_sales_invoice(self, conversion_rate):
si = self.create_sales_invoice(
qty=1, rate=100, posting_date=nowdate(), do_not_save=True, do_not_submit=True
)
si.customer = self.customer_usd
si.currency = "USD"
si.conversion_rate = conversion_rate
si.debit_to = self.debtors_usd
si.save().submit()
return si
def create_foreign_currency_journal_payment(self, debtors_account, exchange_rate):
je = self.create_journal_entry(self.bank, debtors_account, 100, nowdate())
je.multi_currency = 1
je.accounts[0].exchange_rate = 1
je.accounts[0].credit_in_account_currency = 0
je.accounts[0].credit = 0
je.accounts[0].debit_in_account_currency = 100 * exchange_rate
je.accounts[0].debit = 100 * exchange_rate
je.accounts[1].party_type = "Customer"
je.accounts[1].party = self.customer_usd
je.accounts[1].exchange_rate = exchange_rate
je.accounts[1].credit_in_account_currency = 100
je.accounts[1].credit = 100 * exchange_rate
je.accounts[1].debit_in_account_currency = 0
je.accounts[1].debit = 0
je.save()
je.submit()
return je
def test_voucher_outstanding_metadata_comes_from_one_ledger_entry(self):
"""cost_center and remarks must describe the same Payment Ledger Entry.
A voucher can post several ledger entries for one party with different cost centers and
remarks. Aggregating each column on its own can pair one entry's cost center with another's
remarks -- a row that was never posted -- and because Max() over text is a sort, MariaDB and
PostgreSQL can pick differently on top of that.
"""
from erpnext.accounts.utils import QueryPaymentLedger
je = frappe.new_doc("Journal Entry")
je.posting_date = nowdate()
je.company = self.company
je.user_remark = "aaa base remark"
for cost_center, remark, amount in (
(self.main_cc, "aaa main line", 100),
(self.sub_cc, "zzz sub line", 50),
):
je.append(
"accounts",
{
"account": self.debit_to,
"party_type": "Customer",
"party": self.customer,
"cost_center": cost_center,
"user_remark": remark,
"debit_in_account_currency": amount,
},
)
je.append(
"accounts", {"account": self.cash, "cost_center": self.main_cc, "credit_in_account_currency": 150}
)
je.save()
je.submit()
posted = {
(row.cost_center, row.remarks)
for row in frappe.get_all(
"Payment Ledger Entry",
filters={"voucher_no": je.name, "delinked": 0},
fields=["cost_center", "remarks"],
)
}
self.assertGreater(len(posted), 1, "fixture must post more than one ledger entry to be meaningful")
ledger = QueryPaymentLedger()
rows = ledger.get_voucher_outstandings(
vouchers=[frappe._dict(voucher_type="Journal Entry", voucher_no=je.name)]
)
self.assertTrue(rows)
for row in rows:
self.assertIn((row.cost_center, row.remarks), posted)
def test_voucher_outstanding_splits_by_party_account(self):
"""A voucher posting to two party accounts must report each account separately.
account is the join key between the amount and outstanding CTEs. Selecting Max(account)
while grouping without it made that key an aggregate over two different row sets, so the two
sides could pick different accounts, the join would miss and the outstanding come back NULL.
It also summed amounts across accounts that need not share a currency.
"""
from erpnext.accounts.utils import QueryPaymentLedger
second_receivable = "_Test Receivable - _TC"
je = frappe.new_doc("Journal Entry")
je.posting_date = nowdate()
je.company = self.company
je.user_remark = "two receivable accounts"
for account, amount in ((self.debit_to, 100), (second_receivable, 60)):
je.append(
"accounts",
{
"account": account,
"party_type": "Customer",
"party": self.customer,
"cost_center": self.main_cc,
"debit_in_account_currency": amount,
},
)
je.append(
"accounts", {"account": self.cash, "cost_center": self.main_cc, "credit_in_account_currency": 160}
)
je.save()
je.submit()
rows = QueryPaymentLedger().get_voucher_outstandings(
vouchers=[frappe._dict(voucher_type="Journal Entry", voucher_no=je.name)]
)
by_account = {row.account: row for row in rows}
self.assertEqual(set(by_account), {self.debit_to, second_receivable})
self.assertEqual(flt(by_account[self.debit_to].invoice_amount), 100)
self.assertEqual(flt(by_account[second_receivable].invoice_amount), 60)
for row in rows:
self.assertIsNotNone(row.outstanding)
def test_filter_min_max(self):
# check filter condition minimum and maximum amount
self.create_sales_invoice(qty=1, rate=300)
@@ -859,6 +1004,85 @@ class TestPaymentReconciliation(ERPNextTestSuite):
frappe.db.get_value("Journal Entry", jea_parent.parent, "voucher_type"), "Exchange Gain Or Loss"
)
def test_exchange_gain_loss_split_default_account(self):
gain_account, loss_account = self.setup_split_exchange_accounts()
self.create_foreign_currency_sales_invoice(conversion_rate=80)
self.create_foreign_currency_journal_payment(self.debtors_usd, exchange_rate=85)
pr = self.create_payment_reconciliation()
pr.party = self.customer_usd
pr.receivable_payable_account = self.debtors_usd
pr.get_unreconciled_entries()
invoices = [x.as_dict() for x in pr.invoices]
payments = [x.as_dict() for x in pr.payments]
pr.allocate_entries(frappe._dict({"invoices": invoices, "payments": payments}))
self.assertEqual(pr.allocation[0].difference_amount, 500)
self.assertEqual(pr.allocation[0].difference_account, gain_account)
pr.reconcile()
self.create_foreign_currency_sales_invoice(conversion_rate=85)
self.create_foreign_currency_journal_payment(self.debtors_usd, exchange_rate=80)
pr = self.create_payment_reconciliation()
pr.party = self.customer_usd
pr.receivable_payable_account = self.debtors_usd
pr.get_unreconciled_entries()
invoices = [x.as_dict() for x in pr.invoices]
payments = [x.as_dict() for x in pr.payments]
pr.allocate_entries(frappe._dict({"invoices": invoices, "payments": payments}))
self.assertEqual(pr.allocation[0].difference_amount, -500)
self.assertEqual(pr.allocation[0].difference_account, loss_account)
def test_payment_reconciliation_difference_account_override(self):
_, loss_account = self.setup_split_exchange_accounts()
override_account = create_account(
account_name="_Test PR Override Exchange Account",
parent_account="Indirect Expenses - _TC",
company=self.company,
)
si = self.create_foreign_currency_sales_invoice(conversion_rate=85)
self.create_foreign_currency_journal_payment(self.debtors_usd, exchange_rate=80)
pr = self.create_payment_reconciliation()
pr.party = self.customer_usd
pr.receivable_payable_account = self.debtors_usd
pr.get_unreconciled_entries()
invoices = [x.as_dict() for x in pr.invoices]
payments = [x.as_dict() for x in pr.payments]
pr.allocate_entries(frappe._dict({"invoices": invoices, "payments": payments}))
# Default, computed from the split company fields, is pre-filled onto the row...
self.assertEqual(pr.allocation[0].difference_amount, -500)
self.assertEqual(pr.allocation[0].difference_account, loss_account)
# ...but the user can override it in the "Select Difference Account" dialog before reconciling,
# and that explicit choice must be what actually gets booked, not the computed default.
pr.allocation[0].difference_account = override_account
pr.reconcile()
jea_parent = frappe.db.get_all(
"Journal Entry Account",
filters={"account": self.debtors_usd, "docstatus": 1, "reference_name": si.name, "credit": 500},
fields=["parent"],
)[0]
self.assertEqual(
frappe.db.get_value("Journal Entry", jea_parent.parent, "voucher_type"), "Exchange Gain Or Loss"
)
gain_loss_line_account = frappe.db.get_value(
"Journal Entry Account",
{"parent": jea_parent.parent, "account": ["!=", self.debtors_usd]},
"account",
)
self.assertEqual(gain_loss_line_account, override_account)
def test_difference_amount_via_negative_debit_or_credit_journal_entry(self):
# Make Sale Invoice
si = self.create_sales_invoice(
@@ -2402,6 +2626,86 @@ class TestPaymentReconciliation(ERPNextTestSuite):
self.assertEqual(flt(pr.allocation[0].get("difference_amount")), -5000.0)
pr.reconcile()
def test_foreign_currency_reverse_payment_entry_gain_for_supplier(self):
transaction_date = nowdate()
self.supplier = "_Test Supplier USD"
amount = 100
department = frappe.db.get_value("Department", {"company": self.company, "is_group": 0}, "name")
# Pay USD 100 at an exchange rate of 90.
pe = self.create_payment_entry(amount=amount, posting_date=transaction_date)
pe.payment_type = "Pay"
pe.party_type = "Supplier"
pe.party = self.supplier
pe.paid_from = self.cash
pe.paid_from_account_currency = "INR"
pe.target_exchange_rate = 90
pe.paid_amount = 90 * amount
pe.received_amount = amount
pe.paid_to = self.creditors_usd
pe.paid_to_account_currency = "USD"
pe.department = department
pe = pe.save().submit()
# Receive USD 100 from the supplier at an exchange rate of 100.
reverse_pe = self.create_payment_entry(amount=amount, posting_date=transaction_date)
reverse_pe.payment_type = "Receive"
reverse_pe.party_type = "Supplier"
reverse_pe.party = self.supplier
reverse_pe.paid_from = self.creditors_usd
reverse_pe.paid_from_account_currency = "USD"
reverse_pe.source_exchange_rate = 100
reverse_pe.paid_amount = amount
reverse_pe.received_amount = 100 * amount
reverse_pe.paid_to = self.cash
reverse_pe.paid_to_account_currency = "INR"
reverse_pe.department = department
reverse_pe = reverse_pe.save().submit()
pr = self.create_payment_reconciliation(party_is_customer=False)
pr.party = self.supplier
pr.receivable_payable_account = self.creditors_usd
pr.get_unreconciled_entries()
invoices = [invoice.as_dict() for invoice in pr.invoices]
payments = [payment.as_dict() for payment in pr.payments]
pr.allocate_entries(frappe._dict({"invoices": invoices, "payments": payments}))
for row in pr.allocation:
row.department = department
self.assertEqual(flt(pr.allocation[0].difference_amount), 1000)
pr.reconcile()
gain_loss_journal = frappe.db.get_value(
"Journal Entry Account",
{
"reference_type": reverse_pe.doctype,
"reference_name": reverse_pe.name,
"party": self.supplier,
"docstatus": 1,
},
"parent",
)
party_row = frappe.db.get_value(
"Journal Entry Account",
{"parent": gain_loss_journal, "party": self.supplier},
["debit", "credit"],
as_dict=True,
)
self.assertEqual(flt(party_row.debit), 1000)
self.assertEqual(flt(party_row.credit), 0)
party_gl_entries = frappe.get_all(
"GL Entry",
filters={
"voucher_no": ["in", [pe.name, reverse_pe.name, gain_loss_journal]],
"account": self.creditors_usd,
"party": self.supplier,
"is_cancelled": 0,
},
fields=["debit", "credit"],
)
self.assertEqual(flt(sum(row.debit - row.credit for row in party_gl_entries)), 0)
def test_foreign_currency_reverse_journal_entry_against_journal_entry_for_customer(self):
transaction_date = nowdate()
customer = self.customer_usd

View File

@@ -92,6 +92,7 @@ frappe.ui.form.on("Payment Request", "is_a_subscription", function (frm) {
freeze: true,
callback: function (data) {
if (!data.exc) {
frm.clear_table("subscription_plans");
$.each(data.message || [], function (i, v) {
var d = frappe.model.add_child(
frm.doc,

View File

@@ -640,7 +640,7 @@ class PaymentRequest(Document):
}
if self.message:
return frappe.render_template(self.message, context)
return frappe.render_template(self.message, context, restrict_globals=True)
def set_failed(self):
pass
@@ -875,6 +875,7 @@ def make_payment_request(**args):
party_account = get_party_account(party_type, ref_doc.get(party_type.lower()), ref_doc.company)
party_account_currency = get_account_currency(party_account)
subscription_plans = get_subscription_details(ref_doc.doctype, ref_doc.name)
pr.update(
{
"payment_gateway_account": gateway_account.get("name"),
@@ -906,12 +907,24 @@ def make_payment_request(**args):
or gateway_account.get("payment_channel", "Email") != "Email"
),
"phone_number": args.get("phone_number") if args.get("phone_number") else None,
"is_a_subscription": 1 if subscription_plans else 0,
}
)
if selected_payment_schedules:
apply_payment_references(pr, payment_reference)
if subscription_plans:
pr.set(
"subscription_plans",
[
{
"plan": row.plan,
"qty": row.qty,
}
for row in subscription_plans
],
)
# Dimensions
pr.update(
{
@@ -1225,20 +1238,25 @@ def get_dummy_message(doc):
@frappe.whitelist()
def get_subscription_details(reference_doctype: str, reference_name: str):
if reference_doctype == "Sales Invoice":
subscriptions = frappe.get_all(
"Subscription Invoice",
filters={"invoice": reference_name},
fields=["parent as sub_name"],
order_by="", # match the original query (no ORDER BY); avoid get_all's default sort
)
subscription_plans = []
for subscription in subscriptions:
plans = frappe.get_doc("Subscription", subscription.sub_name).plans
for plan in plans:
subscription_plans.append(plan)
return subscription_plans
def get_subscription_details(reference_doctype: str, reference_name: str) -> list[dict]:
frappe.has_permission(reference_doctype, "read", reference_name, throw=True)
if not frappe.get_meta(reference_doctype).has_field("subscription"):
return []
subscription = frappe.db.get_value(reference_doctype, reference_name, "subscription")
if not subscription:
return []
return frappe.get_all(
"Subscription Plan Detail",
filters={"parent": subscription, "parenttype": "Subscription", "parentfield": "plans"},
fields=[
"plan",
"qty",
],
)
@frappe.whitelist()

View File

@@ -11,12 +11,21 @@ from frappe.utils import add_days, nowdate
from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
from erpnext.accounts.doctype.payment_entry.test_payment_entry import create_payment_terms_template
from erpnext.accounts.doctype.payment_request.payment_request import make_payment_request
from erpnext.accounts.doctype.payment_request.payment_request import (
get_subscription_details,
make_payment_request,
)
from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice
from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
from erpnext.accounts.doctype.subscription.test_subscription import (
create_plan,
create_subscription,
make_plans,
)
from erpnext.buying.doctype.purchase_order.test_purchase_order import create_purchase_order
from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
from erpnext.setup.utils import get_exchange_rate
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.tests.utils import ERPNextTestSuite
PAYMENT_URL = "https://example.com/payment"
@@ -2009,3 +2018,140 @@ class TestPaymentRequestV2Gateway(ERPNextTestSuite):
call_kwargs = mock_log_error.call_args
self.assertIn("Payment Initialization Failed", str(call_kwargs))
self.assertIn("_Test Gateway", str(call_kwargs))
def test_payment_request_with_subscription(self):
make_plans()
subscription_plan = frappe.get_doc("Subscription Plan", "_Test Plan Name")
subscription_plan.payment_gateway = "_Test Gateway - INR - _TC"
subscription_plan.save()
subscription = create_subscription(
plans=[{"plan": "_Test Plan Name", "qty": 1}],
start_date=nowdate(),
generate_invoice_at="Prepaid (bill at period start)",
submit_invoice=1,
)
invoice_name = frappe.get_value(
"Sales Invoice",
{
"subscription": subscription.name,
"docstatus": 1,
"is_return": 0,
},
"name",
order_by="from_date asc",
)
payment_request = make_payment_request(
dt="Sales Invoice",
dn=invoice_name,
recipient_id="test@example.com",
)
self.assertEqual(payment_request.is_a_subscription, 1)
self.assertEqual(len(payment_request.subscription_plans), 1)
subscription_plan = payment_request.subscription_plans[0]
self.assertEqual(subscription_plan.plan, "_Test Plan Name")
self.assertEqual(subscription_plan.qty, 1)
self.assertEqual(payment_request.reference_doctype, "Sales Invoice")
self.assertEqual(payment_request.reference_name, invoice_name)
def test_payment_request_without_subscription(self):
si = create_sales_invoice()
payment_request = make_payment_request(
dt="Sales Invoice",
dn=si.name,
recipient_id="test@example.com",
)
self.assertEqual(payment_request.is_a_subscription, 0)
self.assertEqual(len(payment_request.subscription_plans), 0)
self.assertEqual(payment_request.reference_doctype, "Sales Invoice")
self.assertEqual(payment_request.reference_name, si.name)
def test_payment_request_with_subscription_for_purchase_invoice(self):
make_plans()
subscription_plan = frappe.get_doc("Subscription Plan", "_Test Plan Name")
subscription_plan.payment_gateway = "_Test Gateway - INR - _TC"
subscription_plan.save()
subscription = create_subscription(
party_type="Supplier",
party="_Test Supplier",
plans=[{"plan": "_Test Plan Name", "qty": 1}],
start_date=nowdate(),
generate_invoice_at="Prepaid (bill at period start)",
submit_invoice=1,
)
invoice_name = frappe.get_value(
"Purchase Invoice",
{
"subscription": subscription.name,
"docstatus": 1,
"is_return": 0,
},
"name",
order_by="from_date asc",
)
payment_request = make_payment_request(
dt="Purchase Invoice",
dn=invoice_name,
party_type="Supplier",
party="_Test Supplier",
recipient_id="test@example.com",
)
self.assertEqual(payment_request.is_a_subscription, 1)
self.assertEqual(len(payment_request.subscription_plans), 1)
subscription_plan = payment_request.subscription_plans[0]
self.assertEqual(subscription_plan.plan, "_Test Plan Name")
self.assertEqual(subscription_plan.qty, 1)
self.assertEqual(payment_request.reference_doctype, "Purchase Invoice")
self.assertEqual(payment_request.reference_name, invoice_name)
def test_payment_request_without_subscription_for_purchase_invoice(self):
pi = make_purchase_invoice()
payment_request = make_payment_request(
dt="Purchase Invoice",
dn=pi.name,
party_type="Supplier",
party=pi.supplier,
recipient_id="test@example.com",
)
self.assertEqual(payment_request.is_a_subscription, 0)
self.assertEqual(len(payment_request.subscription_plans), 0)
self.assertEqual(payment_request.reference_doctype, "Purchase Invoice")
self.assertEqual(payment_request.reference_name, pi.name)
def test_get_subscription_details_returns_empty_for_doctype_without_subscription_field(self):
so = make_sales_order()
self.assertEqual(get_subscription_details("Sales Order", so.name), [])
def test_get_subscription_details_requires_read_permission_on_reference(self):
si = create_sales_invoice()
restricted_user = "no-roles@example.com"
if not frappe.db.exists("User", restricted_user):
user = frappe.new_doc("User")
user.email = restricted_user
user.first_name = "No Roles"
user.send_welcome_email = 0
user.insert()
accounts_user = "accounts-user@example.com"
if not frappe.db.exists("User", accounts_user):
user = frappe.new_doc("User")
user.email = accounts_user
user.first_name = "Accounts"
user.send_welcome_email = 0
user.add_roles("Accounts User")
with self.set_user(restricted_user):
self.assertRaises(frappe.PermissionError, get_subscription_details, "Sales Invoice", si.name)
with self.set_user(accounts_user):
self.assertEqual(get_subscription_details("Sales Invoice", si.name), [])

View File

@@ -116,7 +116,7 @@
}
],
"links": [],
"modified": "2024-03-27 13:10:11.511137",
"modified": "2026-08-21 23:11:45.693762",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Payment Term",
@@ -157,11 +157,36 @@
"role": "Accounts User",
"share": 1,
"write": 1
},
{
"role": "Maintenance Manager",
"select": 1
},
{
"role": "Maintenance User",
"select": 1
},
{
"role": "Purchase Manager",
"select": 1
},
{
"role": "Purchase User",
"select": 1
},
{
"role": "Sales Manager",
"select": 1
},
{
"role": "Sales User",
"select": 1
}
],
"quick_entry": 1,
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"track_changes": 1
}
}

View File

@@ -6,8 +6,10 @@ import copy
import frappe
from frappe import _
from frappe.utils import add_days, flt, formatdate, getdate
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 (
make_closing_entries,
)
@@ -17,6 +19,8 @@ from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
from erpnext.accounts.general_ledger import check_freezing_date, is_immutable_ledger_enabled
from erpnext.accounts.utils import get_account_currency, get_fiscal_year
from erpnext.controllers.accounts_controller import AccountsController
from erpnext.stock.doctype.stock_closing_entry.stock_closing_entry import apply_unscoped_filters
from erpnext.stock.utils import get_stock_value_on
class PeriodClosingVoucher(AccountsController):
@@ -141,6 +145,121 @@ class PeriodClosingVoucher(AccountsController):
if account_currency != company_currency:
frappe.throw(_("Currency of the Closing Account must be {0}").format(company_currency))
def before_submit(self):
if not self.has_stock_transactions():
return
self.validate_stock_accounts_balance()
self.validate_stock_closing_entry()
def has_stock_transactions(self):
if not is_perpetual_inventory_enabled(self.company):
return False
return bool(
frappe.db.exists(
"Stock Ledger Entry",
{
"company": self.company,
"is_cancelled": 0,
"posting_date": ("<=", self.period_end_date),
},
)
)
def validate_stock_accounts_balance(self):
precision = frappe.get_precision("GL Entry", "debit")
account_balance = flt(self.get_stock_accounts_balance(), precision)
stock_value = flt(
get_stock_value_on(posting_date=self.period_end_date, company=self.company), precision
)
if account_balance == stock_value:
return
currency = frappe.get_cached_value("Company", self.company, "default_currency")
frappe.throw(
_(
"The closing balance {0} of the Stock Asset accounts does not match the closing value {1} of the Stock Balance report as on {2}. Resolve the difference using the Stock Ledger Variance report before closing the period."
).format(
frappe.bold(fmt_money(account_balance, currency=currency)),
frappe.bold(fmt_money(stock_value, currency=currency)),
frappe.bold(formatdate(self.period_end_date)),
),
title=_("Stock Value Mismatch"),
)
def get_stock_accounts_balance(self):
gle = frappe.qb.DocType("GL Entry")
account = frappe.qb.DocType("Account")
stock_accounts = (
frappe.qb.from_(account)
.select(account.name)
.where(
(account.account_type == "Stock")
& (account.company == self.company)
& (account.is_group == 0)
)
)
balance = (
frappe.qb.from_(gle)
.select(Sum(gle.debit - gle.credit))
.where(
(gle.company == self.company)
& (gle.is_cancelled == 0)
& (gle.posting_date <= self.period_end_date)
& gle.account.isin(stock_accounts)
)
).run()
return flt(balance[0][0]) if balance else 0.0
def validate_stock_closing_entry(self):
closing_entry = frappe.db.get_value(
"Stock Closing Entry",
apply_unscoped_filters(
{"company": self.company, "to_date": self.period_end_date, "docstatus": 1}
),
["name", "status", "modified"],
as_dict=True,
)
if not closing_entry:
frappe.throw(
_(
"Create a Stock Closing Entry for the entire company with To Date as {0} before submitting the Period Closing Voucher."
).format(frappe.bold(formatdate(self.period_end_date))),
title=_("Stock Closing Entry Required"),
)
if closing_entry.status != "Completed":
frappe.throw(
_(
"The Stock Closing Entry for {0} is not completed yet. Wait for it to complete before submitting the Period Closing Voucher."
).format(frappe.bold(formatdate(self.period_end_date))),
title=_("Stock Closing Entry In Progress"),
)
self.validate_stock_closing_entry_is_fresh(closing_entry)
def validate_stock_closing_entry_is_fresh(self, closing_entry):
sle = frappe.qb.DocType("Stock Ledger Entry")
last_change = (
frappe.qb.from_(sle)
.select(Max(sle.modified))
.where((sle.company == self.company) & (sle.posting_date <= self.period_end_date))
).run()
if last_change and last_change[0][0] and last_change[0][0] > closing_entry.modified:
frappe.throw(
_(
"Stock transactions were created or modified after the Stock Closing Entry {0} was generated. Regenerate it before submitting the Period Closing Voucher."
).format(get_link_to_form("Stock Closing Entry", closing_entry.name)),
title=_("Stock Closing Entry Outdated"),
)
def on_submit(self):
self.db_set("gle_processing_status", "In Progress")
if frappe.get_single_value("Accounts Settings", "use_legacy_controller_for_pcv"):

View File

@@ -2,7 +2,7 @@
# License: GNU General Public License v3. See license.txt
import frappe
from frappe.utils import today
from frappe.utils import flt, today
from erpnext.accounts.doctype.finance_book.test_finance_book import create_finance_book
from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journal_entry
@@ -386,6 +386,218 @@ class TestPeriodClosingVoucher(ERPNextTestSuite):
self.assertEqual(acb_figures["Cash"][key_for(cc1)], 400)
self.assertEqual(acb_figures["Cash"][key_for(cc2)], 200)
def test_stock_validations_before_period_closing(self):
from unittest.mock import patch
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
create_custom_fields(
{
"Stock Closing Entry": [
{
"fieldname": "warehouse",
"label": "Warehouse",
"fieldtype": "Link",
"options": "Warehouse",
}
]
}
)
item = make_item("Test PCV Stock Item", {"is_stock_item": 1})
se = make_stock_entry(
item_code=item.name,
qty=10,
rate=100,
to_warehouse="Stores - TPC",
company="Test PCV Company",
posting_date="2021-03-15",
)
pcv = self.make_period_closing_voucher(posting_date="2021-03-31", submit=False)
self.assertRaisesRegex(frappe.ValidationError, "Create a Stock Closing Entry", pcv.submit)
sce = frappe.get_doc(
{
"doctype": "Stock Closing Entry",
"company": "Test PCV Company",
"from_date": pcv.period_start_date,
"to_date": pcv.period_end_date,
"warehouse": "Stores - TPC",
}
).insert()
with patch("erpnext.stock.doctype.stock_closing_entry.stock_closing_entry.enqueue"):
sce.submit()
sce.db_set("status", "Completed")
pcv.reload()
self.assertRaisesRegex(frappe.ValidationError, "Create a Stock Closing Entry", pcv.submit)
frappe.db.set_value("Stock Closing Entry", sce.name, {"warehouse": None, "status": "In Progress"})
pcv.reload()
self.assertRaisesRegex(frappe.ValidationError, "is not completed yet", pcv.submit)
sce.create_stock_closing_balance_entries()
sce.db_set("status", "Completed")
sle = frappe.db.get_value(
"Stock Ledger Entry",
{"voucher_no": se.name},
["name", "stock_value_difference"],
as_dict=1,
)
frappe.db.set_value(
"Stock Ledger Entry", sle.name, "stock_value_difference", sle.stock_value_difference + 100
)
pcv.reload()
self.assertRaisesRegex(frappe.ValidationError, "does not match", pcv.submit)
frappe.db.set_value(
"Stock Ledger Entry", sle.name, "stock_value_difference", sle.stock_value_difference
)
pcv.reload()
self.assertRaisesRegex(frappe.ValidationError, "Regenerate", pcv.submit)
self.rebuild_stock_closing_balance(sce)
pcv.reload()
pcv.submit()
self.assertEqual(pcv.docstatus, 1)
def test_batch_valuation_seeded_from_stock_closing_after_period_closing(self):
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.stock.doctype.serial_and_batch_bundle.test_serial_and_batch_bundle import (
get_batch_from_bundle,
)
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
item = make_item(
"Test PCV Batch Item",
{
"is_stock_item": 1,
"has_batch_no": 1,
"create_new_batch": 1,
"batch_number_series": "TPCVB.####",
},
)
se1 = make_stock_entry(
item_code=item.name,
qty=10,
rate=100,
to_warehouse="Stores - TPC",
company="Test PCV Company",
posting_date="2021-03-15",
)
batch_no = get_batch_from_bundle(se1.items[0].serial_and_batch_bundle)
make_stock_entry(
item_code=item.name,
qty=10,
rate=200,
to_warehouse="Stores - TPC",
company="Test PCV Company",
posting_date="2021-06-15",
batch_no=batch_no,
)
pcv = self.make_period_closing_voucher(posting_date="2021-03-31", submit=False)
sce = self.make_completed_stock_closing_entry(pcv.period_start_date, pcv.period_end_date)
pcv.reload()
pcv.submit()
outward = make_stock_entry(
item_code=item.name,
qty=5,
from_warehouse="Stores - TPC",
company="Test PCV Company",
posting_date="2022-04-01",
batch_no=batch_no,
)
stock_value_difference = frappe.db.get_value(
"Stock Ledger Entry",
{"voucher_no": outward.name, "is_cancelled": 0},
"stock_value_difference",
)
self.assertEqual(flt(stock_value_difference, 2), -750.0)
self.assertRaisesRegex(
frappe.ValidationError,
"frozen",
make_stock_entry,
item_code=item.name,
qty=1,
rate=100,
to_warehouse="Stores - TPC",
company="Test PCV Company",
posting_date="2021-05-01",
)
self.assertRaisesRegex(frappe.ValidationError, "frozen", se1.cancel)
self.assertRaisesRegex(frappe.ValidationError, "closed accounting period", sce.cancel)
def test_period_closing_blocks_stale_stock_closing_entry(self):
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
item = make_item("Test PCV Stock Item", {"is_stock_item": 1})
make_stock_entry(
item_code=item.name,
qty=10,
rate=100,
to_warehouse="Stores - TPC",
company="Test PCV Company",
posting_date="2021-03-15",
)
pcv = self.make_period_closing_voucher(posting_date="2021-03-31", submit=False)
sce = self.make_completed_stock_closing_entry(pcv.period_start_date, pcv.period_end_date)
make_stock_entry(
item_code=item.name,
qty=5,
rate=100,
to_warehouse="Stores - TPC",
company="Test PCV Company",
posting_date="2021-05-01",
)
pcv.reload()
self.assertRaisesRegex(frappe.ValidationError, "Regenerate", pcv.submit)
self.rebuild_stock_closing_balance(sce)
pcv.reload()
pcv.submit()
self.assertEqual(pcv.docstatus, 1)
def make_completed_stock_closing_entry(self, from_date, to_date):
from unittest.mock import patch
sce = frappe.get_doc(
{
"doctype": "Stock Closing Entry",
"company": "Test PCV Company",
"from_date": from_date,
"to_date": to_date,
}
).insert()
with patch("erpnext.stock.doctype.stock_closing_entry.stock_closing_entry.enqueue"):
sce.submit()
sce.create_stock_closing_balance_entries()
sce.db_set("status", "Completed")
return sce
def rebuild_stock_closing_balance(self, sce):
sce.remove_stock_closing()
sce.create_stock_closing_balance_entries()
sce.db_set("status", "Completed")
def make_period_closing_voucher(self, posting_date, submit=True):
surplus_account = create_account()
cost_center = create_cost_center("Test Cost Center 1")

View File

@@ -497,6 +497,7 @@
},
{
"collapsible": 1,
"collapsible_depends_on": "eval:doc.currency && doc.currency != erpnext.get_currency(doc.company)",
"depends_on": "customer",
"fieldname": "currency_and_price_list",
"fieldtype": "Section Break",
@@ -1642,7 +1643,7 @@
"icon": "fa fa-file-text",
"is_submittable": 1,
"links": [],
"modified": "2026-06-21 12:46:13.250145",
"modified": "2026-08-21 23:11:45.029925",
"modified_by": "Administrator",
"module": "Accounts",
"name": "POS Invoice",
@@ -1685,6 +1686,14 @@
"permlevel": 1,
"read": 1,
"role": "All"
},
{
"role": "Sales Manager",
"select": 1
},
{
"role": "Sales User",
"select": 1
}
],
"row_format": "Dynamic",

View File

@@ -259,6 +259,7 @@
"fieldname": "conversion_factor",
"fieldtype": "Float",
"label": "UOM Conversion Factor",
"precision": "9",
"print_hide": 1,
"reqd": 1
},
@@ -888,7 +889,7 @@
],
"istable": 1,
"links": [],
"modified": "2026-07-18 10:00:00.000000",
"modified": "2026-08-07 17:31:31.732720",
"modified_by": "Administrator",
"module": "Accounts",
"name": "POS Invoice Item",

View File

@@ -582,7 +582,7 @@
"link_fieldname": "pos_profile"
}
],
"modified": "2026-02-10 14:24:48.597412",
"modified": "2026-08-21 23:11:45.419667",
"modified_by": "Administrator",
"module": "Accounts",
"name": "POS Profile",
@@ -606,6 +606,10 @@
"read": 1,
"report": 1,
"role": "Accounts User"
},
{
"role": "Sales Manager",
"select": 1
}
],
"row_format": "Dynamic",

View File

@@ -187,7 +187,10 @@ class PricingRule(Document):
tocheck = frappe.scrub(self.get("applicable_for", ""))
if tocheck and not self.get(tocheck):
throw(_("{0} is required").format(_(self.meta.get_label(tocheck))), frappe.MandatoryError)
throw(
_("{0} is required").format(self.meta.get_translated_label(tocheck)),
frappe.MandatoryError,
)
if self.apply_rule_on_other:
o_field = "other_" + frappe.scrub(self.apply_rule_on_other)

View File

@@ -240,10 +240,8 @@ erpnext.accounts.PurchaseInvoice = class PurchaseInvoice extends erpnext.buying.
unblock_invoice() {
const me = this;
frappe.call({
method: "erpnext.accounts.doctype.purchase_invoice.purchase_invoice.unblock_invoice",
args: { name: me.frm.doc.name },
callback: (r) => me.frm.reload_doc(),
me.frm.call("unblock_invoice", null, () => {
me.frm.reload_doc();
});
}
@@ -294,15 +292,16 @@ erpnext.accounts.PurchaseInvoice = class PurchaseInvoice extends erpnext.buying.
this.dialog.set_primary_action(__("Save"), function () {
const dialog_data = me.dialog.get_values();
frappe.call({
method: "erpnext.accounts.doctype.purchase_invoice.purchase_invoice.block_invoice",
args: {
name: me.frm.doc.name,
me.frm.call(
"block_invoice",
{
hold_comment: dialog_data.hold_comment,
release_date: dialog_data.release_date,
},
callback: (r) => me.frm.reload_doc(),
});
() => {
me.frm.reload_doc();
}
);
me.dialog.hide();
});
@@ -341,10 +340,9 @@ erpnext.accounts.PurchaseInvoice = class PurchaseInvoice extends erpnext.buying.
}
set_release_date(data) {
return frappe.call({
method: "erpnext.accounts.doctype.purchase_invoice.purchase_invoice.change_release_date",
args: data,
callback: (r) => this.frm.reload_doc(),
const me = this;
return me.frm.call("change_release_date", { release_date: data.release_date }, () => {
me.frm.reload_doc();
});
}

View File

@@ -360,6 +360,7 @@
{
"collapsible": 1,
"collapsible_depends_on": "eval:doc.on_hold",
"depends_on": "eval:doc.on_hold",
"fieldname": "sb_14",
"fieldtype": "Section Break",
"label": "Hold Invoice"
@@ -511,6 +512,7 @@
},
{
"collapsible": 1,
"collapsible_depends_on": "eval:doc.currency && doc.currency != erpnext.get_currency(doc.company)",
"fieldname": "currency_and_price_list",
"fieldtype": "Section Break",
"label": "Currency and Price List",
@@ -1694,7 +1696,7 @@
"idx": 204,
"is_submittable": 1,
"links": [],
"modified": "2026-07-12 23:54:21.263951",
"modified": "2026-08-21 23:11:46.733125",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Purchase Invoice",
@@ -1747,6 +1749,18 @@
"read": 1,
"role": "Accounts Manager",
"write": 1
},
{
"role": "Manufacturing Manager",
"select": 1
},
{
"role": "Quality Manager",
"select": 1
},
{
"role": "Stock Manager",
"select": 1
}
],
"row_format": "Dynamic",

View File

@@ -5,7 +5,7 @@
import frappe
from frappe import _, throw
from frappe.model.document import Document
from frappe.utils import cint, cstr, flt, formatdate, get_link_to_form, getdate, nowdate
from frappe.utils import DateTimeLikeObject, cint, cstr, flt, formatdate, get_link_to_form, getdate, nowdate
import erpnext
from erpnext.accounts.deferred_revenue import validate_service_stop_date
@@ -279,9 +279,7 @@ class PurchaseInvoice(BuyingController):
self.check_conversion_rate()
self.validate_credit_to_acc()
self.clear_unallocated_advances("Purchase Invoice Advance", "advances")
self.check_for_on_hold_or_closed_status(
"Purchase Order", "purchase_order", exclude_if_field="purchase_receipt"
)
self.check_purchase_order_on_hold_or_close("purchase_order", exclude_if_field="purchase_receipt")
self.validate_with_previous_doc()
self.validate_uom_is_integer("uom", "qty")
self.validate_uom_is_integer("stock_uom", "stock_qty")
@@ -297,6 +295,7 @@ class PurchaseInvoice(BuyingController):
BillingValidationService(self).validate_multiple_billing("Purchase Receipt", "pr_detail", "amount")
self.set_status()
self.validate_purchase_receipt_if_update_stock()
self.validate_exchange_rate_with_purchase_receipt()
validate_inter_company_party(
self.doctype, self.supplier, self.company, self.inter_company_invoice_reference
)
@@ -306,6 +305,9 @@ class PurchaseInvoice(BuyingController):
PurchaseTaxWithholding(self).on_validate()
self.set_percentage_received()
if self.on_hold:
self.validate_invoice_hold()
def set_percentage_received(self):
total_billed_qty = 0.0
total_received_qty = 0.0
@@ -317,6 +319,54 @@ class PurchaseInvoice(BuyingController):
if total_billed_qty and total_received_qty:
self.per_received = total_received_qty / total_billed_qty * 100
def validate_exchange_rate_with_purchase_receipt(self):
if self.is_internal_transfer() or not erpnext.is_perpetual_inventory_enabled(self.company):
return
stock_items = self.get_stock_items()
receipts = {
item.purchase_receipt
for item in self.items
if item.purchase_receipt and item.item_code in stock_items
}
if not receipts:
return
if frappe.db.get_single_value("Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate"):
return
mismatched = [
f"{frappe.bold(row.name)} ({row.conversion_rate})"
for row in frappe.get_all(
"Purchase Receipt",
filters={"name": ("in", list(receipts))},
fields=["name", "currency", "conversion_rate"],
)
if row.currency == self.currency
and flt(row.conversion_rate)
and flt(row.conversion_rate) != flt(self.conversion_rate)
]
if not mismatched:
return
frappe.throw(
_(
"Exchange rate {0} does not match the exchange rate of Purchase Receipt {1}. Use the same exchange rate as the Purchase Receipt or enable {2} in {3} to adjust the landed cost based on this invoice."
).format(
frappe.bold(self.conversion_rate),
", ".join(mismatched),
frappe.bold(_("Set Landed Cost Based on Purchase Invoice Rate")),
get_link_to_form("Buying Settings", "Buying Settings", _("Buying Settings")),
)
)
def validate_invoice_hold(self):
if self.is_return:
frappe.throw(_("Return Purchase Invoice cannot be held."))
if self.docstatus < 1:
frappe.throw(_("Purchase Invoice can be held after submitting."))
def validate_release_date(self):
if self.release_date and getdate(nowdate()) >= getdate(self.release_date):
frappe.throw(_("Release date must be in the future"))
@@ -722,9 +772,7 @@ class PurchaseInvoice(BuyingController):
super().on_cancel()
PurchaseTaxWithholding(self).on_cancel()
self.check_for_on_hold_or_closed_status(
"Purchase Order", "purchase_order", exclude_if_field="purchase_receipt"
)
self.check_purchase_order_on_hold_or_close("purchase_order", exclude_if_field="purchase_receipt")
if self.is_return and not self.update_billed_amount_in_purchase_order:
# NOTE status updating bypassed for is_return
@@ -820,14 +868,38 @@ class PurchaseInvoice(BuyingController):
def on_recurring(self, reference_doc, auto_repeat_doc):
self.due_date = None
def block_invoice(self, hold_comment=None, release_date=None):
self.db_set("on_hold", 1)
self.db_set("hold_comment", cstr(hold_comment))
@frappe.whitelist(methods=["POST"])
def block_invoice(self, hold_comment: str | None = None, release_date: DateTimeLikeObject | None = None):
self.check_permission("write")
self.on_hold = 1
self.release_date = release_date
self.validate_block_invoice()
self.db_set({"on_hold": 1, "hold_comment": cstr(hold_comment), "release_date": release_date})
@frappe.whitelist(methods=["POST"])
def unblock_invoice(self):
self.check_permission("write")
self.db_set({"on_hold": 0, "release_date": None})
@frappe.whitelist(methods=["POST"])
def change_release_date(self, release_date: DateTimeLikeObject | None = None):
self.check_permission("write")
if not self.on_hold:
frappe.throw(_("Invoice is not blocked. Block the invoice to change the release date."))
self.release_date = release_date
self.validate_block_invoice()
self.db_set("release_date", release_date)
def unblock_invoice(self):
self.db_set("on_hold", 0)
self.db_set("release_date", None)
def validate_block_invoice(self):
self.validate_invoice_hold()
if self.outstanding_amount <= 0:
frappe.throw(_("Purchase Invoice without any outstanding amount cannot be held."))
self.validate_release_date()
def set_status(self, update=False, status=None, update_modified=True):
if self.is_new():
@@ -925,24 +997,3 @@ def get_list_context(context=None):
@erpnext.allow_regional
def make_regional_gl_entries(gl_entries, doc):
return gl_entries
@frappe.whitelist()
def change_release_date(name: str, release_date: str | None = None):
pi = frappe.get_lazy_doc("Purchase Invoice", name)
pi.check_permission()
pi.db_set("release_date", release_date)
@frappe.whitelist()
def unblock_invoice(name: str):
if frappe.db.exists("Purchase Invoice", name):
pi = frappe.get_lazy_doc("Purchase Invoice", name)
pi.unblock_invoice()
@frappe.whitelist()
def block_invoice(name: str, release_date: str, hold_comment: str | None = None):
if frappe.db.exists("Purchase Invoice", name):
pi = frappe.get_lazy_doc("Purchase Invoice", name)
pi.block_invoice(hold_comment, release_date)

View File

@@ -130,6 +130,9 @@ class PurchaseInvoiceGLComposer(BaseGLComposer):
from erpnext.accounts.doctype.purchase_invoice.purchase_invoice import (
get_purchase_document_details,
)
from erpnext.stock.doctype.landed_cost_voucher.landed_cost_voucher import (
get_custom_dimension_overrides,
)
doc = self.doc
tax_service = TaxService(doc)
@@ -270,25 +273,25 @@ class PurchaseInvoiceGLComposer(BaseGLComposer):
# Amount added through landed-cost-voucher
if landed_cost_entries:
if (item.item_code, item.name) in landed_cost_entries:
for account, base_amount in landed_cost_entries[
(item.item_code, item.name)
].items():
gl_entries.append(
self.get_gl_dict(
{
"account": account,
"against": item.expense_account,
"cost_center": item.cost_center,
"remarks": doc.get("remarks") or _("Accounting Entry for Stock"),
"credit": flt(base_amount["base_amount"]),
"credit_in_account_currency": flt(base_amount["amount"]),
"credit_in_transaction_currency": item.net_amount,
"project": item.project or doc.project,
},
item=item,
)
)
for entry in landed_cost_entries.get((item.item_code, item.name), []):
if not (entry.amount or entry.base_amount):
continue
gl_dict = self.get_gl_dict(
{
"account": entry.expense_account,
"against": item.expense_account,
"cost_center": entry.dimensions.cost_center or item.cost_center,
"remarks": doc.get("remarks") or _("Accounting Entry for Stock"),
"credit": flt(entry.base_amount),
"credit_in_account_currency": flt(entry.amount),
"credit_in_transaction_currency": item.net_amount,
"project": entry.dimensions.project or item.project or doc.project,
},
item=item,
)
gl_dict.update(get_custom_dimension_overrides(entry))
gl_entries.append(gl_dict)
# sub-contracting warehouse
if flt(item.rm_supp_cost):

View File

@@ -278,14 +278,166 @@ class TestPurchaseInvoice(ERPNextTestSuite, StockTestMixin):
def test_purchase_invoice_explicit_block(self):
pi = make_purchase_invoice()
pi.block_invoice()
release_date = add_days(nowdate(), 10)
pi.block_invoice(hold_comment="Waiting for the goods", release_date=release_date)
self.assertEqual(pi.on_hold, 1)
on_hold, hold_comment, saved_release_date = frappe.db.get_value(
"Purchase Invoice", pi.name, ["on_hold", "hold_comment", "release_date"]
)
self.assertEqual(on_hold, 1)
self.assertEqual(hold_comment, "Waiting for the goods")
self.assertEqual(getdate(saved_release_date), getdate(release_date))
pi.unblock_invoice()
self.assertEqual(pi.on_hold, 0)
on_hold, saved_release_date = frappe.db.get_value(
"Purchase Invoice", pi.name, ["on_hold", "release_date"]
)
self.assertEqual(on_hold, 0)
self.assertIsNone(saved_release_date)
def test_purchase_invoice_cannot_be_held_before_submission(self):
pi = make_purchase_invoice(do_not_save=True)
pi.on_hold = 1
self.assertRaises(frappe.ValidationError, pi.save)
pi.on_hold = 0
pi.save()
pi.submit()
pi.block_invoice()
self.assertEqual(frappe.db.get_value("Purchase Invoice", pi.name, "on_hold"), 1)
def test_return_purchase_invoice_cannot_be_held(self):
from erpnext.controllers.sales_and_purchase_return import make_return_doc
pi = make_purchase_invoice()
return_pi = make_return_doc(pi.doctype, pi.name)
return_pi.on_hold = 1
self.assertRaisesRegex(frappe.ValidationError, "cannot be held", return_pi.save)
return_pi.on_hold = 0
return_pi.save()
return_pi.submit()
self.assertRaisesRegex(frappe.ValidationError, "cannot be held", return_pi.block_invoice)
def test_return_purchase_invoice_is_not_affected_by_hold_validations(self):
from erpnext.controllers.sales_and_purchase_return import make_return_doc
pi = make_purchase_invoice()
# a return has a negative outstanding amount, which must not be mistaken
# for an invalid hold on a document that was never held
return_pi = make_return_doc(pi.doctype, pi.name)
return_pi.save()
return_pi.submit()
self.assertEqual(return_pi.docstatus, 1)
self.assertEqual(return_pi.on_hold, 0)
self.assertLess(return_pi.outstanding_amount, 0)
def test_settled_purchase_invoice_cannot_be_held(self):
pi = make_purchase_invoice()
pe = get_payment_entry("Purchase Invoice", dn=pi.name, bank_account="_Test Bank - _TC")
pe.reference_no = "1"
pe.reference_date = nowdate()
pe.save()
pe.submit()
pi.reload()
self.assertEqual(pi.outstanding_amount, 0)
self.assertRaises(frappe.ValidationError, pi.block_invoice)
self.assertEqual(frappe.db.get_value("Purchase Invoice", pi.name, "on_hold"), 0)
def test_release_date_of_held_invoice_must_be_in_future(self):
pi = make_purchase_invoice()
self.assertRaises(frappe.ValidationError, pi.block_invoice, "Hold", add_days(nowdate(), -1))
self.assertRaises(frappe.ValidationError, pi.block_invoice, "Hold", nowdate())
def test_rejected_hold_does_not_partially_update_invoice(self):
pi = make_purchase_invoice()
self.assertRaises(frappe.ValidationError, pi.block_invoice, "Hold", add_days(nowdate(), -1))
pi.reload()
self.assertEqual(pi.on_hold, 0)
self.assertIsNone(pi.release_date)
def test_change_release_date_of_held_invoice(self):
pi = make_purchase_invoice()
pi.block_invoice(hold_comment="Hold", release_date=add_days(nowdate(), 10))
new_release_date = add_days(nowdate(), 20)
pi.change_release_date(new_release_date)
self.assertEqual(
getdate(frappe.db.get_value("Purchase Invoice", pi.name, "release_date")),
getdate(new_release_date),
)
self.assertRaises(frappe.ValidationError, pi.change_release_date, add_days(nowdate(), -1))
def test_release_date_cannot_be_changed_on_an_invoice_that_is_not_held(self):
pi = make_purchase_invoice()
self.assertRaisesRegex(
frappe.ValidationError,
"Invoice is not blocked",
pi.change_release_date,
add_days(nowdate(), 10),
)
self.assertIsNone(frappe.db.get_value("Purchase Invoice", pi.name, "release_date"))
def test_hold_methods_are_whitelisted_document_methods(self):
import erpnext.accounts.doctype.purchase_invoice.purchase_invoice as purchase_invoice_module
pi = frappe.new_doc("Purchase Invoice")
for method in ("block_invoice", "unblock_invoice", "change_release_date"):
# raises if the method is not whitelisted for client side calls
pi.is_whitelisted(method)
self.assertFalse(
hasattr(purchase_invoice_module, method),
f"{method} should only be exposed as a document method",
)
def test_hold_methods_require_write_permission(self):
pi = make_purchase_invoice()
user = "test_pi_hold_permission@example.com"
if not frappe.db.exists("User", user):
frappe.get_doc(
{
"doctype": "User",
"email": user,
"first_name": "Test PI Hold",
"roles": [{"role": "Employee"}],
}
).insert(ignore_permissions=True)
frappe.set_user(user)
try:
self.assertRaises(frappe.PermissionError, pi.block_invoice)
self.assertRaises(frappe.PermissionError, pi.unblock_invoice)
self.assertRaises(frappe.PermissionError, pi.change_release_date, add_days(nowdate(), 10))
finally:
frappe.set_user("Administrator")
self.assertEqual(frappe.db.get_value("Purchase Invoice", pi.name, "on_hold"), 0)
def test_gl_entries_with_perpetual_inventory_against_pr(self):
pr = make_purchase_receipt(
company="_Test Company with perpetual inventory",
@@ -431,6 +583,12 @@ class TestPurchaseInvoice(ERPNextTestSuite, StockTestMixin):
)
frappe.db.set_single_value("Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 0)
self.addCleanup(
frappe.db.set_single_value,
"Buying Settings",
"set_landed_cost_based_on_purchase_invoice_rate",
original_value,
)
pr = make_purchase_receipt(
company="_Test Company with perpetual inventory",
@@ -442,25 +600,15 @@ class TestPurchaseInvoice(ERPNextTestSuite, StockTestMixin):
pi = create_purchase_invoice(pr.name)
pi.conversion_rate = 80
self.assertRaises(frappe.ValidationError, pi.insert)
pi.conversion_rate = 70
pi.insert()
pi.submit()
# Get exchnage gain and loss account
exchange_gain_loss_account = frappe.db.get_value("Company", pi.company, "exchange_gain_loss_account")
# fetching the latest GL Entry with exchange gain and loss account account
amount = frappe.db.get_value(
"GL Entry", {"account": exchange_gain_loss_account, "voucher_no": pi.name}, "debit"
)
discrepancy_caused_by_exchange_rate_diff = abs(
pi.items[0].base_net_amount - pr.items[0].base_net_amount
)
self.assertEqual(discrepancy_caused_by_exchange_rate_diff, amount)
frappe.db.set_single_value(
"Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", original_value
self.assertFalse(
frappe.db.exists("GL Entry", {"account": exchange_gain_loss_account, "voucher_no": pi.name})
)
def test_purchase_invoice_with_exchange_rate_difference_for_non_stock_item(self):
@@ -468,7 +616,17 @@ class TestPurchaseInvoice(ERPNextTestSuite, StockTestMixin):
make_purchase_invoice as create_purchase_invoice,
)
# Creating Purchase Invoice with USD currency
original_value = frappe.db.get_single_value(
"Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate"
)
frappe.db.set_single_value("Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 0)
self.addCleanup(
frappe.db.set_single_value,
"Buying Settings",
"set_landed_cost_based_on_purchase_invoice_rate",
original_value,
)
pr = frappe.new_doc("Purchase Receipt")
pr.currency = "USD"
pr.company = "_Test Company with perpetual inventory"
@@ -482,34 +640,20 @@ class TestPurchaseInvoice(ERPNextTestSuite, StockTestMixin):
"rate": 100,
},
)
pr.append(
"items",
{"item_code": "_Test Item", "qty": 1, "rate": 5, "warehouse": "Stores - TCP1"},
)
pr.insert()
pr.submit()
# Createing purchase invoice against Purchase Receipt
pi = create_purchase_invoice(pr.name)
pi.conversion_rate = 70
pi.credit_to = "_Test Payable USD - TCP1"
pi.insert()
pi.submit()
# Get exchnage gain and loss account
exchange_gain_loss_account = frappe.db.get_value("Company", pi.company, "exchange_gain_loss_account")
# fetching the latest GL Entry with exchange gain and loss account account
amount = frappe.db.get_value(
"GL Entry", {"account": exchange_gain_loss_account, "voucher_no": pi.name}, "credit"
self.assertFalse(
frappe.db.exists("GL Entry", {"account": exchange_gain_loss_account, "voucher_no": pi.name})
)
discrepancy_caused_by_exchange_rate_diff = abs(
pi.items[1].base_net_amount - pr.items[1].base_net_amount
)
self.assertEqual(flt(discrepancy_caused_by_exchange_rate_diff, 2), amount)
def test_purchase_invoice_change_naming_series(self):
pi = frappe.copy_doc(self.globalTestRecords["Purchase Invoice"][1])
pi.insert()

View File

@@ -241,6 +241,7 @@
"fieldname": "conversion_factor",
"fieldtype": "Float",
"label": "UOM Conversion Factor",
"precision": "9",
"print_hide": 1,
"read_only": 1,
"reqd": 1
@@ -1032,7 +1033,7 @@
"idx": 1,
"istable": 1,
"links": [],
"modified": "2026-07-18 10:00:00.000000",
"modified": "2026-08-07 17:31:31.732720",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Purchase Invoice Item",

View File

@@ -77,7 +77,7 @@
"icon": "fa fa-money",
"idx": 1,
"links": [],
"modified": "2024-03-27 13:10:26.945131",
"modified": "2026-08-21 23:11:47.506282",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Purchase Taxes and Charges Template",
@@ -104,12 +104,29 @@
{
"read": 1,
"role": "Purchase User"
},
{
"role": "Accounts Manager",
"select": 1
},
{
"role": "Accounts User",
"select": 1
},
{
"role": "Manufacturing Manager",
"select": 1
},
{
"role": "Stock Manager",
"select": 1
}
],
"row_format": "Dynamic",
"show_title_field_in_link": 1,
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"title_field": "title",
"track_changes": 1
}
}

View File

@@ -587,7 +587,12 @@ erpnext.accounts.SalesInvoiceController = class SalesInvoiceController extends (
super.set_dynamic_labels();
this.frm.events.hide_fields(this.frm);
const hide_update_stock = cint(this.frm.doc.is_debit_note) || cint(this.frm.doc.has_subcontracted);
this.frm.set_df_property("update_stock", "hidden", hide_update_stock);
// frm.set_df_property mutates a per-document copy, not the doctype's shared field
// metadata, so this always reflects the original (Customize Form) hidden value.
const hidden_by_customization = cint(
frappe.meta.get_docfield("Sales Invoice", "update_stock")?.hidden
);
this.frm.set_df_property("update_stock", "hidden", hide_update_stock || hidden_by_customization);
}
items_on_form_rendered() {

View File

@@ -170,6 +170,10 @@
"shipping_address_section",
"shipping_address_name",
"shipping_address",
"shipping_contact_person",
"shipping_contact_display",
"shipping_contact_mobile",
"shipping_contact_email",
"shipping_addr_col_break",
"dispatch_address_name",
"dispatch_address",
@@ -297,7 +301,6 @@
"hide_days": 1,
"hide_seconds": 1,
"label": "Tax Id",
"print_hide": 1,
"read_only": 1
},
{
@@ -590,6 +593,46 @@
"print_hide": 1,
"read_only": 1
},
{
"fieldname": "shipping_contact_person",
"fieldtype": "Link",
"hide_days": 1,
"hide_seconds": 1,
"label": "Shipping Contact Person",
"options": "Contact",
"print_hide": 1
},
{
"fetch_from": "shipping_contact_person.full_name",
"fieldname": "shipping_contact_display",
"fieldtype": "Small Text",
"hide_days": 1,
"hide_seconds": 1,
"label": "Shipping Contact",
"read_only": 1
},
{
"fetch_from": "shipping_contact_person.mobile_no",
"fieldname": "shipping_contact_mobile",
"fieldtype": "Small Text",
"hide_days": 1,
"hide_seconds": 1,
"label": "Shipping Contact Mobile No",
"options": "Phone",
"read_only": 1
},
{
"fetch_from": "shipping_contact_person.email_id",
"fieldname": "shipping_contact_email",
"fieldtype": "Data",
"hidden": 1,
"hide_days": 1,
"hide_seconds": 1,
"label": "Shipping Contact Email",
"options": "Email",
"print_hide": 1,
"read_only": 1
},
{
"fieldname": "company_address",
"fieldtype": "Link",
@@ -610,6 +653,7 @@
},
{
"collapsible": 1,
"collapsible_depends_on": "eval:doc.currency && doc.currency != erpnext.get_currency(doc.company)",
"depends_on": "customer",
"fieldname": "currency_and_price_list",
"fieldtype": "Section Break",
@@ -1940,6 +1984,7 @@
"allow_on_submit": 1,
"fieldname": "additional_discount_account",
"fieldtype": "Link",
"hidden": 1,
"label": "Discount Account",
"options": "Account"
},
@@ -2360,7 +2405,7 @@
"link_fieldname": "consolidated_invoice"
}
],
"modified": "2026-06-21 12:46:13.250145",
"modified": "2026-08-14 12:43:19.480555",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Invoice",

View File

@@ -29,6 +29,7 @@ from erpnext.setup.doctype.company.company import update_company_current_month_s
from erpnext.stock.doctype.delivery_note.services.billing_status import (
update_billed_amount_based_on_so,
)
from erpnext.stock.utils import get_bin_qty_map
from .services.fixed_assets import FixedAssetService
from .services.inter_company import (
@@ -201,6 +202,10 @@ class SalesInvoice(SellingController):
set_warehouse: DF.Link | None
shipping_address: DF.TextEditor | None
shipping_address_name: DF.Link | None
shipping_contact_display: DF.SmallText | None
shipping_contact_email: DF.Data | None
shipping_contact_mobile: DF.SmallText | None
shipping_contact_person: DF.Link | None
shipping_rule: DF.Link | None
status: DF.Literal[
"",
@@ -609,6 +614,7 @@ class SalesInvoice(SellingController):
"percent_join_field": "sales_order",
"status_field": "delivery_status",
"keyword": "Delivered",
"exclude_field": "skip_delivery",
"second_source_dt": "Delivery Note Item",
"second_source_field": "qty",
"second_join_field": "so_detail",
@@ -991,11 +997,17 @@ class SalesInvoice(SellingController):
)
def update_current_stock(self):
bin_qty_map = get_bin_qty_map(self.items + self.packed_items)
for item in self.items:
item.set_actual_qty()
if item.item_code and item.warehouse:
bin_data = bin_qty_map.get((item.item_code, item.warehouse))
item.actual_qty = bin_data.actual_qty if bin_data else 0
for packed_item in self.packed_items:
packed_item.set_actual_and_projected_qty()
bin_data = bin_qty_map.get((packed_item.item_code, packed_item.warehouse))
packed_item.actual_qty = bin_data.actual_qty if bin_data else 0
packed_item.projected_qty = bin_data.projected_qty if bin_data else 0
def update_packing_list(self):
if cint(self.update_stock) == 1:
@@ -1165,6 +1177,7 @@ class SalesInvoice(SellingController):
child_tables = {
"items": ("income_account", "expense_account", "discount_account"),
"taxes": ("account_head",),
"payments": ("account",),
}
self.needs_repost = self.check_if_fields_updated(fields_to_check, child_tables)
if self.needs_repost:

View File

@@ -114,6 +114,14 @@ class TestSalesInvoice(ERPNextTestSuite):
si.save()
self.assertEqual(si.items[0].qty, 1)
@ERPNextTestSuite.change_settings("Selling Settings", {"allow_negative_rates_for_items": 1})
def test_sales_invoice_negative_grand_total_still_blocked_with_setting(self):
"""allow_negative_rates_for_items must not bypass the >=0 guard for a non-return
invoice, since invoices post to the GL (unlike Sales Order)."""
si = create_sales_invoice(qty=1, rate=100, do_not_save=True)
si.append("items", {"item_code": "_Test Item 2", "qty": 1, "rate": -150})
self.assertRaises(frappe.ValidationError, si.save)
def test_timestamp_change(self):
w = frappe.copy_doc(self.globalTestRecords["Sales Invoice"][0])
w.docstatus = 0

View File

@@ -249,6 +249,7 @@
"fieldname": "conversion_factor",
"fieldtype": "Float",
"label": "UOM Conversion Factor",
"precision": "9",
"print_hide": 1,
"reqd": 1
},
@@ -886,6 +887,7 @@
"allow_on_submit": 1,
"fieldname": "discount_account",
"fieldtype": "Link",
"hidden": 1,
"label": "Discount Account",
"options": "Account"
},
@@ -1066,7 +1068,7 @@
"idx": 1,
"istable": 1,
"links": [],
"modified": "2026-07-18 10:00:00.000000",
"modified": "2026-08-11 12:00:00.000000",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Invoice Item",

View File

@@ -114,15 +114,6 @@ class SalesInvoiceItem(Document):
)
)
def set_actual_qty(self):
if self.item_code and self.warehouse:
self.actual_qty = (
frappe.db.get_value(
"Bin", {"item_code": self.item_code, "warehouse": self.warehouse}, "actual_qty"
)
or 0
)
def set_income_account_for_fixed_asset(self, company: str):
"""Set income account for fixed asset item based on company's disposal account and cost center."""
if not self.is_fixed_asset:

View File

@@ -1,5 +1,6 @@
{
"actions": [],
"allow_bulk_edit": 1,
"creation": "2016-05-08 23:49:38.842621",
"doctype": "DocType",
"editable_grid": 1,
@@ -17,6 +18,7 @@
],
"fields": [
{
"allow_on_submit": 1,
"fieldname": "mode_of_payment",
"fieldtype": "Link",
"in_list_view": 1,
@@ -39,6 +41,7 @@
"fieldtype": "Column Break"
},
{
"allow_on_submit": 1,
"fieldname": "account",
"fieldtype": "Link",
"label": "Account",
@@ -47,6 +50,7 @@
"read_only": 1
},
{
"allow_on_submit": 1,
"fetch_from": "mode_of_payment.type",
"fieldname": "type",
"fieldtype": "Read Only",
@@ -85,7 +89,7 @@
],
"istable": 1,
"links": [],
"modified": "2026-02-16 20:46:34.592604",
"modified": "2026-07-29 16:44:54.482826",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Invoice Payment",

View File

@@ -79,7 +79,7 @@
"icon": "fa fa-money",
"idx": 1,
"links": [],
"modified": "2024-03-27 13:10:38.343481",
"modified": "2026-08-21 23:11:48.797423",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Taxes and Charges Template",
@@ -113,12 +113,33 @@
"role": "Sales Master Manager",
"share": 1,
"write": 1
},
{
"role": "Delivery Manager",
"select": 1
},
{
"role": "Delivery User",
"select": 1
},
{
"role": "Maintenance Manager",
"select": 1
},
{
"role": "Maintenance User",
"select": 1
},
{
"role": "Stock Manager",
"select": 1
}
],
"row_format": "Dynamic",
"show_title_field_in_link": 1,
"sort_field": "creation",
"sort_order": "ASC",
"states": [],
"title_field": "title",
"track_changes": 1
}
}

View File

@@ -7,10 +7,9 @@ def get_data():
"non_standard_fieldnames": {
"Tax Rule": "sales_tax_template",
"Subscription": "sales_tax_template",
"Restaurant": "default_tax_template",
},
"transactions": [
{"label": _("Transactions"), "items": ["Sales Invoice", "Sales Order", "Delivery Note"]},
{"label": _("References"), "items": ["POS Profile", "Subscription", "Restaurant", "Tax Rule"]},
{"label": _("References"), "items": ["POS Profile", "Subscription", "Tax Rule"]},
],
}

View File

@@ -149,7 +149,7 @@
"icon": "fa fa-truck",
"idx": 1,
"links": [],
"modified": "2026-07-22 14:53:27.315435",
"modified": "2026-08-21 23:11:49.532098",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Shipping Rule",
@@ -195,6 +195,38 @@
"role": "Sales Master Manager",
"share": 1,
"write": 1
},
{
"role": "Delivery Manager",
"select": 1
},
{
"role": "Delivery User",
"select": 1
},
{
"role": "Maintenance Manager",
"select": 1
},
{
"role": "Maintenance User",
"select": 1
},
{
"role": "Manufacturing Manager",
"select": 1
},
{
"role": "Purchase Manager",
"select": 1
},
{
"role": "Purchase User",
"select": 1
},
{
"role": "Stock Manager",
"select": 1
}
],
"row_format": "Dynamic",

View File

@@ -161,7 +161,14 @@ class ShippingRule(Document):
)
shipping_charge["add_deduct_tax"] = "Add"
existing_shipping_charge = doc.get("taxes", filters=shipping_charge)
shipping_charge_filters = shipping_charge.copy()
if not self.cost_center:
shipping_charge_filters["cost_center"] = (
"in",
(None, "", erpnext.get_default_cost_center(doc.company)),
)
existing_shipping_charge = doc.get("taxes", filters=shipping_charge_filters)
if existing_shipping_charge:
# take the last record found
existing_shipping_charge[-1].tax_amount = shipping_amount

View File

@@ -278,6 +278,9 @@ class Subscription(Document):
"""
Sets the status of the `Subscription`
"""
if self.status == STATUS_CANCELLED:
return
self._set_current_invoice_dates()
if self.is_trialling():
self.status = STATUS_TRIALING
@@ -673,7 +676,7 @@ class Subscription(Document):
if self.cancel_at_period_end and (
getdate(posting_date) >= getdate(self.next_billing_period_end)
or getdate(posting_date) >= getdate(self.end_date)
or (self.end_date and getdate(posting_date) >= getdate(self.end_date))
):
self.cancel_subscription()

View File

@@ -779,6 +779,38 @@ class TestSubscription(ERPNextTestSuite):
subscription.reload()
self.assertEqual(subscription.status, "Active")
def test_cancelled_subscription_stays_cancelled_after_payment_and_reprocess(self):
# https://github.com/frappe/erpnext/issues/57761
subscription = create_subscription(
start_date=nowdate(),
generate_invoice_at="Prepaid (bill at period start)",
submit_invoice=1,
cancel_at_period_end=1,
)
subscription.process(posting_date=nowdate())
invoice = subscription.get_current_invoice()
self.assertGreater(invoice.outstanding_amount, 0)
subscription.cancel_subscription()
self.assertEqual(subscription.status, "Cancelled")
cancelation_date = getdate(subscription.cancelation_date)
self.assertIsNotNone(cancelation_date)
payment_entry = get_payment_entry(invoice.doctype, invoice.name, bank_account="_Test Bank - _TC")
payment_entry.reference_no = "12345"
payment_entry.reference_date = nowdate()
payment_entry.submit()
subscription.reload()
self.assertEqual(subscription.status, "Cancelled")
self.assertEqual(getdate(subscription.cancelation_date), cancelation_date)
invoice_count = len(subscription.invoices)
subscription.process()
subscription.reload()
self.assertEqual(subscription.status, "Cancelled")
self.assertEqual(len(subscription.invoices), invoice_count)
def test_first_invoice_generated_on_create_for_prepaid(self):
subscription = create_subscription(
start_date=nowdate(),

View File

@@ -29,7 +29,7 @@
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2024-03-27 13:10:51.976600",
"modified": "2026-08-21 23:11:50.740962",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Tax Category",
@@ -68,11 +68,68 @@
"report": 1,
"role": "Accounts User",
"share": 1
},
{
"role": "Delivery Manager",
"select": 1
},
{
"role": "Delivery User",
"select": 1
},
{
"role": "Item Manager",
"select": 1
},
{
"role": "Maintenance Manager",
"select": 1
},
{
"role": "Maintenance User",
"select": 1
},
{
"role": "Manufacturing Manager",
"select": 1
},
{
"role": "Purchase Manager",
"select": 1
},
{
"role": "Purchase Master Manager",
"select": 1
},
{
"role": "Purchase User",
"select": 1
},
{
"role": "Sales Manager",
"select": 1
},
{
"role": "Sales Master Manager",
"select": 1
},
{
"role": "Sales User",
"select": 1
},
{
"role": "Stock Manager",
"select": 1
},
{
"role": "Stock User",
"select": 1
}
],
"quick_entry": 1,
"row_format": "Dynamic",
"sort_field": "creation",
"sort_order": "DESC",
"states": [],
"track_changes": 1
}
}

View File

@@ -100,7 +100,7 @@
],
"index_web_pages_for_search": 1,
"links": [],
"modified": "2025-07-30 07:13:51.785735",
"modified": "2026-08-21 23:11:50.979676",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Tax Withholding Category",
@@ -142,6 +142,26 @@
"role": "Accounts User",
"share": 1,
"write": 1
},
{
"role": "Item Manager",
"select": 1
},
{
"role": "Purchase Manager",
"select": 1
},
{
"role": "Purchase Master Manager",
"select": 1
},
{
"role": "Sales Master Manager",
"select": 1
},
{
"role": "Sales User",
"select": 1
}
],
"row_format": "Dynamic",

View File

@@ -21,7 +21,7 @@
"grid_page_length": 50,
"index_web_pages_for_search": 1,
"links": [],
"modified": "2025-06-29 05:25:50.243710",
"modified": "2026-08-21 23:11:51.176158",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Tax Withholding Group",
@@ -39,6 +39,30 @@
"role": "System Manager",
"share": 1,
"write": 1
},
{
"role": "Accounts Manager",
"select": 1
},
{
"role": "Accounts User",
"select": 1
},
{
"role": "Purchase Manager",
"select": 1
},
{
"role": "Purchase Master Manager",
"select": 1
},
{
"role": "Sales Master Manager",
"select": 1
},
{
"role": "Sales User",
"select": 1
}
],
"row_format": "Dynamic",

View File

@@ -19,6 +19,6 @@
"modified": "2026-07-09 16:13:49.623613",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Party Account (Standard)",
"name": "Party Account - Accounts",
"owner": "Administrator"
}

View File

@@ -27,6 +27,6 @@
"modified": "2026-07-10 11:26:57.841200",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Payment Entry (Standard)",
"name": "Payment Entry - Accounts",
"owner": "Administrator"
}

View File

@@ -71,6 +71,6 @@
"modified": "2026-07-20 15:56:46.025286",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Purchase Invoice (Standard)",
"name": "Purchase Invoice - Accounts",
"owner": "Administrator"
}

View File

@@ -63,6 +63,6 @@
"modified": "2026-07-20 15:32:43.080034",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Invoice (Standard)",
"name": "Sales Invoice - Accounts",
"owner": "Administrator"
}

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